// app/api/account/password/route.ts import { NextResponse } from "next/server"; import { requireBearer } from "@/app/api/_lib/auth"; import { loginDirectus } from "@/lib/directus"; 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"); // 1) Load current user to get provider + identifiers const meRes = await fetch(`${API}/users/me?fields=id,email,username,provider`, { headers: { Authorization: `Bearer ${bearer}`, Accept: "application/json" }, cache: "no-store", }); const me = await meRes.json().catch(() => ({})); if (!meRes.ok) { return NextResponse.json( { error: "Could not verify user", debug: me?.errors?.[0]?.message || meRes.statusText }, { status: meRes.status } ); } const provider: string = me?.data?.provider ?? me?.provider ?? "local"; const email: string | undefined = me?.data?.email ?? me?.email ?? undefined; const username: string | undefined = me?.data?.username ?? me?.username ?? undefined; if (provider !== "local") { return NextResponse.json( { error: "Password managed by external provider", debug: `provider=${provider}` }, { status: 400 } ); } // 2) Verify CURRENT password by logging in with email OR username const identifier = email || username; if (!identifier) { return NextResponse.json( { error: "No login identifier available for this user", debug: "missing email and username" }, { status: 400 } ); } const auth = await loginDirectus(identifier, current).catch(() => null); const access = auth?.access_token ?? auth?.data?.access_token; if (!access) { return NextResponse.json({ error: "Current password is incorrect" }, { status: 401 }); } // 3) Update password using ONLY the 'password' field const patchRes = await fetch(`${API}/users/me`, { method: "PATCH", headers: { Authorization: `Bearer ${bearer}`, "Content-Type": "application/json", Accept: "application/json", }, body: JSON.stringify({ password: next }), }); const j = await patchRes.json().catch(() => ({})); if (!patchRes.ok) { const reason = j?.errors?.[0]?.message || j?.error || (typeof j === "string" ? j : "") || "Password change failed"; return NextResponse.json({ error: reason }, { status: patchRes.status }); } return NextResponse.json({ ok: true }); } export async function POST(req: Request) { return handle(req); } export async function PATCH(req: Request) { return handle(req); }