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:
@@ -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