- 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>
282 lines
15 KiB
TypeScript
282 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
|
|
import React, { useState } from "react";
|
|
import QRCode from "qrcode";
|
|
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
|
import { useBranding } from "@/components/BrandingProvider";
|
|
import { NoticeText } from "@/components/NoticeText";
|
|
import { call, type ApiError } from "@/lib/api";
|
|
import { useExternalEffect } from "@/lib/hooks";
|
|
|
|
type State = {
|
|
uid: string;
|
|
stage: "password" | "verify_email" | "two_factor" | "setup_two_factor" | "notice" | "news" | "done";
|
|
product: string;
|
|
signupEnabled: boolean;
|
|
loginHint?: string | null;
|
|
screen?: "signin" | "signup";
|
|
name?: string;
|
|
email?: string;
|
|
sentTo?: string;
|
|
method?: "totp" | "email" | "whatsapp";
|
|
methods?: string[];
|
|
why?: "admin" | "product";
|
|
notice?: { version: number; title: string; body: string };
|
|
updated?: boolean;
|
|
redirectTo?: string;
|
|
recoveryCodes?: string[];
|
|
};
|
|
|
|
/**
|
|
* One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). The backend says which step comes next;
|
|
* when it's done, the browser goes back to the product it came from.
|
|
*/
|
|
export function SignIn({ uid }: { uid: string }) {
|
|
const branding = useBranding();
|
|
const [state, setState] = useState<State | null>(null);
|
|
const [error, setError] = useState<ApiError | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const [mode, setMode] = useState<"signin" | "signup">("signin");
|
|
const [codes, setCodes] = useState<{ codes: string[]; next: State } | null>(null);
|
|
const [opened, setOpened] = useState(false);
|
|
|
|
// New recovery codes (2FA just set up, or moved in from Cross Events without them) are shown
|
|
// first, whatever comes next.
|
|
const go = (s: State) => {
|
|
if (s.stage === "done" && s.redirectTo) {
|
|
window.location.assign(s.redirectTo);
|
|
return;
|
|
}
|
|
setState(s);
|
|
};
|
|
const apply = (s: State) => {
|
|
if (!opened) {
|
|
setOpened(true);
|
|
if (s.screen === "signup" && s.signupEnabled) setMode("signup");
|
|
}
|
|
if (s.recoveryCodes?.length) {
|
|
setCodes({ codes: s.recoveryCodes, next: s });
|
|
return;
|
|
}
|
|
go(s);
|
|
};
|
|
|
|
useExternalEffect(() => {
|
|
let alive = true;
|
|
call<State>("GET", `/interaction/${encodeURIComponent(uid)}/state`).then((r) => {
|
|
if (!alive) return;
|
|
if (r.ok) apply(r.data);
|
|
else setError(r.error);
|
|
});
|
|
return () => { alive = false; };
|
|
}, [uid]);
|
|
|
|
const submit = async (path: string, body: unknown) => {
|
|
setBusy(true);
|
|
setError(null);
|
|
const r = await call<State>("POST", `/interaction/${encodeURIComponent(uid)}${path}`, body);
|
|
setBusy(false);
|
|
if (r.ok) apply(r.data);
|
|
else setError(r.error);
|
|
return r;
|
|
};
|
|
|
|
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
|
|
|
|
if (codes) {
|
|
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
|
|
}
|
|
if (!state) {
|
|
return frame(error ? (
|
|
<>
|
|
<Heading icon={<AlertTriangle className="h-5 w-5" />}>We couldn't continue</Heading>
|
|
<Notice tone="error">{error.message}</Notice>
|
|
</>
|
|
) : <p className="text-gray-600">Loading…</p>);
|
|
}
|
|
|
|
const err = error ? <Notice tone="error">{error.message}</Notice> : null;
|
|
const fieldError = (name: string) => error?.fields?.[name] ?? null;
|
|
|
|
switch (state.stage) {
|
|
case "password":
|
|
return frame(mode === "signin"
|
|
? <PasswordStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/password", b)} onSignUp={() => { setError(null); setMode("signup"); }} />
|
|
: <SignUpStep busy={busy} err={err} fieldError={fieldError} onSubmit={(b) => submit("/signup", b)} onBack={() => { setError(null); setMode("signin"); }} />);
|
|
case "verify_email":
|
|
return frame(<CodeStep title="Check your email" sub={<>We sent a 6-digit code to <strong>{state.sentTo}</strong>. Enter it to confirm your email address.</>} busy={busy} err={err} onSubmit={(code) => submit("/verify-email", { code })} onResend={() => submit("/resend", {})} />);
|
|
case "two_factor":
|
|
return frame(<TwoFactorStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/two-factor", b)} onResend={() => submit("/resend", {})} />);
|
|
case "setup_two_factor":
|
|
return frame(<SetupStep uid={uid} state={state} busy={busy} err={err} setError={setError} onConfirm={(b) => submit("/two-factor/setup/confirm", b)} />);
|
|
case "notice":
|
|
return frame(<NoticeStep state={state} busy={busy} err={err} onAccept={() => submit("/notice", { version: state.notice!.version })} />);
|
|
case "news":
|
|
return frame(<NewsStep busy={busy} err={err} onSubmit={(b) => submit("/news", b)} />);
|
|
default:
|
|
return frame(<p className="text-gray-600">Taking you back…</p>);
|
|
}
|
|
}
|
|
|
|
function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onSignUp: () => void }) {
|
|
const branding = useBranding();
|
|
return (
|
|
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email"), password: f.get("password"), remember: f.get("remember") === "on" }); }}>
|
|
<Heading icon={<LogIn className="h-5 w-5" />} sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
|
{err}
|
|
<Field label="Email address" name="email" type="email" autoComplete="username" required defaultValue={state.loginHint ?? ""} />
|
|
<Field label="Password" name="password" type="password" autoComplete="current-password" required />
|
|
<Checkbox name="remember" label="Keep me signed in on this device" defaultChecked />
|
|
<Button type="submit" busy={busy} className="w-full">Sign in</Button>
|
|
<div className="mt-4 flex flex-wrap justify-between gap-2 text-sm">
|
|
<a href={`/forgot?uid=${encodeURIComponent(state.uid)}`} className="text-brand underline">Forgot your password?</a>
|
|
{state.signupEnabled && <button type="button" onClick={onSignUp} className="text-brand underline">Create an account</button>}
|
|
</div>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean; err: React.ReactNode; fieldError: (n: string) => string | null; onSubmit: (b: object) => void; onBack: () => void }) {
|
|
const branding = useBranding();
|
|
const [phone, setPhone] = useState("");
|
|
return (
|
|
<form onSubmit={(e) => {
|
|
e.preventDefault();
|
|
const f = new FormData(e.currentTarget);
|
|
onSubmit({ name: f.get("name"), email: f.get("email"), phone: f.get("phone") || undefined, password: f.get("password"), acceptNotice: f.get("acceptNotice") === "on", newsEmail: f.get("newsEmail") === "on", newsWhatsApp: f.get("newsWhatsApp") === "on", remember: true });
|
|
}}>
|
|
<Heading icon={<UserPlus className="h-5 w-5" />} sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
|
{err}
|
|
<Field label="Your name" name="name" autoComplete="name" required error={fieldError("name")} />
|
|
<Field label="Email address" name="email" type="email" autoComplete="email" required error={fieldError("email")} />
|
|
<Field label="Mobile number (optional)" name="phone" type="tel" autoComplete="tel" value={phone} onChange={(e) => setPhone(e.target.value)} error={fieldError("phone")} hint="For WhatsApp messages, if you'd like them." />
|
|
<Field label="Password" name="password" type="password" autoComplete="new-password" required minLength={8} error={fieldError("password")} hint="At least 8 characters." />
|
|
<Checkbox name="newsEmail" label="Send me church news by email" />
|
|
{phone && <Checkbox name="newsWhatsApp" label="Send me church news on WhatsApp" />}
|
|
<Checkbox name="acceptNotice" required label={<>I've read the <a href="/privacy" target="_blank" className="text-brand underline">privacy notice</a></>} hint={fieldError("acceptNotice") ?? undefined} />
|
|
<Button type="submit" busy={busy} className="w-full">Create account</Button>
|
|
<p className="mt-4 text-sm"><button type="button" onClick={onBack} className="text-brand underline">I already have an account</button></p>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
function CodeStep({ title, sub, busy, err, onSubmit, onResend }: { title: string; sub: React.ReactNode; busy: boolean; err: React.ReactNode; onSubmit: (code: string) => void; onResend?: () => void }) {
|
|
return (
|
|
<form onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("code") ?? "")); }}>
|
|
<Heading icon={<Mail className="h-5 w-5" />} sub={sub}>{title}</Heading>
|
|
{err}
|
|
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9 ]{6,7}" required autoFocus />
|
|
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
|
{onResend && <p className="mt-4 text-sm"><button type="button" onClick={onResend} className="text-brand underline">Send a new code</button></p>}
|
|
</form>
|
|
);
|
|
}
|
|
|
|
function TwoFactorStep({ state, busy, err, onSubmit, onResend }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onResend: () => void }) {
|
|
const [recovery, setRecovery] = useState(false);
|
|
if (recovery) {
|
|
return (
|
|
<form onSubmit={(e) => { e.preventDefault(); onSubmit({ recoveryCode: new FormData(e.currentTarget).get("recoveryCode") }); }}>
|
|
<Heading sub="One of the recovery codes you saved when you turned on two-step sign-in. Each works once.">Use a recovery code</Heading>
|
|
{err}
|
|
<Field label="Recovery code" name="recoveryCode" autoComplete="off" required autoFocus />
|
|
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
|
<p className="mt-4 text-sm"><button type="button" onClick={() => setRecovery(false)} className="text-brand underline">Use a code instead</button></p>
|
|
</form>
|
|
);
|
|
}
|
|
const sub = state.method === "totp" ? "Enter the 6-digit code from your authenticator app." : <>We sent a 6-digit code to <strong>{state.sentTo}</strong>.</>;
|
|
return (
|
|
<>
|
|
<CodeStep title="Second step" sub={sub} busy={busy} err={err} onSubmit={(code) => onSubmit({ code })} onResend={state.method === "totp" ? undefined : onResend} />
|
|
<p className="mt-2 text-sm"><button type="button" onClick={() => setRecovery(true)} className="text-brand underline">Use a recovery code</button></p>
|
|
</>
|
|
);
|
|
}
|
|
|
|
function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string; state: State; busy: boolean; err: React.ReactNode; setError: (e: ApiError | null) => void; onConfirm: (b: object) => void }) {
|
|
const [started, setStarted] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string } | null>(null);
|
|
const [qr, setQr] = useState<string | null>(null);
|
|
const start = async (method: string) => {
|
|
setError(null);
|
|
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", `/interaction/${encodeURIComponent(uid)}/two-factor/setup`, { method });
|
|
if (!r.ok) return setError(r.error);
|
|
setStarted(r.data);
|
|
if (r.data.otpauthUrl) setQr(await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }));
|
|
};
|
|
const why = state.why === "admin" ? "Admins must use a second step when they sign in." : `${state.product} asks for a second step when you sign in.`;
|
|
if (!started) {
|
|
const labels: Record<string, [string, string]> = {
|
|
totp: ["An authenticator app", "Google Authenticator, Microsoft Authenticator, 1Password… Most secure, works without signal."],
|
|
email: ["A code by email", `Sent to ${state.email}.`],
|
|
whatsapp: ["A code on WhatsApp", "Sent to your mobile number."],
|
|
};
|
|
return (
|
|
<>
|
|
<Heading icon={<ShieldCheck className="h-5 w-5" />} sub={why}>Set up two-step sign-in</Heading>
|
|
{err}
|
|
<div className="space-y-2">
|
|
{(state.methods ?? []).map((m) => (
|
|
<button key={m} type="button" onClick={() => start(m)} className="w-full rounded-lg border p-3 text-left hover:border-brand">
|
|
<span className="block font-medium">{labels[m]?.[0] ?? m}</span>
|
|
<span className="block text-sm text-gray-600">{labels[m]?.[1]}</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</>
|
|
);
|
|
}
|
|
return (
|
|
<form onSubmit={(e) => { e.preventDefault(); onConfirm({ method: started.method, code: new FormData(e.currentTarget).get("code") }); }}>
|
|
<Heading sub={started.method === "totp" ? "Scan this with your authenticator app, then enter the code it shows." : <>We sent a code to <strong>{started.sentTo}</strong>.</>}>
|
|
{started.method === "totp" ? "Scan the QR code" : "Enter the code"}
|
|
</Heading>
|
|
{err}
|
|
{qr && <img src={qr} alt="QR code for your authenticator app" className="mx-auto mb-3 h-48 w-48" />}
|
|
{started.secret && <p className="mb-4 break-all text-center font-mono text-sm text-gray-600">Or type this key: {started.secret}</p>}
|
|
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required autoFocus />
|
|
<Button type="submit" busy={busy} className="w-full">Turn on</Button>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void }) {
|
|
const text = codes.join("\n");
|
|
return (
|
|
<>
|
|
<Heading icon={<KeyRound className="h-5 w-5" />} sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
|
<pre className="mb-4 rounded-lg bg-gray-50 p-4 text-center font-mono text-sm leading-7">{text}</pre>
|
|
<div className="mb-4 flex gap-2">
|
|
<Button type="button" variant="secondary" onClick={() => navigator.clipboard?.writeText(text)}>Copy</Button>
|
|
<a className="rounded-lg border px-4 py-2.5 text-sm" download="recovery-codes.txt" href={`data:text/plain;charset=utf-8,${encodeURIComponent(text)}`}>Download</a>
|
|
</div>
|
|
<Button type="button" className="w-full" onClick={onDone}>I've saved them</Button>
|
|
</>
|
|
);
|
|
}
|
|
|
|
function NoticeStep({ state, busy, err, onAccept }: { state: State; busy: boolean; err: React.ReactNode; onAccept: () => void }) {
|
|
return (
|
|
<>
|
|
<Heading icon={<FileText className="h-5 w-5" />} sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
|
{err}
|
|
<div className="mb-4 max-h-80 overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={state.notice!.body} compact /></div>
|
|
<Button type="button" busy={busy} className="w-full" onClick={onAccept}>I've read it</Button>
|
|
</>
|
|
);
|
|
}
|
|
|
|
function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void }) {
|
|
const branding = useBranding();
|
|
return (
|
|
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" }); }}>
|
|
<Heading icon={<Megaphone className="h-5 w-5" />} sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
|
{err}
|
|
<Checkbox name="email" label="Yes, by email" />
|
|
<Checkbox name="whatsapp" label="Yes, on WhatsApp" hint="If your mobile number is on your account." />
|
|
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
|
</form>
|
|
);
|
|
}
|