Files
crosscode-platform/apps/events/frontend/src/components/admin/SignInTab.tsx
T
joshuaandClaude Opus 5.5 70c471666b Accounts sign-in looks like the church's site; Events sends its logo and colours
- @crosscode/ui: Shell with the church's colour wash, logo (or its initial)
  and name, footer; Card edged in the church's colour; Heading with an
  icon tile. Icons on every sign-in step.
- contracts 1.9.0: churchLookSchema (logo, accent colour) in import.begin;
  church.branding request. Accounts fills (move) or replaces (button) the
  church profile's name, logo and colours.
- Events 3.1.0: src/accounts/look.ts (logo as a full address), sent with a
  move; Settings -> Sign-in "Use this site's logo and colours".
Tests: Accounts 55, contracts 218, Events 774, test:accounts 16.

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

203 lines
12 KiB
TypeScript

"use client";
import React, { useEffect, useState } from "react";
import { LogIn } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiV2, type V2Result } from "@/lib/apiV2";
import { errorMessage } from "@/lib/utils";
import { AccountsMessaging } from "@/components/admin/AccountsMessaging";
type Status = V2Result<"/settings/sign-in", "get">["data"];
type Check = V2Result<"/settings/sign-in/check", "post">["data"];
type Report = { created: number; linked: { name: string; email: string }[]; refused: { name: string; email: string; reason: string }[]; skipped: number; accountsAdmins: { name: string }[]; by: string; movedAt: string };
const when = (iso: string | null | undefined) =>
iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "";
/**
* Site settings → Sign-in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): where people sign in, and moving
* sign-in to the church's Accounts: Check (nothing changes), Move (with which admins also manage
* Accounts), and Undo for 14 days.
*/
export function SignInTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [status, setStatus] = useState<Status | null>(null);
const [checked, setChecked] = useState<Check | null>(null);
const [admins, setAdmins] = useState<Set<string>>(new Set());
const [keepAccountsNotices, setKeepAccountsNotices] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
// 3.1.0: what Accounts can send (the move needs its email).
const [sending, setSending] = useState<{ email: boolean; whatsapp: boolean } | null>(null);
useEffect(() => {
if (!active || !token) return;
let alive = true;
apiV2("get", "/settings/sign-in", { authToken: token })
.then(({ data }) => { if (alive) setStatus(data); })
.catch((e) => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load the sign-in settings." }); });
return () => { alive = false; };
}, [active, token]);
if (!token) return null;
if (!status) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
const auth = { authToken: token };
const runCheck = async () => {
setBusy("check");
setMsg(null);
try {
const { data } = await apiV2("post", "/settings/sign-in/check", auth);
setChecked(data);
setAdmins(new Set(data.admins.map((a) => a.id)));
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "The check didn't work." });
}
setBusy(null);
};
const runMove = async () => {
if (!checked) return;
if (!window.confirm(`Move sign-in to your church's Accounts now? ${checked.toMove} people will sign in there from now on, with the passwords they have today.`)) return;
setBusy("move");
setMsg(null);
try {
const { data } = await apiV2("post", "/settings/sign-in/move", { ...auth, body: { adminIds: [...admins], ...(checked.noticeConflict ? { keepAccountsNotices } : {}) } });
setStatus(data);
setChecked(null);
setMsg({ ok: true, text: "Sign-in now goes through your church's Accounts. People already signed in stay signed in." });
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "The move didn't finish. Nothing was switched; you can try again." });
}
setBusy(null);
};
const runUndo = async () => {
if (!window.confirm("Go back to Cross Events' own sign-in? People sign in with the password they had at the move. Changes made in Accounts since then (a new password, two-step sign-in) don't come back here.")) return;
setBusy("undo");
setMsg(null);
try {
const { data } = await apiV2("post", "/settings/sign-in/undo", auth);
setStatus(data);
setMsg({ ok: true, text: "Sign-in is back in Cross Events." });
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "Undo didn't work." });
}
setBusy(null);
};
const report = status.report as Report | null;
return (
<div className="space-y-6">
<div>
<h2 className="flex items-center gap-2 text-lg font-semibold"><LogIn className="h-5 w-5 text-brand-600" aria-hidden /> Sign-in</h2>
<p className="text-sm text-gray-600 mt-1">
{status.mode === "accounts"
? "People sign in with their church account, the same one they use for the church's other sites and apps. Passwords and two-step sign-in are managed there."
: "People sign in with a Cross Events password. You can move sign-in to your church's Accounts, so one account works for all the church's sites and apps."}
</p>
</div>
{msg && <p className={`text-sm rounded-lg px-3 py-2 ${msg.ok ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`} role="status">{msg.text}</p>}
{status.accountsConnected && <AccountsMessaging onReady={setSending} />}
{status.accountsConnected && (
<section className="border rounded-xl p-4 flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-[16rem]">
<h3 className="font-medium">How the sign-in page looks</h3>
<p className="text-sm text-gray-600">The church&apos;s sign-in page uses its name, logo and colours. Moving sign-in copies this site&apos;s when it has none; this replaces them with this site&apos;s now.</p>
</div>
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy} onClick={async () => {
setBusy("look");
setMsg(null);
try {
await apiV2("post", "/settings/sign-in/look", auth);
setMsg({ ok: true, text: "The sign-in page now uses this site's logo and colours." });
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "That didn't work." });
}
setBusy(null);
}}>{busy === "look" ? "Sending…" : "Use this site's logo and colours"}</button>
</section>
)}
{status.mode === "accounts" ? (
<section className="border rounded-xl p-4 space-y-3">
<p className="text-sm"><span className="font-medium">Through Accounts</span>{status.accountsUrl ? <> at <a className="underline" href={status.accountsUrl} target="_blank" rel="noreferrer">{status.accountsUrl.replace(/^https?:\/\//, "")}</a></> : null}{status.movedAt ? `, since ${when(status.movedAt)}` : ""}.</p>
{report && (
<ul className="text-sm text-gray-700 list-disc pl-5 space-y-1">
<li>{report.created} people moved{report.by ? ` (by ${report.by})` : ""}.</li>
{report.linked.length > 0 && <li>{report.linked.length} already had an account and were linked to it: {report.linked.map((l) => l.email).join(", ")}.</li>}
{report.refused.length > 0 && <li>{report.refused.length} couldn&apos;t move: {report.refused.map((r) => `${r.email} (${r.reason})`).join("; ")}.</li>}
<li>{report.skipped} guests and deleted people stay in Cross Events only.</li>
<li>Also Accounts admins: {report.accountsAdmins.map((a) => a.name).join(", ") || "nobody"}.</li>
</ul>
)}
{status.undoUntil && !status.secretsCleared ? (
<div className="flex flex-wrap items-center gap-3">
<button type="button" onClick={runUndo} disabled={!!busy} className="px-3 py-2 rounded-lg border text-sm">{busy === "undo" ? "Going back…" : "Undo the move"}</button>
<span className="text-xs text-gray-500">Possible until {when(status.undoUntil)}. After that, Cross Events removes the old passwords.</span>
</div>
) : <p className="text-xs text-gray-500">Cross Events no longer holds anyone&apos;s password.</p>}
</section>
) : !status.accountsConnected ? (
<section className="border rounded-xl p-4">
<p className="text-sm text-gray-700">Connect your church&apos;s Accounts first, under <span className="font-medium">Linked products</span>. Ask Cross Code to install Accounts if it isn&apos;t listed there.</p>
</section>
) : (
<section className="border rounded-xl p-4 space-y-4">
<div className="flex flex-wrap items-center gap-3">
<button type="button" onClick={runCheck} disabled={!!busy || status.running} className="px-3 py-2 rounded-lg border text-sm">{busy === "check" ? "Checking…" : checked ? "Check again" : "Check the move"}</button>
<span className="text-xs text-gray-500">Nothing changes until you press Move.</span>
</div>
{checked && (
<div className="space-y-4">
<ul className="text-sm text-gray-700 list-disc pl-5 space-y-1">
<li>{checked.wouldCreate} people move with their current password{checked.withTwoFactor ? `; ${checked.withTwoFactor} use two-step sign-in and keep their method (they get new recovery codes the first time)` : ""}.</li>
{checked.wouldLink.length > 0 && <li>{checked.wouldLink.length} already have a church account and will be linked to it (they keep that account&apos;s password): {checked.wouldLink.map((l) => l.email).join(", ")}.</li>}
{checked.refused.length > 0 && <li className="text-red-700">{checked.refused.length} can&apos;t move: {checked.refused.map((r) => `${r.email} (${r.reason})`).join("; ")}. Fix these first, or they won&apos;t be able to sign in.</li>}
<li>{checked.skipped} guests and deleted people stay in Cross Events only.</li>
<li>Accounts {checked.accountsVersion}.</li>
</ul>
{checked.admins.length > 0 && (
<fieldset>
<legend className="text-sm font-medium mb-1">Also make these admins Accounts admins (they can manage everyone&apos;s sign-in)</legend>
{checked.admins.map((a) => (
<label key={a.id} className="flex items-center gap-2 text-sm py-0.5">
<input type="checkbox" checked={admins.has(a.id)} onChange={(e) => {
const next = new Set(admins);
if (e.target.checked) next.add(a.id); else next.delete(a.id);
setAdmins(next);
}} />
{a.name} <span className="text-gray-500">({a.email})</span>
</label>
))}
</fieldset>
)}
{checked.noticeConflict && (
<fieldset>
<legend className="text-sm font-medium mb-1">Accounts already has its own privacy notice. Which one should people see?</legend>
<label className="flex items-center gap-2 text-sm py-0.5"><input type="radio" name="notice" checked={keepAccountsNotices} onChange={() => setKeepAccountsNotices(true)} /> Keep Accounts&apos; notice (everyone accepts it at their next sign-in)</label>
<label className="flex items-center gap-2 text-sm py-0.5 text-gray-400"><input type="radio" name="notice" disabled checked={!keepAccountsNotices} readOnly /> Use Cross Events&apos; notice (remove Accounts&apos; notice in Accounts first)</label>
</fieldset>
)}
{!(sending?.email ?? checked.messaging.email) && (
<p className="text-sm font-medium text-red-800">Set up Accounts&apos; email above first (copy this site&apos;s, test it, save it): without it nobody could get a sign-in code or password link after the move.</p>
)}
{!!checked.messaging.whatsappTwoFactor && !(sending?.whatsapp ?? checked.messaging.whatsapp) && (
<p className="text-sm text-amber-800">{checked.messaging.whatsappTwoFactor} people get their codes by WhatsApp, which Accounts can&apos;t send yet: their codes will go by email until you set it up.</p>
)}
<button type="button" onClick={runMove} disabled={!!busy || (!!checked.noticeConflict && !keepAccountsNotices) || !(sending?.email ?? checked.messaging.email)} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">
{busy === "move" ? "Moving… (don't close this page)" : "Move sign-in to Accounts"}
</button>
<p className="text-xs text-gray-500">Pick a quiet time. It takes about a minute; people already signed in stay signed in. You can undo it for 14 days.</p>
</div>
)}
</section>
)}
</div>
);
}