"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 = { 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(null); const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null); const load = useCallback(async () => { const r = await call("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

Loading…

; const signOut = Sign out; return ( {me.role === "admin" && Admin}{signOut}}>

Your account

One account for all of {branding.name}'s sites and apps.

{msg && {msg.text}}
); } 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 ( 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 ( 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.
  • }
); }