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:
@@ -18,3 +18,6 @@ TURNSTILE_SECRET_KEY=""
|
|||||||
|
|
||||||
# Kinescope API
|
# Kinescope API
|
||||||
KINESCOPE_API_KEY=""
|
KINESCOPE_API_KEY=""
|
||||||
|
|
||||||
|
# Internal access-provisioning (payment-router → /api/internal/grant)
|
||||||
|
INTERNAL_GRANT_SECRET=""
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- Add force-password-change flag (set for auto-provisioned buyers with a temp password)
|
||||||
|
ALTER TABLE "User" ADD COLUMN "mustChangePassword" BOOLEAN NOT NULL DEFAULT false;
|
||||||
@@ -24,6 +24,7 @@ model User {
|
|||||||
banReason String?
|
banReason String?
|
||||||
banExpires DateTime?
|
banExpires DateTime?
|
||||||
comment String?
|
comment String?
|
||||||
|
mustChangePassword Boolean @default(false)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { LogoutButton } from "@/components/layout/logout-button";
|
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() });
|
const session = await auth.api.getSession({ headers: await headers() });
|
||||||
if (!session) redirect("/login");
|
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
|
// Maintenance mode: non-admin users see the maintenance page
|
||||||
if (session.user.role !== "admin") {
|
if (session.user.role !== "admin") {
|
||||||
const maintenance = await getSetting("maintenanceMode");
|
const maintenance = await getSetting("maintenanceMode");
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ export async function changePasswordAction(_prevState: unknown, formData: FormDa
|
|||||||
where: { id: account.id },
|
where: { id: account.id },
|
||||||
data: { password: hash },
|
data: { password: hash },
|
||||||
});
|
});
|
||||||
|
await prisma.user.update({
|
||||||
|
where: { id: session.user.id },
|
||||||
|
data: { mustChangePassword: false },
|
||||||
|
});
|
||||||
|
|
||||||
return { success: true };
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -213,6 +213,50 @@ export async function sendAccessEmail(
|
|||||||
}).catch((e) => console.error("[email] sendAccessEmail:", e));
|
}).catch((e) => console.error("[email] sendAccessEmail:", e));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Выдача доступа по факту оплаты (через payment-router /api/internal/grant).
|
||||||
|
// tempPassword != null — новый покупатель (аккаунт создан с временным паролем,
|
||||||
|
// force-change при первом входе). null — существующий (курсы добавлены).
|
||||||
|
export async function sendCourseGrantEmail(
|
||||||
|
to: string,
|
||||||
|
name: string,
|
||||||
|
courseTitles: string[],
|
||||||
|
tempPassword: string | null,
|
||||||
|
) {
|
||||||
|
const school = await getSchoolName();
|
||||||
|
const list = courseTitles
|
||||||
|
.map((t) => `<li style="margin:0 0 6px;">${t}</li>`)
|
||||||
|
.join("");
|
||||||
|
const loginBlock = tempPassword
|
||||||
|
? `
|
||||||
|
<p ${p}><strong>Данные для входа:</strong></p>
|
||||||
|
${quote(`Адрес: school.second-brain.ru\nEmail: ${to}\nПароль: ${tempPassword}`)}
|
||||||
|
<p ${p}>Это <strong>временный пароль</strong> — при первом входе система попросит задать свой.</p>`
|
||||||
|
: `
|
||||||
|
<p ${p}>Войдите под своим обычным паролем — новые курсы уже на главной.</p>`;
|
||||||
|
const subject =
|
||||||
|
courseTitles.length > 1
|
||||||
|
? `Доступ к курсам ${school} открыт`
|
||||||
|
: `Доступ к курсу «${courseTitles[0] ?? school}» открыт`;
|
||||||
|
await getResend()
|
||||||
|
.emails.send({
|
||||||
|
from: FROM,
|
||||||
|
to,
|
||||||
|
subject,
|
||||||
|
html: base(
|
||||||
|
`
|
||||||
|
<p ${p}>Привет, ${name || ""} 👋🏽</p>
|
||||||
|
<p ${p}>Спасибо за покупку! Доступ уже открыт в вашем личном кабинете на <strong>school.second-brain.ru</strong>. Вам открыты курсы:</p>
|
||||||
|
<ul style="margin:0 0 18px;padding-left:20px;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.65;color:#323232;">${list}</ul>
|
||||||
|
${loginBlock}
|
||||||
|
${btn(`${BASE_URL}/login`, "Войти на платформу")}
|
||||||
|
<p style="margin:18px 0 0;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.65;color:#666666;">Если что-то не получается — просто ответьте на это письмо.</p>
|
||||||
|
`,
|
||||||
|
school,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
.catch((e) => console.error("[email] sendCourseGrantEmail:", e));
|
||||||
|
}
|
||||||
|
|
||||||
export async function sendPasswordResetEmail(to: string, name: string, resetUrl: string) {
|
export async function sendPasswordResetEmail(to: string, name: string, resetUrl: string) {
|
||||||
const school = await getSchoolName();
|
const school = await getSchoolName();
|
||||||
await getResend().emails.send({
|
await getResend().emails.send({
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getSessionCookie } from "better-auth/cookies";
|
import { getSessionCookie } from "better-auth/cookies";
|
||||||
|
|
||||||
const PUBLIC_ROUTES = ["/login", "/register", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/api/register", "/maintenance"];
|
const PUBLIC_ROUTES = ["/login", "/register", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/api/register", "/api/internal", "/maintenance"];
|
||||||
|
|
||||||
export function middleware(request: NextRequest) {
|
export function middleware(request: NextRequest) {
|
||||||
const { pathname } = request.nextUrl;
|
const { pathname } = request.nextUrl;
|
||||||
|
|||||||
Reference in New Issue
Block a user