Add password recovery page at /recover

This commit is contained in:
Bonna Moon
2026-06-29 16:44:42 -05:00
parent ddc0a60a0c
commit 8ec43f3561
5 changed files with 189 additions and 0 deletions

BIN
.DS_Store vendored

Binary file not shown.

14
scripts/reset-password.ts Normal file
View File

@@ -0,0 +1,14 @@
import { PrismaClient } from "@prisma/client";
import { hashSync } from "bcryptjs";
const db = new PrismaClient();
async function main() {
const hash = hashSync("moonbase!", 10);
const result = await db.user.updateMany({
data: { passwordHash: hash, mustChangePassword: false },
});
console.log(`Reset password for ${result.count} user(s). Login with: moonbase!`);
}
main().catch(console.error).finally(() => db.$disconnect());

View File

@@ -0,0 +1,49 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { hashSync } from "bcryptjs";
import { db } from "@/lib/db";
const schema = z.object({
secret: z.string().min(1),
username: z.string().min(1),
password: z.string().min(6),
});
export async function POST(req: Request) {
const recoverySecret = process.env.RECOVERY_SECRET;
if (!recoverySecret) {
return NextResponse.json({ error: "Recovery not configured" }, { status: 503 });
}
try {
const body = await req.json();
const data = schema.parse(body);
if (data.secret !== recoverySecret) {
return NextResponse.json({ error: "Invalid recovery secret" }, { status: 403 });
}
const user = await db.user.findFirst({
where: { OR: [{ username: data.username }, { email: data.username }], active: true },
});
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
await db.user.update({
where: { id: user.id },
data: { passwordHash: hashSync(data.password, 10), mustChangePassword: false },
});
await db.auditEvent.create({
data: { action: "auth.recover", entityId: user.id, payload: { username: user.username } },
});
return NextResponse.json({ ok: true, name: user.name });
} catch (err) {
if (err instanceof z.ZodError) return NextResponse.json({ error: "Invalid input" }, { status: 400 });
console.error(err);
return NextResponse.json({ error: "Server error" }, { status: 500 });
}
}

View File

@@ -74,6 +74,11 @@ function LoginForm() {
<Button type="submit" className="w-full" disabled={busy}>
{busy ? "Signing in…" : "Sign in"}
</Button>
<p className="text-center text-xs text-muted-foreground">
<a href="/recover" className="underline underline-offset-2 hover:text-foreground">
Forgot password?
</a>
</p>
</form>
</CardContent>
</Card>

121
src/app/recover/page.tsx Normal file
View File

@@ -0,0 +1,121 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
export default function RecoverPage() {
const router = useRouter();
const [form, setForm] = useState({ secret: "", username: "", password: "", confirm: "" });
const [status, setStatus] = useState<{ type: "error" | "success"; message: string } | null>(null);
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (form.password !== form.confirm) {
setStatus({ type: "error", message: "Passwords don't match." });
return;
}
setLoading(true);
setStatus(null);
try {
const res = await fetch("/api/auth/recover", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ secret: form.secret, username: form.username, password: form.password }),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error ?? "Failed");
setStatus({ type: "success", message: `Password reset for ${json.name}. You can now log in.` });
} catch (err) {
setStatus({ type: "error", message: String(err).replace("Error: ", "") });
} finally {
setLoading(false);
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-6">
<div>
<h1 className="text-2xl font-bold">Account Recovery</h1>
<p className="text-sm text-muted-foreground mt-1">
Enter the recovery secret from your <code>.env</code> file to reset a password.
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1">
<label className="text-sm font-medium">Recovery secret</label>
<input
type="password"
required
value={form.secret}
onChange={e => setForm(f => ({ ...f, secret: e.target.value }))}
className="w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
placeholder="from your .env file"
/>
</div>
<div className="space-y-1">
<label className="text-sm font-medium">Username</label>
<input
type="text"
required
value={form.username}
onChange={e => setForm(f => ({ ...f, username: e.target.value }))}
className="w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
placeholder="bonna"
/>
</div>
<div className="space-y-1">
<label className="text-sm font-medium">New password</label>
<input
type="password"
required
minLength={6}
value={form.password}
onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
className="w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
<div className="space-y-1">
<label className="text-sm font-medium">Confirm new password</label>
<input
type="password"
required
value={form.confirm}
onChange={e => setForm(f => ({ ...f, confirm: e.target.value }))}
className="w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
{status && (
<div className={`rounded-md p-3 text-sm ${status.type === "success" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>
{status.message}
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium hover:bg-primary/90 disabled:opacity-50"
>
{loading ? "Resetting…" : "Reset password"}
</button>
{status?.type === "success" && (
<button
type="button"
onClick={() => router.push("/login")}
className="w-full rounded-md border px-4 py-2 text-sm font-medium hover:bg-accent"
>
Go to login
</button>
)}
</form>
</div>
</div>
);
}