account management upgrades

This commit is contained in:
makearmy 2025-09-30 19:35:27 -04:00
parent 94de501a49
commit 86fdd403b0
8 changed files with 439 additions and 46 deletions

View file

@ -6,6 +6,7 @@ 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 });
const secure = process.env.NODE_ENV === "production";
/** GET: current user's profile */
export async function GET(req: Request) {
@ -36,17 +37,32 @@ return NextResponse.json({ ok: true, user: j?.data ?? j });
export async function PATCH(req: Request) {
try {
const bearer = requireBearer(req);
const body = await req.json().catch(() => ({}));
const body = await req.json().catch(() => ({} as Record<string, unknown>));
// Enforce recent re-auth for sensitive fields (email/username)
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: Record<string, any> = {};
if (typeof body.first_name === "string") payload.first_name = body.first_name.trim();
if (typeof body.last_name === "string") payload.last_name = body.last_name.trim();
if ("email" in body) {
const e = String(body.email ?? "").trim();
const e = String((body as any).email ?? "").trim();
payload.email = e ? e : null; // optional; blank clears
}
if (typeof body.location === "string") payload.location = body.location.trim();
if (typeof body.avatar === "string") payload.avatar = body.avatar; // file id
// (username is read-only in UI; if you decide to allow it later, payload.username = ...)
if (!Object.keys(payload).length) return bad("No changes");
@ -62,6 +78,21 @@ export async function PATCH(req: Request) {
return NextResponse.json({ error: msg }, { status: res.status });
}
// Success: if we just did a sensitive change, clear recent-auth cookie (single-use)
if (wantsSensitive) {
const resp = NextResponse.json({ ok: true });
resp.cookies.set({
name: "ma_ra",
value: "",
httpOnly: false,
sameSite: "lax",
secure,
path: "/",
maxAge: 0,
});
return resp;
}
return NextResponse.json({ ok: true });
} catch (e: any) {
const status = e?.status === 401 ? 401 : e?.status || 500;

View file

@ -9,14 +9,14 @@ export async function POST(req: NextRequest) {
try {
const body = await req.json().catch(() => ({} as any));
const identifier = String(body?.identifier ?? "").trim();
const password = String(body?.password ?? "").trim();
const password = String(body?.password ?? "").trim();
if (!identifier || !password) {
return NextResponse.json({ error: "Missing credentials" }, { status: 400 });
}
// Resolve identifier -> email (username allowed)
let email = identifier.includes("@") ? identifier : await emailForUsername(identifier);
// Resolve identifier -> email (username or email accepted)
const email = identifier.includes("@") ? identifier : await emailForUsername(identifier);
if (!email) return NextResponse.json({ error: "User not found" }, { status: 404 });
const auth = await loginDirectus(email, password);
@ -30,7 +30,8 @@ export async function POST(req: NextRequest) {
const res = NextResponse.json({ ok: true });
// Refresh the access token cookie
const maxAge = typeof expiresSec === "number" ? Math.max(0, Math.floor(expiresSec)) : 60 * 60 * 8;
const maxAge =
typeof expiresSec === "number" ? Math.max(0, Math.floor(expiresSec)) : 60 * 60 * 8;
res.cookies.set({
name: "ma_at",
value: access,
@ -41,7 +42,7 @@ export async function POST(req: NextRequest) {
maxAge,
});
// Short-lived client-visible flag: “recently authenticated”
// Short-lived client-visible flag: “recently authenticated” (5 minutes)
res.cookies.set({
name: "ma_ra",
value: "1",
@ -49,7 +50,7 @@ export async function POST(req: NextRequest) {
sameSite: "lax",
secure,
path: "/",
maxAge: 5 * 60, // 5 minutes
maxAge: 5 * 60,
});
return res;

View file

@ -1,8 +1,12 @@
// app/portal/account/AccountPanel.tsx
"use client";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState, useCallback } from "react";
import ProfileEditor from "@/components/account/ProfileEditor";
import PasswordChange from "@/components/account/PasswordChange";
import AvatarUploader from "@/components/account/AvatarUploader";
type Avatar = { id: string; filename_download?: string } | null;
type Me = {
id: string;
username: string;
@ -10,7 +14,7 @@ type Me = {
last_name?: string | null;
email?: string | null;
location?: string | null;
avatar?: { id: string; filename_download: string } | null;
avatar?: Avatar;
};
export default function AccountPanel() {
@ -18,20 +22,34 @@ export default function AccountPanel() {
const [err, setErr] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
// Precompute API base once on the client
const API_BASE = useMemo(
() => (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, ""),
[]
);
const refetchMe = useCallback(async () => {
try {
const r = await fetch("/api/account", {
credentials: "include",
cache: "no-store",
});
if (!r.ok) throw new Error(`Load failed (${r.status})`);
const j = await r.json();
const user: Me | undefined = j?.user ?? j?.data ?? undefined;
if (!user) throw new Error("Malformed response");
setMe(user);
} catch (e: any) {
setErr(e?.message || "Failed to load account");
}
}, []);
useEffect(() => {
let alive = true;
(async () => {
try {
setErr(null);
const r = await fetch("/api/account", {
credentials: "include",
cache: "no-store",
});
if (!r.ok) throw new Error(`Load failed (${r.status})`);
const j = await r.json();
if (alive) setMe(j);
} catch (e: any) {
if (alive) setErr(e?.message || "Failed to load account");
await refetchMe();
} finally {
if (alive) setLoading(false);
}
@ -39,16 +57,13 @@ export default function AccountPanel() {
return () => {
alive = false;
};
}, []);
}, [refetchMe]);
if (loading) return <div className="rounded-md border p-6 text-sm opacity-70">Loading</div>;
if (err) return <div className="rounded-md border p-6 text-red-600">Error: {err}</div>;
if (!me) return null;
const avatarUrl =
me.avatar?.id
? `${process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "")}/assets/${me.avatar.id}`
: null;
const avatarUrl = me.avatar?.id ? `${API_BASE}/assets/${me.avatar.id}` : null;
return (
<div className="space-y-6">
@ -64,9 +79,7 @@ export default function AccountPanel() {
<span className="text-xs opacity-60">No Avatar</span>
)}
</div>
<div className="text-xs text-muted-foreground">
Usernames cant be changed.
</div>
<div className="text-xs text-muted-foreground">Usernames cant be changed.</div>
</div>
<div className="grid sm:grid-cols-2 gap-3 text-sm">
@ -93,7 +106,18 @@ export default function AccountPanel() {
</div>
</div>
{/* Add your edit forms/buttons below; they should only trigger reauth on submit */}
{/* Editable sections */}
<AvatarUploader
avatarId={me.avatar?.id || null}
onUpdated={refetchMe}
/>
<ProfileEditor
me={me}
onUpdated={refetchMe}
/>
<PasswordChange />
</div>
);
}

View file

@ -10,7 +10,7 @@ export default async function AccountPage() {
if (!at) {
redirect(`/auth/sign-in?next=${encodeURIComponent("/portal/account")}`);
}
// No reauth gating here; the panel will fetch and render profile,
// and only ask for reauth when user submits sensitive changes.
// No reauth gating here; the panel fetches and renders profile,
// and only asks for reauth when the user submits sensitive changes.
return <AccountPanel />;
}