46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
// app/api/account/password/route.ts
|
|
import { NextResponse } from "next/server";
|
|
import { requireBearer } from "@/app/api/_lib/auth";
|
|
|
|
export const runtime = "nodejs";
|
|
|
|
const API = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
|
|
const bad = (m: string, c = 400) => NextResponse.json({ error: m }, { status: c });
|
|
|
|
async function handle(req: Request) {
|
|
const bearer = requireBearer(req);
|
|
|
|
const body = await req.json().catch(() => ({}));
|
|
const current =
|
|
String(body?.current ?? body?.current_password ?? "").trim();
|
|
const next =
|
|
String(body?.next ?? body?.new_password ?? "").trim();
|
|
|
|
if (!current || !next) return bad("Missing current and/or new password");
|
|
if (next.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: next, old_password: current }),
|
|
});
|
|
|
|
const j = await res.json().catch(() => ({}));
|
|
|
|
if (!res.ok) {
|
|
const reason = j?.errors?.[0]?.message || "Password change failed";
|
|
const friendly = /invalid|credential|old_password|incorrect/i.test(reason)
|
|
? "Current password is incorrect"
|
|
: reason;
|
|
// Propagate upstream status (401/403/400…) so the UI can react.
|
|
return NextResponse.json({ error: friendly }, { status: res.status });
|
|
}
|
|
|
|
return NextResponse.json({ ok: true });
|
|
}
|
|
|
|
export async function POST(req: Request) { return handle(req); }
|
|
export async function PATCH(req: Request) { return handle(req); }
|