push to maple-street
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
consumeMagicToken,
|
||||
getUser,
|
||||
verifyPasswordResetToken,
|
||||
} from "@/auth/magic-link";
|
||||
import { hashPassword, validatePassword } from "@/auth/password";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { updateUserCredentials } from "@/db/users";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const json = (payload: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
|
||||
|
||||
const bodySchema = z.object({
|
||||
token: z.string().min(1),
|
||||
newPassword: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
/**
|
||||
* Complete an admin-issued password reset. The token is single-use and is
|
||||
* consumed before the new hash is written, so replaying the same link cannot
|
||||
* reset the account twice.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return json({ error: "A JSON body is required." }, 400);
|
||||
}
|
||||
const parsed = bodySchema.safeParse(body);
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
const passwordError = validatePassword(parsed.data.newPassword);
|
||||
if (passwordError) return json({ error: passwordError }, 400);
|
||||
|
||||
const payload = await verifyPasswordResetToken(parsed.data.token);
|
||||
if (!payload) {
|
||||
return json({ error: "This reset link is invalid or has expired." }, 400);
|
||||
}
|
||||
|
||||
const user = await getUser(payload.email);
|
||||
if (!user || user.status !== "active" || user.deactivatedAt) {
|
||||
return json({ error: "This account cannot reset its password." }, 400);
|
||||
}
|
||||
|
||||
const consumed = await consumeMagicToken(payload);
|
||||
if (!consumed) {
|
||||
return json({ error: "This reset link has already been used." }, 409);
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(parsed.data.newPassword);
|
||||
const updated = await updateUserCredentials(user.id, { passwordHash });
|
||||
if (!updated) return json({ error: "unknown user" }, 404);
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: user.id,
|
||||
action: "user.password_reset",
|
||||
entityType: "user",
|
||||
entityId: user.id,
|
||||
after: { passwordSet: true },
|
||||
});
|
||||
|
||||
return json({ ok: true });
|
||||
};
|
||||
Reference in New Issue
Block a user