"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 = { 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 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(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("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 ; const first = me.name.split(" ")[0] || me.name; return ( {section === "overview" ? `Hi, ${first}` : s.title} {msg && {msg.text}} {section === "overview" && } {section === "details" &&
} {section === "security" &&
} {section === "privacy" &&
} {section === "activity" &&
}
); } // ─── 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 = { events: Calendar, website: Globe, app: Smartphone }; function Overview({ me }: { me: Me }) { const branding = useBranding(); const [apps, setApps] = useState(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 (

Go to

{apps === null &&

Loading…

} {apps && !apps.length && (

{branding.name}'s sites and apps will show here once they sign people in with this account.

)} {apps && apps.length > 0 && (
{apps.map((a) => { const Icon = APP_ICONS[a.product] ?? Globe; return ( {a.name} {a.description && {a.description}} {a.url.replace(/^https?:\/\//, "").replace(/\/.*$/, "")} ); })}
)}

Your account

{checks.map((c) => { const Icon = c.icon; return ( {c.label} {c.detail} ); })}
Change your details Download your data {me.noticeVersionAccepted >= me.noticeVersion && You've read the latest privacy notice}
); } 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 ( } sub="Change them here and the church's sites get them too.">Your details
{ 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); }}>

Email address: {me.email}

{!changingEmail ? ( ) : (
{ 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); }}> )}
); } 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(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 ( }>Signing in

Two-step sign-in: {me.twoFactor ? on, with {METHOD[me.twoFactor]} : off} {me.twoFactor && · {me.recoveryCodesLeft} recovery codes left}

{codes && ( Save these recovery codes somewhere safe. Each works once; they won't be shown again.
{codes.join("\n")}
)} {setup ? (
{ 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 && QR code for your authenticator app} {setup.secret &&

Key: {setup.secret}

} {setup.sentTo &&

We sent a code to {setup.sentTo}.

}
) : (
)} {me.twoFactor && !setup && ( { 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" && ( { 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); }} /> )}
{ 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); }}>
); } function PasswordAction({ label, button, danger, onSubmit }: { label: string; button: string; danger?: boolean; onSubmit: (password: string) => void }) { const [open, setOpen] = useState(false); if (!open) return

; return (
{ e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("password"))); setOpen(false); }}>
); } function Privacy({ me, onDone, onFail }: Props) { const [exports, setExports] = useState([]); 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 ( }>Privacy
{ 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); }}>

Read the privacy notice

Download my data

Everything the church's sites hold about you, in one file. It takes a few minutes; we'll email you when it's ready.

{exports.map((x) => (

{when(x.createdAt)}: {x.status === "ready" ? Download : x.status === "collecting" ? "being put together…" : "expired"}

))}

Delete my account

{!confirmDelete ? ( ) : (
{ 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); }}> You'll be signed out of all the church'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're booked for is over).
)}
); } function Activity({ onDone }: { onDone: (t: string) => void }) { const [items, setItems] = useState([]); 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 ( } sub="If you see something you don't recognise, change your password and sign out everywhere.">Recent activity
    {items.map((e, i) => (
  • {EVENT[e.type] ?? e.type}{e.site ? · {e.site.replace(/^https?:\/\//, "")} : null} {when(e.at)}
  • ))} {!items.length &&
  • Nothing yet.
  • }
); }