Files
crosscode-platform/apps/accounts/frontend/src/app/account/Account.tsx
T
joshuaandClaude Opus 5.5 f202a5a88e Accounts 1.0.0 frontend and @crosscode/ui
Sign-in steps (password, sign-up, email code, two-step sign-in and its
setup with recovery codes, privacy notice, news question), forgot and
reset password, the account page, admin (people, deletions, church
profile, linked products, settings, notice, licence, audit) and setup.
Strict CSP with a nonce per page; church colours from the profile.
@crosscode/ui gets its first components (shell, card, fields, buttons).
Plan: roles stay in each product (asked 2026-11-18).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:42:45 +02:00

270 lines
15 KiB
TypeScript

"use client";
import React, { useCallback, useState } from "react";
import QRCode from "qrcode";
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type Me = {
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
};
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
type Export = { id: string; status: string; createdAt: string; readyAt: string | null; expiresAt: string };
const METHOD = { totp: "an authenticator app", email: "a code by email", whatsapp: "a code on WhatsApp" } as const;
const EVENT: Record<string, string> = {
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
};
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
/** The account page (docs/ACCOUNTS-1.0-PLAN.md §8): everything about one's own account. */
export function Account() {
const branding = useBranding();
const [me, setMe] = useState<Me | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
const load = useCallback(async () => {
const r = await call<Me>("GET", "/me");
if (r.status === 401) return window.location.assign(selfSignIn("/account"));
if (r.ok) setMe(r.data);
}, []);
useExternalEffect(() => { void load(); }, [load]);
const done = (text: string) => { setMsg({ tone: "success", text }); void load(); };
const fail = (text: string) => setMsg({ tone: "error", text });
if (!me) return <Shell branding={branding}><p className="text-gray-600">Loading…</p></Shell>;
const signOut = <a href={`/api/oidc/session/end?client_id=accounts-self&post_logout_redirect_uri=${encodeURIComponent(`${window.location.origin}/signed-out`)}`} className="text-sm text-brand underline">Sign out</a>;
return (
<Shell branding={branding} wide aside={<div className="flex gap-4">{me.role === "admin" && <a href="/admin" className="text-sm text-brand underline">Admin</a>}{signOut}</div>}>
<h1 className="mb-1 text-2xl font-semibold">Your account</h1>
<p className="mb-6 text-sm text-gray-600">One account for all of {branding.name}&apos;s sites and apps.</p>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
<div className="grid gap-6 md:grid-cols-2">
<Profile me={me} onDone={done} onFail={fail} />
<Security me={me} onDone={done} onFail={fail} />
<Privacy me={me} onDone={done} onFail={fail} />
<Activity onDone={done} />
</div>
</Shell>
);
}
type Props = { me: Me; onDone: (t: string) => void; onFail: (t: string) => void };
function Profile({ me, onDone, onFail }: Props) {
const [busy, setBusy] = useState(false);
const [changingEmail, setChangingEmail] = useState(false);
return (
<Card>
<Heading>Your details</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
setBusy(true);
const r = await call("PUT", "/me", { name: f.get("name"), phone: f.get("phone") || null });
setBusy(false);
if (r.ok) onDone("Your details are saved, and the church's sites have them too.");
else onFail(r.error.message);
}}>
<Field label="Name" name="name" defaultValue={me.name} required autoComplete="name" />
<Field label="Mobile number" name="phone" type="tel" defaultValue={me.phone ?? ""} autoComplete="tel" />
<Button type="submit" busy={busy}>Save</Button>
</form>
<div className="mt-6 border-t pt-4">
<p className="text-sm text-gray-700">Email address: <strong>{me.email}</strong></p>
{!changingEmail ? (
<Button variant="link" className="mt-1 text-sm" onClick={() => setChangingEmail(true)}>Change it</Button>
) : (
<form className="mt-3" onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const r = await call("POST", "/me/email", { email: f.get("email"), password: f.get("password") });
if (r.ok) { setChangingEmail(false); onDone("Check your new email address for a link to confirm it. Until then you sign in with the old one."); } else onFail(r.error.message);
}}>
<Field label="New email address" name="email" type="email" required />
<Field label="Your password" name="password" type="password" required autoComplete="current-password" />
<Button type="submit">Send the link</Button>
</form>
)}
</div>
</Card>
);
}
function Security({ me, onDone, onFail }: Props) {
const [setup, setSetup] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string; qr?: string } | null>(null);
const [codes, setCodes] = useState<string[] | null>(null);
const start = async (method: string) => {
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", "/me/two-factor/setup", { method });
if (!r.ok) return onFail(r.error.message);
setSetup({ ...r.data, qr: r.data.otpauthUrl ? await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }) : undefined });
};
return (
<Card>
<Heading>Signing in</Heading>
<p className="mb-3 text-sm text-gray-700">
Two-step sign-in: {me.twoFactor ? <strong>on, with {METHOD[me.twoFactor]}</strong> : <strong>off</strong>}
{me.twoFactor && <span className="text-gray-500"> · {me.recoveryCodesLeft} recovery codes left</span>}
</p>
{codes && (
<Notice tone="warning">
Save these recovery codes somewhere safe. Each works once; they won&apos;t be shown again.
<pre className="mt-2 font-mono">{codes.join("\n")}</pre>
</Notice>
)}
{setup ? (
<form onSubmit={async (e) => {
e.preventDefault();
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/two-factor/confirm", { method: setup.method, code: new FormData(e.currentTarget).get("code") });
if (!r.ok) return onFail(r.error.message);
setSetup(null);
setCodes(r.data.recoveryCodes);
onDone("Two-step sign-in is on.");
}}>
{setup.qr && <img src={setup.qr} alt="QR code for your authenticator app" className="mb-2 h-40 w-40" />}
{setup.secret && <p className="mb-3 break-all font-mono text-xs text-gray-600">Key: {setup.secret}</p>}
{setup.sentTo && <p className="mb-3 text-sm">We sent a code to <strong>{setup.sentTo}</strong>.</p>}
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required />
<div className="flex gap-2"><Button type="submit">Turn on</Button><Button type="button" variant="secondary" onClick={() => setSetup(null)}>Cancel</Button></div>
</form>
) : (
<div className="mb-4 flex flex-wrap gap-2">
<Button variant="secondary" onClick={() => start("totp")}>{me.twoFactor ? "Use an authenticator app" : "Turn on with an app"}</Button>
<Button variant="secondary" onClick={() => start("email")}>{me.twoFactor ? "Use email codes" : "Turn on with email"}</Button>
</div>
)}
{me.twoFactor && !setup && (
<PasswordAction label="New recovery codes" button="Make new codes" onSubmit={async (password) => {
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/recovery-codes", { password });
if (r.ok) { setCodes(r.data.recoveryCodes); onDone("New recovery codes made; the old ones no longer work."); } else onFail(r.error.message);
}} />
)}
{me.twoFactor && !setup && me.role !== "admin" && (
<PasswordAction label="Turn off two-step sign-in" button="Turn off" danger onSubmit={async (password) => {
const r = await call("POST", "/me/two-factor/off", { password });
if (r.ok) onDone("Two-step sign-in is off."); else onFail(r.error.message);
}} />
)}
<div className="mt-4 border-t pt-4">
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const r = await call("POST", "/me/password", { current: f.get("current"), password: f.get("password") });
if (r.ok) { e.currentTarget.reset(); onDone("Your password is changed."); } else onFail(r.error.message);
}}>
<Field label="Current password" name="current" type="password" autoComplete="current-password" required />
<Field label="New password" name="password" type="password" autoComplete="new-password" minLength={8} required />
<Button type="submit" variant="secondary">Change password</Button>
</form>
</div>
</Card>
);
}
function PasswordAction({ label, button, danger, onSubmit }: { label: string; button: string; danger?: boolean; onSubmit: (password: string) => void }) {
const [open, setOpen] = useState(false);
if (!open) return <p className="mb-2"><Button variant="link" className="text-sm" onClick={() => setOpen(true)}>{label}</Button></p>;
return (
<form className="mb-3 rounded-lg border p-3" onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("password"))); setOpen(false); }}>
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
<div className="flex gap-2"><Button type="submit" variant={danger ? "danger" : "primary"}>{button}</Button><Button type="button" variant="secondary" onClick={() => setOpen(false)}>Cancel</Button></div>
</form>
);
}
function Privacy({ me, onDone, onFail }: Props) {
const [exports, setExports] = useState<Export[]>([]);
const [confirmDelete, setConfirmDelete] = useState(false);
const loadExports = useCallback(async () => {
const r = await call<{ items: Export[] }>("GET", "/me/exports");
if (r.ok) setExports(r.data.items);
}, []);
useExternalEffect(() => { void loadExports(); }, [loadExports]);
return (
<Card>
<Heading>Privacy</Heading>
<form onChange={async (e) => {
const f = new FormData(e.currentTarget);
const r = await call("PUT", "/me/news", { email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" });
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
}}>
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
</form>
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p>
<div className="border-t pt-4">
<p className="mb-2 text-sm font-medium">Download my data</p>
<p className="mb-3 text-sm text-gray-600">Everything the church&apos;s sites hold about you, in one file. It takes a few minutes; we&apos;ll email you when it&apos;s ready.</p>
{exports.map((x) => (
<p key={x.id} className="mb-2 text-sm">
{when(x.createdAt)}: {x.status === "ready" ? <a className="text-brand underline" href={`/api/v2/me/exports/${x.id}/download`}>Download</a> : x.status === "collecting" ? "being put together…" : "expired"}
</p>
))}
<Button variant="secondary" onClick={async () => {
const r = await call("POST", "/me/exports");
if (r.ok) { onDone("We're putting your data together. We'll email you when it's ready."); void loadExports(); } else onFail(r.error.message);
}}>Ask for a copy</Button>
</div>
<div className="mt-4 border-t pt-4">
<p className="mb-2 text-sm font-medium">Delete my account</p>
{!confirmDelete ? (
<Button variant="link" className="text-sm text-red-700" onClick={() => setConfirmDelete(true)}>Delete my account…</Button>
) : (
<form onSubmit={async (e) => {
e.preventDefault();
const r = await call("POST", "/me/delete", { password: new FormData(e.currentTarget).get("password") });
// A full page load: the signed-out page has nothing of this session left.
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
if (r.ok) window.location.assign("/signed-out"); else onFail(r.error.message);
}}>
<Notice tone="warning">You&apos;ll be signed out of all the church&apos;s sites straight away. An admin then confirms the deletion, and each site removes what it holds about you (a site may wait until an event you&apos;re booked for is over).</Notice>
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
<div className="flex gap-2"><Button type="submit" variant="danger">Delete my account</Button><Button type="button" variant="secondary" onClick={() => setConfirmDelete(false)}>Cancel</Button></div>
</form>
)}
</div>
</Card>
);
}
function Activity({ onDone }: { onDone: (t: string) => void }) {
const [items, setItems] = useState<SignIn[]>([]);
useExternalEffect(() => {
let alive = true;
call<{ items: SignIn[] }>("GET", "/me/sign-ins").then((r) => { if (alive && r.ok) setItems(r.data.items); });
return () => { alive = false; };
}, []);
return (
<Card>
<Heading sub="If you see something you don't recognise, change your password and sign out everywhere.">Recent activity</Heading>
<ul className="mb-4 max-h-72 space-y-2 overflow-y-auto text-sm">
{items.map((e, i) => (
<li key={i} className="flex justify-between gap-3 border-b pb-2 last:border-0">
<span>{EVENT[e.type] ?? e.type}{e.site ? <span className="text-gray-500"> · {e.site.replace(/^https?:\/\//, "")}</span> : null}</span>
<span className="shrink-0 text-gray-500">{when(e.at)}</span>
</li>
))}
{!items.length && <li className="text-gray-500">Nothing yet.</li>}
</ul>
<Button variant="secondary" onClick={async () => {
const r = await call("POST", "/me/sign-out-everywhere");
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
if (r.ok) { onDone("You're signed out everywhere."); window.location.assign("/signed-out"); }
}}>Sign out everywhere</Button>
</Card>
);
}