Add forgot-password and reset-password flow
Users can now request a password reset link via email. Better Auth sendResetPassword callback sends a branded email via Resend. Login page shows success notice after password is set. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
border: "2px solid var(--border)",
|
||||
color: "var(--foreground)",
|
||||
fontFamily: "var(--font-sans)",
|
||||
outline: "none",
|
||||
};
|
||||
|
||||
export function ForgotPasswordForm() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [sent, setSent] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
setLoading(true);
|
||||
await authClient.requestPasswordReset({
|
||||
email,
|
||||
redirectTo: "/reset-password",
|
||||
});
|
||||
setLoading(false);
|
||||
setSent(true);
|
||||
}
|
||||
|
||||
if (sent) {
|
||||
return (
|
||||
<div className="space-y-4 text-center">
|
||||
<p className="text-sm" style={{ color: "var(--foreground)" }}>
|
||||
Письмо со ссылкой для сброса пароля отправлено на{" "}
|
||||
<strong>{email}</strong>.
|
||||
</p>
|
||||
<p className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
Проверьте папку «Спам», если письмо не пришло в течение пары минут.
|
||||
</p>
|
||||
<Link href="/login" className="block text-xs underline mt-4" style={{ color: "var(--muted-foreground)" }}>
|
||||
Вернуться к входу
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-sm mb-4" style={{ color: "var(--muted-foreground)" }}>
|
||||
Введите email — мы пришлём ссылку для задания нового пароля.
|
||||
</p>
|
||||
<label className="block text-xs uppercase tracking-widest font-bold" style={{ color: "var(--muted-foreground)" }}>
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="w-full px-3 py-2 text-sm bg-transparent"
|
||||
style={inputStyle}
|
||||
onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
|
||||
onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
|
||||
placeholder="you@example.com"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm" style={{ color: "var(--destructive)" }}>{error}</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="btn-aubade w-full justify-center"
|
||||
style={loading ? { opacity: 0.6, cursor: "not-allowed" } : undefined}
|
||||
>
|
||||
{loading ? "Отправка..." : "Сбросить пароль"}
|
||||
</button>
|
||||
<p className="text-center text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
<Link href="/login" className="underline" style={{ color: "var(--foreground)" }}>
|
||||
Вернуться к входу
|
||||
</Link>
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { getSetting } from "@/lib/settings";
|
||||
import { ForgotPasswordForm } from "./forgot-password-form";
|
||||
|
||||
export default async function ForgotPasswordPage() {
|
||||
const schoolName = await getSetting("schoolName");
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: "var(--background)" }}>
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-wide" style={{ color: "var(--foreground)" }}>
|
||||
{schoolName}
|
||||
</h1>
|
||||
<p className="mt-1 text-sm uppercase tracking-widest" style={{ color: "var(--muted-foreground)", fontSize: "0.65rem" }}>
|
||||
Образовательная платформа
|
||||
</p>
|
||||
</div>
|
||||
<div className="card-aubade p-8">
|
||||
<ForgotPasswordForm />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -95,12 +95,14 @@ export function LoginForm() {
|
||||
>
|
||||
{loading ? "Вход..." : "Войти"}
|
||||
</button>
|
||||
<p className="text-center text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
Нет аккаунта?{" "}
|
||||
<div className="flex items-center justify-between text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
<Link href="/forgot-password" className="underline" style={{ color: "var(--muted-foreground)" }}>
|
||||
Забыли пароль?
|
||||
</Link>
|
||||
<Link href="/register" className="underline" style={{ color: "var(--foreground)" }}>
|
||||
Зарегистрироваться
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,14 @@ export default async function LoginPage({
|
||||
Образовательная платформа
|
||||
</p>
|
||||
</div>
|
||||
{notice === "password_reset" && (
|
||||
<div
|
||||
className="mb-4 px-4 py-3 text-sm text-center"
|
||||
style={{ border: "2px solid var(--border)", color: "var(--foreground)" }}
|
||||
>
|
||||
Пароль успешно задан. Войдите с новым паролем.
|
||||
</div>
|
||||
)}
|
||||
{notice === "registration_closed" && (
|
||||
<div
|
||||
className="mb-4 px-4 py-3 text-sm text-center"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Suspense } from "react";
|
||||
import { getSetting } from "@/lib/settings";
|
||||
import { ResetPasswordForm } from "./reset-password-form";
|
||||
|
||||
export default async function ResetPasswordPage() {
|
||||
const schoolName = await getSetting("schoolName");
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: "var(--background)" }}>
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-wide" style={{ color: "var(--foreground)" }}>
|
||||
{schoolName}
|
||||
</h1>
|
||||
<p className="mt-1 text-sm uppercase tracking-widest" style={{ color: "var(--muted-foreground)", fontSize: "0.65rem" }}>
|
||||
Образовательная платформа
|
||||
</p>
|
||||
</div>
|
||||
<div className="card-aubade p-8">
|
||||
<Suspense fallback={null}>
|
||||
<ResetPasswordForm />
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
border: "2px solid var(--border)",
|
||||
color: "var(--foreground)",
|
||||
fontFamily: "var(--font-sans)",
|
||||
outline: "none",
|
||||
};
|
||||
|
||||
export function ResetPasswordForm() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams.get("token") ?? "";
|
||||
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
if (!token) {
|
||||
return (
|
||||
<div className="text-center space-y-4">
|
||||
<p className="text-sm" style={{ color: "var(--muted-foreground)" }}>
|
||||
Ссылка недействительна или устарела.
|
||||
</p>
|
||||
<Link href="/forgot-password" className="text-xs underline" style={{ color: "var(--foreground)" }}>
|
||||
Запросить новую ссылку
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
if (password !== confirm) {
|
||||
setError("Пароли не совпадают");
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError("Пароль должен быть не короче 8 символов");
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
const result = await authClient.resetPassword({ newPassword: password, token });
|
||||
setLoading(false);
|
||||
if (result.error) {
|
||||
setError("Ссылка устарела или уже использована. Запросите новую.");
|
||||
return;
|
||||
}
|
||||
router.push("/login?notice=password_reset");
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<p className="text-sm" style={{ color: "var(--muted-foreground)" }}>
|
||||
Задайте новый пароль для вашего аккаунта.
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-xs uppercase tracking-widest font-bold" style={{ color: "var(--muted-foreground)" }}>
|
||||
Новый пароль
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
className="w-full px-3 py-2 text-sm bg-transparent"
|
||||
style={inputStyle}
|
||||
onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
|
||||
onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
|
||||
placeholder="Минимум 8 символов"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-xs uppercase tracking-widest font-bold" style={{ color: "var(--muted-foreground)" }}>
|
||||
Повторите пароль
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
required
|
||||
className="w-full px-3 py-2 text-sm bg-transparent"
|
||||
style={inputStyle}
|
||||
onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
|
||||
onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm" style={{ color: "var(--destructive)" }}>{error}</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="btn-aubade w-full justify-center"
|
||||
style={loading ? { opacity: 0.6, cursor: "not-allowed" } : undefined}
|
||||
>
|
||||
{loading ? "Сохранение..." : "Сохранить пароль"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
+4
-1
@@ -3,7 +3,7 @@ import { prismaAdapter } from "better-auth/adapters/prisma";
|
||||
import { admin } from "better-auth/plugins";
|
||||
import { prisma } from "./prisma";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { sendWelcomeEmail } from "./email";
|
||||
import { sendWelcomeEmail, sendPasswordResetEmail } from "./email";
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
@@ -16,6 +16,9 @@ export const auth = betterAuth({
|
||||
hash: (password) => bcrypt.hash(password, 10),
|
||||
verify: ({ hash, password }) => bcrypt.compare(password, hash),
|
||||
},
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await sendPasswordResetEmail(user.email, user.name, url);
|
||||
},
|
||||
},
|
||||
databaseHooks: {
|
||||
user: {
|
||||
|
||||
@@ -189,3 +189,19 @@ export async function sendTestEmail(to: string) {
|
||||
`, school),
|
||||
}).catch((e) => console.error("[email] sendTestEmail:", e));
|
||||
}
|
||||
|
||||
export async function sendPasswordResetEmail(to: string, name: string, resetUrl: string) {
|
||||
const school = await getSchoolName();
|
||||
await getResend().emails.send({
|
||||
from: FROM,
|
||||
to,
|
||||
subject: `Сброс пароля — ${school}`,
|
||||
html: base(`
|
||||
<p ${p}>Привет, ${name}!</p>
|
||||
<p ${p}>Вы запросили сброс пароля для вашего аккаунта на платформе <strong>${school}</strong>.</p>
|
||||
<p ${p}>Нажмите на кнопку ниже чтобы задать новый пароль. Ссылка действительна <strong>1 час</strong>.</p>
|
||||
<p ${pLast}>Если вы не запрашивали сброс — просто проигнорируйте это письмо.</p>
|
||||
${btn(resetUrl, "Задать новый пароль")}
|
||||
`, school),
|
||||
}).catch((e) => console.error("[email] sendPasswordResetEmail:", e));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user