75 lines
2.8 KiB
TypeScript
75 lines
2.8 KiB
TypeScript
// 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() {
|
|
try {
|
|
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<string, unknown>));
|
|
|
|
// 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 });
|
|
}
|
|
}
|
|
|
|
const payload: Record<string, 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
|
|
}
|
|
|
|
if (!Object.keys(payload).length) return bad("No changes");
|
|
|
|
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);
|
|
|
|
// Single-use recent-auth: clear ma_ra after sensitive success
|
|
if (wantsSensitive) {
|
|
const resp = NextResponse.json({ ok: true });
|
|
resp.cookies.set({
|
|
name: "ma_ra",
|
|
value: "",
|
|
httpOnly: false,
|
|
sameSite: "lax",
|
|
secure: process.env.NODE_ENV === "production",
|
|
path: "/",
|
|
maxAge: 0,
|
|
});
|
|
return resp;
|
|
}
|
|
|
|
return NextResponse.json({ ok: true });
|
|
} catch (e: any) {
|
|
return bad(e?.message || "Unexpected error", e?.status || 500);
|
|
}
|
|
}
|