Add internal grant endpoint + temp-password / force-change flow
- /api/internal/grant: secret-auth endpoint for payment-router to provision access on a paid order — find-or-create user (emailVerified, temp password, mustChangePassword), enroll by course slug list, AccessLog, delivery email. Idempotent by order_id. - User.mustChangePassword flag (+ migration); (student) layout redirects flagged users to /change-password (forced first-login change). - email.ts: sendCourseGrantEmail (temp password for new buyers). - middleware: /api/internal is public (own secret auth). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { redirect } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { LogoutButton } from "@/components/layout/logout-button";
|
||||
@@ -10,6 +11,13 @@ export default async function StudentLayout({ children }: { children: React.Reac
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) redirect("/login");
|
||||
|
||||
// Force password change for auto-provisioned buyers (temp password)
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { mustChangePassword: true },
|
||||
});
|
||||
if (dbUser?.mustChangePassword) redirect("/change-password");
|
||||
|
||||
// Maintenance mode: non-admin users see the maintenance page
|
||||
if (session.user.role !== "admin") {
|
||||
const maintenance = await getSetting("maintenanceMode");
|
||||
|
||||
@@ -30,6 +30,10 @@ export async function changePasswordAction(_prevState: unknown, formData: FormDa
|
||||
where: { id: account.id },
|
||||
data: { password: hash },
|
||||
});
|
||||
await prisma.user.update({
|
||||
where: { id: session.user.id },
|
||||
data: { mustChangePassword: false },
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendCourseGrantEmail } from "@/lib/email";
|
||||
import bcrypt from "bcryptjs";
|
||||
import crypto from "crypto";
|
||||
|
||||
/**
|
||||
* Internal access-provisioning endpoint, called by payment-router on a paid order.
|
||||
* Auth: shared secret in `x-internal-secret`. Idempotent by order_id (AccessLog note).
|
||||
*
|
||||
* Body: { email, name?, course_slugs: string[], order_id, payment_system? }
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const secret = process.env.INTERNAL_GRANT_SECRET;
|
||||
if (!secret || request.headers.get("x-internal-secret") !== secret) {
|
||||
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
email?: string;
|
||||
name?: string;
|
||||
course_slugs?: string[];
|
||||
order_id?: string;
|
||||
};
|
||||
try {
|
||||
body = (await request.json()) as typeof body;
|
||||
} catch {
|
||||
return NextResponse.json({ ok: false, error: "bad_json" }, { status: 400 });
|
||||
}
|
||||
|
||||
const email = (body.email ?? "").trim().toLowerCase();
|
||||
const name = (body.name ?? "").trim();
|
||||
const slugs = Array.isArray(body.course_slugs)
|
||||
? body.course_slugs.filter((s) => typeof s === "string" && s.trim())
|
||||
: [];
|
||||
const orderId = (body.order_id ?? "").trim();
|
||||
|
||||
if (!email || slugs.length === 0 || !orderId) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "missing_fields", need: ["email", "course_slugs", "order_id"] },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Idempotency: this order already provisioned?
|
||||
const marker = `order:${orderId}`;
|
||||
const already = await prisma.accessLog.findFirst({ where: { note: { contains: marker } } });
|
||||
if (already) {
|
||||
return NextResponse.json({ ok: true, idempotent: true });
|
||||
}
|
||||
|
||||
// Resolve course slugs → ids
|
||||
const courses = await prisma.course.findMany({
|
||||
where: { slug: { in: slugs } },
|
||||
select: { id: true, title: true, slug: true },
|
||||
});
|
||||
const resolvedSlugs = new Set(courses.map((c) => c.slug));
|
||||
const unresolved = slugs.filter((s) => !resolvedSlugs.has(s));
|
||||
if (courses.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "no_courses_resolved", slugs },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
// Find or create user
|
||||
let user = await prisma.user.findFirst({
|
||||
where: { email: { equals: email, mode: "insensitive" } },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
let tempPassword: string | null = null;
|
||||
if (!user) {
|
||||
tempPassword = "sb-" + crypto.randomBytes(3).toString("hex");
|
||||
const hash = await bcrypt.hash(tempPassword, 10);
|
||||
user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
name: name || email,
|
||||
emailVerified: true,
|
||||
mustChangePassword: true,
|
||||
accounts: {
|
||||
create: { accountId: email, providerId: "credential", password: hash },
|
||||
},
|
||||
},
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
}
|
||||
|
||||
// Enroll + audit log
|
||||
await prisma.courseEnrollment.createMany({
|
||||
data: courses.map((c) => ({ userId: user!.id, courseId: c.id })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
await prisma.accessLog.createMany({
|
||||
data: courses.map((c) => ({
|
||||
courseId: c.id,
|
||||
userId: user!.id,
|
||||
action: "granted",
|
||||
method: "auto-payment",
|
||||
note: `auto-payment ${marker}`,
|
||||
})),
|
||||
});
|
||||
|
||||
// Delivery email (temp password for new buyers, plain "added" for existing)
|
||||
await sendCourseGrantEmail(
|
||||
email,
|
||||
user.name ?? name,
|
||||
courses.map((c) => c.title),
|
||||
tempPassword,
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
created: tempPassword !== null,
|
||||
granted: courses.map((c) => c.slug),
|
||||
unresolved,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"use server";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
// Принудительная смена пароля для покупателей с временным паролем.
|
||||
// Текущий пароль не спрашиваем — пользователь уже аутентифицирован сессией.
|
||||
export async function forceChangePasswordAction(_prevState: unknown, formData: FormData) {
|
||||
const next = (formData.get("newPassword") as string) ?? "";
|
||||
const confirm = (formData.get("confirmPassword") as string) ?? "";
|
||||
|
||||
if (!next || !confirm) return { error: "Заполните оба поля" };
|
||||
if (next !== confirm) return { error: "Пароли не совпадают" };
|
||||
if (next.length < 8) return { error: "Пароль должен быть не короче 8 символов" };
|
||||
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return { error: "Сессия истекла, войдите заново" };
|
||||
|
||||
const account = await prisma.account.findFirst({
|
||||
where: { userId: session.user.id, providerId: "credential" },
|
||||
});
|
||||
if (!account) return { error: "Аккаунт не найден" };
|
||||
|
||||
const hash = await bcrypt.hash(next, 10);
|
||||
await prisma.account.update({ where: { id: account.id }, data: { password: hash } });
|
||||
await prisma.user.update({
|
||||
where: { id: session.user.id },
|
||||
data: { mustChangePassword: false },
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { forceChangePasswordAction } from "./actions";
|
||||
|
||||
export function ForceChangeForm() {
|
||||
const router = useRouter();
|
||||
const [state, formAction, isPending] = useActionState(forceChangePasswordAction, null);
|
||||
|
||||
useEffect(() => {
|
||||
if (state && "success" in state && state.success) {
|
||||
router.push("/dashboard");
|
||||
router.refresh();
|
||||
}
|
||||
}, [state, router]);
|
||||
|
||||
const inputStyle = {
|
||||
width: "100%",
|
||||
padding: "0.5rem 0.75rem",
|
||||
fontSize: "16px",
|
||||
border: "2px solid var(--border)",
|
||||
background: "var(--background)",
|
||||
outline: "none",
|
||||
fontFamily: "inherit",
|
||||
} as React.CSSProperties;
|
||||
|
||||
return (
|
||||
<form action={formAction} className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-bold uppercase tracking-widest" style={{ color: "var(--muted-foreground)" }}>
|
||||
Новый пароль
|
||||
</label>
|
||||
<input type="password" name="newPassword" required minLength={8} style={inputStyle} placeholder="Минимум 8 символов" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-bold uppercase tracking-widest" style={{ color: "var(--muted-foreground)" }}>
|
||||
Повторите пароль
|
||||
</label>
|
||||
<input type="password" name="confirmPassword" required minLength={8} style={inputStyle} placeholder="Ещё раз" />
|
||||
</div>
|
||||
{state && "error" in state && state.error && (
|
||||
<p className="text-xs py-2 px-3" style={{ border: "2px solid oklch(0.577 0.245 27.325)", color: "oklch(0.577 0.245 27.325)" }}>
|
||||
{state.error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" disabled={isPending} className="btn-aubade btn-aubade-accent w-full py-2 text-sm" style={{ opacity: isPending ? 0.6 : 1 }}>
|
||||
{isPending ? "Сохранение..." : "Сохранить и продолжить"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { ForceChangeForm } from "./force-change-form";
|
||||
|
||||
export default async function ChangePasswordPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) redirect("/login");
|
||||
|
||||
return (
|
||||
<div
|
||||
className="min-h-screen flex items-center justify-center p-4"
|
||||
style={{ backgroundColor: "var(--background)" }}
|
||||
>
|
||||
<div className="w-full max-w-sm">
|
||||
<h1 className="text-xl font-bold mb-2" style={{ color: "var(--foreground)" }}>
|
||||
Задайте свой пароль
|
||||
</h1>
|
||||
<p className="text-sm mb-6" style={{ color: "var(--muted-foreground)" }}>
|
||||
Вы вошли с временным паролем. Перед началом работы задайте постоянный — это займёт минуту.
|
||||
</p>
|
||||
<ForceChangeForm />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user