Files
crosscode-platform/apps/accounts/frontend/src/app/account/Account.tsx
T
joshuaandClaude Opus 5.5 8856d6b35d Events 3.3.0, Accounts 1.3.0, contracts 1.11.0: Accounts looks like Events, backups; sign-out and upload fixes
- Accounts: account and admin pages in Cross Events' layout (top bar, sidebar,
  a page per section, dark footer); quick links to the church's sites
  (GET /me/apps); nightly pg_dump backups with Admin -> Backups (run, keep,
  download, audited; heartbeat lastBackupAt); a fuller built-in privacy notice
  with headings and bullets; a fixed favicon. /backups/ ignored (anchored, so
  src/backups is kept).
- Contracts 1.11.0: people.removeDemo (only @example.com, never an admin).
- Events: uploads served from the folder they're saved in (a backend started
  outside backend/ answered 404 for a logo it had just saved); Branding checks
  the file loads before saving; logout waits for the sign-out call so Accounts
  signs out too; set-demo removes the last demo's people from Accounts.
Tests: Accounts 62 + e2e 8, Events 782, contracts 225; npm run check passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:19:57 +02:00

361 lines
21 KiB
TypeScript

"use client";
import Link from "next/link";
import React, { useCallback, useState } from "react";
import QRCode from "qrcode";
import { Activity as ActivityIcon, ArrowUpRight, Calendar, CheckCircle2, Globe, Lock, Mail, ShieldAlert, ShieldCheck, Smartphone, User, type LucideIcon } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
import { Card, Heading } from "@/components/Panel";
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" }) : "—");
export type AccountSection = "overview" | "details" | "security" | "privacy" | "activity";
const SECTIONS: Record<AccountSection, { path: string; title: string; sub: (church: string) => string }> = {
overview: { path: "/account", title: "Your account", sub: (c) => `One account for all of ${c}'s sites and apps.` },
details: { path: "/account/details", title: "Your details", sub: (c) => `Your name and contact details, shared with ${c}'s sites when you sign in.` },
security: { path: "/account/security", title: "Signing in", sub: () => "Your password, two-step sign-in and recovery codes." },
privacy: { path: "/account/privacy", title: "Privacy", sub: () => "Your news choices, a copy of your data, and deleting your account." },
activity: { path: "/account/activity", title: "Activity", sub: () => "Recent sign-ins and changes to your account." },
};
/**
* The account page (docs/ACCOUNTS-1.0-PLAN.md §8): everything about one's own account. 1.3.0: in
* sections down the side (as Cross Events' dashboard), with quick links to the church's sites.
*/
export function Account({ section = "overview" }: { section?: AccountSection }) {
const branding = useBranding();
const [me, setMe] = useState<Me | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
const s = SECTIONS[section] ?? SECTIONS.overview;
const load = useCallback(async () => {
const r = await call<Me>("GET", "/me");
if (r.status === 401) return window.location.assign(selfSignIn(s.path));
if (r.ok) setMe(r.data);
}, [s.path]);
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 <ShellLoading />;
const first = me.name.split(" ")[0] || me.name;
return (
<AppShell me={me} active={s.path}>
<PageTitle sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{section === "overview" && <Overview me={me} />}
{section === "details" && <div className="max-w-2xl"><Profile me={me} onDone={done} onFail={fail} /></div>}
{section === "security" && <div className="max-w-2xl"><Security me={me} onDone={done} onFail={fail} /></div>}
{section === "privacy" && <div className="max-w-2xl"><Privacy me={me} onDone={done} onFail={fail} /></div>}
{section === "activity" && <div className="max-w-2xl"><Activity onDone={done} /></div>}
</AppShell>
);
}
// ─── Overview: the church's sites, and how the account stands ────────────────
type App = { id: string; product: string; name: string; description: string | null; url: string };
const APP_ICONS: Record<string, LucideIcon> = { events: Calendar, website: Globe, app: Smartphone };
function Overview({ me }: { me: Me }) {
const branding = useBranding();
const [apps, setApps] = useState<App[] | null>(null);
useExternalEffect(() => {
let alive = true;
call<{ items: App[] }>("GET", "/me/apps").then((r) => { if (alive) setApps(r.ok ? r.data.items : []); });
return () => { alive = false; };
}, []);
const checks: { ok: boolean; label: string; detail: string; href: string; icon: LucideIcon }[] = [
{ ok: !!me.twoFactor, label: me.twoFactor ? "Two-step sign-in is on" : "Two-step sign-in is off", detail: me.twoFactor ? `With ${METHOD[me.twoFactor]}${me.recoveryCodesLeft < 3 ? `, ${me.recoveryCodesLeft} recovery codes left` : ""}` : "Turn it on so a password alone can't open your account", href: "/account/security", icon: me.twoFactor ? ShieldCheck : ShieldAlert },
{ ok: me.emailVerified, label: me.emailVerified ? "Email address confirmed" : "Email address not confirmed", detail: me.email, href: "/account/details", icon: Mail },
{ ok: true, label: "Last sign-in", detail: when(me.lastSignInAt), href: "/account/activity", icon: ActivityIcon },
];
return (
<div className="space-y-6">
<section aria-labelledby="apps-title">
<h2 id="apps-title" className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Go to</h2>
{apps === null && <p className="text-sm text-gray-500" role="status">Loading…</p>}
{apps && !apps.length && (
<Card><p className="text-sm text-gray-600">{branding.name}&apos;s sites and apps will show here once they sign people in with this account.</p></Card>
)}
{apps && apps.length > 0 && (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{apps.map((a) => {
const Icon = APP_ICONS[a.product] ?? Globe;
return (
<a key={a.id} href={a.url} className="group flex items-center gap-4 rounded-xl border bg-white p-5 shadow-sm transition hover:border-brand/40 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/50">
<span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-brand text-white" aria-hidden><Icon className="h-6 w-6" /></span>
<span className="min-w-0 flex-1">
<span className="block font-semibold text-gray-900">{a.name}</span>
{a.description && <span className="block text-sm text-gray-500">{a.description}</span>}
<span className="block truncate text-xs text-gray-400">{a.url.replace(/^https?:\/\//, "").replace(/\/.*$/, "")}</span>
</span>
<ArrowUpRight className="h-5 w-5 shrink-0 text-gray-300 transition group-hover:text-brand" aria-hidden />
</a>
);
})}
</div>
)}
</section>
<section aria-labelledby="status-title">
<h2 id="status-title" className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Your account</h2>
<div className="grid gap-4 md:grid-cols-3">
{checks.map((c) => {
const Icon = c.icon;
return (
<a key={c.label} href={c.href} className="flex items-start gap-3 rounded-xl border bg-white p-4 shadow-sm hover:bg-gray-50">
<span className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${c.ok ? "bg-brand/10 text-brand" : "bg-amber-50 text-amber-700"}`} aria-hidden><Icon className="h-4 w-4" /></span>
<span className="min-w-0">
<span className="block text-sm font-medium text-gray-900">{c.label}</span>
<span className="block truncate text-xs text-gray-500">{c.detail}</span>
</span>
</a>
);
})}
</div>
</section>
<div className="flex flex-wrap gap-3 text-sm">
<Link href="/account/details" className="inline-flex items-center gap-1.5 rounded-lg border bg-white px-3 py-2 text-gray-700 hover:bg-gray-50"><User className="h-4 w-4" aria-hidden /> Change your details</Link>
<Link href="/account/privacy" className="inline-flex items-center gap-1.5 rounded-lg border bg-white px-3 py-2 text-gray-700 hover:bg-gray-50"><Lock className="h-4 w-4" aria-hidden /> Download your data</Link>
{me.noticeVersionAccepted >= me.noticeVersion && <span className="inline-flex items-center gap-1.5 px-1 py-2 text-gray-500"><CheckCircle2 className="h-4 w-4 text-green-600" aria-hidden /> You&apos;ve read the latest <a href="/privacy" className="text-brand underline">privacy notice</a></span>}
</div>
</div>
);
}
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 icon={<User className="h-4 w-4" />} sub="Change them here and the church's sites get them too.">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 icon={<ShieldCheck className="h-4 w-4" />}>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 icon={<Lock className="h-4 w-4" />}>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 icon={<ActivityIcon className="h-4 w-4" />} 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>
);
}