41 lines
1.6 KiB
TypeScript
41 lines
1.6 KiB
TypeScript
// app/api/account/password/route.ts
|
|
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 });
|
|
}
|
|
|
|
/**
|
|
* This uses the simplest approach: PATCH /users/me { password: NEW }.
|
|
* It requires your role to have Update permission on `directus_users` with
|
|
* filter id = $CURRENT_USER and field permission for `password`.
|
|
* If your Directus is configured to use a dedicated password endpoint instead,
|
|
* swap the implementation accordingly.
|
|
*/
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const bearer = requireBearer(req);
|
|
const { current_password, new_password } = await req.json().catch(() => ({}));
|
|
if (!new_password) return bad("Missing new_password");
|
|
|
|
// Optional: you can verify current_password server-side by attempting a login
|
|
// to your auth endpoint; omitted here to keep it simple.
|
|
|
|
const r = await fetch(`${API}/users/me`, {
|
|
method: "PATCH",
|
|
headers: { Authorization: bearer, "Content-Type": "application/json" },
|
|
body: JSON.stringify({ password: new_password }),
|
|
});
|
|
const j = await r.json().catch(() => ({}));
|
|
if (!r.ok) {
|
|
const msg = j?.errors?.[0]?.message || "Password update failed";
|
|
return bad(msg, r.status);
|
|
}
|
|
return NextResponse.json({ ok: true });
|
|
} catch (e: any) {
|
|
return bad(e?.message || "Failed to change password", e?.status || 500);
|
|
}
|
|
}
|