40 lines
1.4 KiB
TypeScript
40 lines
1.4 KiB
TypeScript
// app/api/account/password/route.ts
|
|
export const runtime = "nodejs";
|
|
|
|
import { NextResponse } from "next/server";
|
|
import { requireBearer } from "@/app/api/_lib/auth";
|
|
|
|
const API = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
|
|
|
|
function bad(msg: string, code = 400) {
|
|
return NextResponse.json({ error: msg }, { status: code });
|
|
}
|
|
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const bearer = requireBearer(req);
|
|
const body = await req.json().catch(() => ({}));
|
|
|
|
// accept various shapes: {next}, {new_password}, {password}
|
|
const nextPwd =
|
|
String(body?.next ?? body?.new_password ?? body?.password ?? "").trim();
|
|
|
|
if (nextPwd.length < 8) return bad("Password must be at least 8 characters");
|
|
|
|
const res = await fetch(`${API}/users/me`, {
|
|
method: "PATCH",
|
|
headers: { Authorization: bearer, "Content-Type": "application/json" },
|
|
body: JSON.stringify({ password: nextPwd }),
|
|
});
|
|
|
|
const j = await res.json().catch(() => ({}));
|
|
if (!res.ok) {
|
|
return bad(j?.errors?.[0]?.message || "Password update failed", res.status);
|
|
}
|
|
|
|
// tell the client to re-auth so their token reflects the password change
|
|
return NextResponse.json({ ok: true, requireReauth: true });
|
|
} catch (e: any) {
|
|
return bad(e?.message || "Unexpected error", e?.status || 500);
|
|
}
|
|
}
|