// app/api/account/profile/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(/\/$/, ""); const bad = (m: string, c = 400) => NextResponse.json({ error: m }, { status: c }); export async function GET() { // show username (read-only) + editable fields // allow missing email try { // caller is already gated by middleware; no token needed for GET here return NextResponse.json({ ok: true }); } catch (e: any) { return bad(e?.message || "Failed to load profile", e?.status || 500); } } export async function PATCH(req: Request) { try { const bearer = requireBearer(req); const body = await req.json().catch(() => ({} as Record)); // Enforce recent re-auth for sensitive fields const SENSITIVE = new Set(["email", "username"]); const wantsSensitive = Object.keys(body).some((k) => SENSITIVE.has(k)); if (wantsSensitive) { const cookie = req.headers.get("cookie") || ""; const hasRecentAuth = /(?:^|;\s*)ma_ra=1(?:;|$)/.test(cookie); if (!hasRecentAuth) { return NextResponse.json( { error: "Re-authentication required" }, { status: 428 } // Precondition Required ); } } const payload: any = {}; if (typeof (body as any).first_name === "string") payload.first_name = (body as any).first_name.trim(); if (typeof (body as any).last_name === "string") payload.last_name = (body as any).last_name.trim(); if (typeof (body as any).location === "string") payload.location = (body as any).location.trim(); if ("email" in body) { const e = String((body as any).email ?? "").trim(); payload.email = e ? e : null; // ← optional! blank clears it } // (password handled by /api/account/password) const r = await fetch(`${API}/users/me`, { method: "PATCH", headers: { Authorization: `Bearer ${bearer}`, "Content-Type": "application/json" }, body: JSON.stringify(payload), }); const j = await r.json().catch(() => ({})); if (!r.ok) return bad(j?.errors?.[0]?.message || "Update failed", r.status); return NextResponse.json({ ok: true }); } catch (e: any) { return bad(e?.message || "Unexpected error", e?.status || 500); } }