NGU-Web/src/pages/admin/AdminPanel.tsx
Zaldimmar b816203c0c Accessibility: reading and color blind modes, audit fixes, calendar window
- Accessibility panel: the switch knob stays in its track; the panel
  follows its button in the Tab order and opens on its first switch.
- Reading mode is the page as plain text: one column, no colors,
  pictures, cards or motion; descriptions stay in place.
- Color blind mode (protanopia, deuteranopia, tritanopia, monochrome):
  palette swaps chosen by simulation, applied to code, data and CSS
  colors on public pages only. The newsletter uses the stored palette.
- Audit fixes: focus not hidden by the header, focus on page change
  and in-page jumps, focus return for the menu, day list and people
  details, labelled admin fields and dialogs, keyboard map tiles,
  scrollable tables, and more.
- Calendar asks /events for its six weeks only (?from=&to=); carousels
  take their 12 most recent past events (?past=12).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 14:33:09 -05:00

460 lines
17 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
ADMIN PANEL
Superadmin only, guarded by RequireRole on the route and by
requireRole("superadmin") on every endpoint it calls. This page
assumes neither: it renders whatever the API gives it and shows
whatever the API refuses.
Four blocks, deliberately boring:
System what's actually running, for when something is off
Content row counts, the cheapest "is the database there"
Accounts roles, access and live sessions
Google groups check someone's groups, re-sync every group
account (server/src/accessGroups.js)
A group account's role comes from its Google group, so its role
select is locked; Disable still works, and sticks.
The role select is driven by ROLES from lib/roles.ts, so a new
rung on the ladder appears here without this file changing. The
legend beside it is the same list: four roles is past the
point where "Editor" explains itself.
Every account write signs that person out, which the server
does rather than this page. Two things you can't do here: edit
your own row, or take the last active superadmin away. Both are
enforced server-side and mirrored in the disabled states, so
the reason shows up before the click rather than after it.
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useState } from "react";
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { useNavigate } from "react-router-dom";
import { ROLES, ROLE_LABELS, ROLE_NOTES, isSuper } from "../../lib/roles.ts";
/* SQLite hands back "2026-09-22 04:11:07": UTC, but without the
marker that says so. Left alone, browsers read it as local time
and last-login drifts by the timezone offset. */
function when(value) {
if (!value) return "-";
const iso = value.includes("T") ? value : `${value.replace(" ", "T")}Z`;
const date = new Date(iso);
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
function uptime(seconds) {
if (seconds == null) return "-";
const d = Math.floor(seconds / 86400);
const h = Math.floor((seconds % 86400) / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (d) return `${d}d ${h}h`;
if (h) return `${h}h ${m}m`;
return `${m}m`;
}
function Block({ title, note, children }: any) {
return (
<section className="mt-8 first:mt-0">
<div className="flex items-baseline gap-3">
<h2 className="text-lg font-bold text-link">{title}</h2>
{note && <p className="text-sm text-muted">{note}</p>}
</div>
<div className="mt-3">{children}</div>
</section>
);
}
function Stat({ label, value }) {
return (
<div className="border border-brand/20 bg-surface px-4 py-3">
<div className="text-xs font-medium uppercase tracking-wider text-muted/70">
{label}
</div>
<div className="mt-1 break-words text-sm font-medium text-ink">{value}</div>
</div>
);
}
/* Google groups: what's set, who a group would let in, and a
re-sync of every group account. */
function AccessGroups({ access, onSynced }) {
const [email, setEmail] = useState("");
const [busy, setBusy] = useState<"check" | "sync" | null>(null);
const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
const [changes, setChanges] = useState<string[]>([]);
const groups = Object.entries(access?.groups ?? {});
async function send(kind: "check" | "sync") {
setBusy(kind);
setNote(null);
setChanges([]);
try {
if (kind === "check") {
const { role } = await post("/admin/panel/access-check", { email });
setNote(
role
? { tone: "ok", text: `${email} would sign in as ${ROLE_LABELS[role] ?? role}.` }
: { tone: "error", text: `${email} isn't in any of these groups.` },
);
} else {
const result = await post("/admin/panel/access-sync", {});
setNote({
tone: result.failed.length ? "error" : "ok",
text:
`Checked ${result.checked} group account${result.checked === 1 ? "" : "s"}, ` +
`${result.changes.length} changed` +
(result.failed.length ? `, ${result.failed.length} couldn't be checked.` : "."),
});
setChanges([...result.changes, ...result.failed]);
onSynced();
}
} catch (err) {
setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." });
} finally {
setBusy(null);
}
}
const button =
"btn border border-brand px-4 py-1.5 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
return (
<Block
title="Google groups"
note="Members of these groups sign in with Google and get the group's role. Set them in Site settings → Access."
>
{!access?.directory && (
<p className="mb-3 text-sm text-danger">
Group lookups aren't set up on the server (GOOGLE_DIRECTORY_AS, docs/google-sign-in.md).
</p>
)}
{groups.length > 0 ? (
<dl className="mb-4 grid gap-x-6 gap-y-1.5 text-sm sm:grid-cols-3">
{groups.map(([role, group]) => (
<div key={role}>
<dt className="font-medium text-ink">{ROLE_LABELS[role] ?? role}</dt>
<dd className="break-all text-muted">{group as string}</dd>
</div>
))}
</dl>
) : (
<p className="mb-4 text-sm text-muted">No groups set: accounts come from admin-cli only.</p>
)}
<div className="flex flex-wrap items-center gap-3">
<label htmlFor="access-check" className="sr-only">
Email to check
</label>
<input
id="access-check"
type="email"
value={email}
placeholder="someone@nextgenerationofunity.org"
onChange={(e) => setEmail(e.target.value)}
className="min-w-0 flex-1 border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25 sm:max-w-sm"
/>
<button type="button" className={button} disabled={busy !== null || !email.trim()} onClick={() => send("check")}>
{busy === "check" ? "Checking…" : "Check their groups"}
</button>
<button type="button" className={button} disabled={busy !== null} onClick={() => send("sync")}>
{busy === "sync" ? "Re-syncing…" : "Re-sync now"}
</button>
</div>
{note && (
<p role="status" className={`mt-3 text-sm ${note.tone === "ok" ? "text-link" : "text-danger"}`}>
{note.text}
</p>
)}
{changes.length > 0 && (
<ul className="mt-2 space-y-1 text-xs text-muted">
{changes.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
)}
</Block>
);
}
export default function AdminPanel() {
const { user: me } = useAuth();
const navigate = useNavigate();
const [data, setData] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<any>(null);
// Which row is mid-request, and what went wrong on it. Scoped to
// the row so a failure on one account doesn't blank the table.
const [busyId, setBusyId] = useState<any>(null);
const [rowError, setRowError] = useState<any>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
setData(await get("/admin/panel/overview", { ttl: 0 }));
} catch (err: any) {
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
setError(err.message || "Couldn't load the panel.");
} finally {
setLoading(false);
}
}, [navigate]);
useEffect(() => {
load();
}, [load]);
// After a re-sync: the accounts table again, without the loading
// screen (which would clear the sync's result).
const refresh = async () => {
try {
setData(await get("/admin/panel/overview", { ttl: 0 }));
} catch {
// The table stays as it was; the next load shows any error.
}
};
/* Replace the one row the server returns rather than refetching
the whole overview; the counts didn't change. */
function mergeUser(updated) {
setData((current) =>
current
? {
...current,
users: current.users.map((u) => (u.id === updated.id ? updated : u)),
}
: current,
);
}
async function run(id, work) {
setBusyId(id);
setRowError(null);
try {
mergeUser(await work());
} catch (err: any) {
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
setRowError({ id, message: err.message || "That didn't work." });
} finally {
setBusyId(null);
}
}
const changeRole = (row, role) =>
run(row.id, async () => (await patch(`/admin/panel/users/${row.id}`, { role })).user);
const setActive = (row, is_active) =>
run(
row.id,
async () => (await patch(`/admin/panel/users/${row.id}`, { is_active })).user,
);
const revoke = (row) =>
run(row.id, async () => (await del(`/admin/panel/users/${row.id}/sessions`)).user);
if (loading) {
return (
<p className="py-12 text-muted" role="status">
Loading the panel…
</p>
);
}
if (error) {
return (
<div className="py-12">
<p className="text-danger">{error}</p>
<button
type="button"
onClick={load}
className="mt-3 btn border border-brand px-4 py-1.5 text-sm text-link transition-colors hover:bg-tint"
>
Try again
</button>
</div>
);
}
const { system, content, users, access } = data;
const activeSupers = users.filter(
(u) => isSuper(u) && u.is_active === 1,
).length;
return (
<div>
<h1 className="text-2xl font-bold text-link">Panel</h1>
<p className="mt-1 text-muted">
Accounts and server state. Everything here is superadmin-only.
</p>
<Block title="System">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<Stat label="Schema version" value={system.schemaVersion} />
<Stat label="API uptime" value={uptime(system.uptimeSeconds)} />
<Stat label="Started" value={when(system.startedAt)} />
<Stat label="Node" value={system.nodeVersion} />
<Stat label="Platform" value={system.platform} />
<Stat label="Live sessions" value={system.sessions} />
</div>
{system.dbPath && (
<p className="mt-3 font-mono text-xs text-muted/70">{system.dbPath}</p>
)}
</Block>
<Block title="Content" note="Row counts, straight from the tables.">
<div className="flex flex-wrap gap-2">
{content.map((row) => (
<span
key={row.label}
className="border border-brand/20 bg-surface px-3 py-1 text-sm text-muted"
>
{row.label}{" "}
<strong className="font-semibold text-ink">
{row.count ?? "-"}
</strong>
</span>
))}
</div>
</Block>
<Block
title="Accounts"
note="Changing a role or disabling an account signs that person out."
>
<div className="overflow-x-auto border border-brand/20 bg-surface">
<table className="w-full min-w-[46rem] text-left text-sm">
<thead className="border-b border-brand/15 text-xs uppercase tracking-wider text-muted/70">
<tr>
<th className="px-4 py-3 font-medium">Account</th>
<th className="px-4 py-3 font-medium">Role</th>
<th className="px-4 py-3 font-medium">Last login</th>
<th className="px-4 py-3 font-medium">Sessions</th>
<th className="px-4 py-3 font-medium">Access</th>
</tr>
</thead>
<tbody className="divide-y divide-brand/10">
{users.map((row) => {
const isMe = row.id === me?.id;
const lastSuper =
isSuper(row) && row.is_active === 1 && activeSupers <= 1;
const locked = isMe || lastSuper;
const fromGroup = row.access_source === "group";
const busy = busyId === row.id;
return (
<tr key={row.id} className={row.is_active ? "" : "bg-tint-soft"}>
<td className="px-4 py-3">
<div className="font-medium text-ink">
{row.name || row.email}
{isMe && (
<span className="ml-2 text-xs font-normal text-muted/70">
you
</span>
)}
</div>
{row.name && (
<div className="text-xs text-muted/80">{row.email}</div>
)}
{fromGroup && (
<div className="mt-1 text-xs text-muted">
Google group
{row.group_disabled === 1 && ": in no access group"}
</div>
)}
{rowError?.id === row.id && (
<div className="mt-1 text-xs text-danger">
{rowError.message}
</div>
)}
</td>
<td className="px-4 py-3">
<select
value={row.role}
disabled={locked || busy || fromGroup}
onChange={(e) => changeRole(row, e.target.value)}
aria-label={`Role for ${row.name || row.email}`}
className="border border-brand/30 bg-surface px-2 py-1 text-sm text-ink disabled:cursor-not-allowed disabled:bg-tint-soft disabled:text-muted/60"
title={
fromGroup
? "The role comes from this person's Google group."
: isMe
? "You can't change your own role."
: lastSuper
? "The last active superadmin can't be demoted."
: ROLE_NOTES[row.role]
}
>
{ROLES.map((r) => (
<option key={r} value={r}>
{ROLE_LABELS[r]}
</option>
))}
</select>
</td>
<td className="px-4 py-3 text-muted">{when(row.last_login_at)}</td>
<td className="px-4 py-3">
<span className="text-muted">{row.sessions}</span>
{row.sessions > 0 && (
<button
type="button"
disabled={busy}
onClick={() => revoke(row)}
className="ml-3 text-xs font-medium text-link underline-offset-4 hover:underline disabled:opacity-50"
>
Sign out
</button>
)}
</td>
<td className="px-4 py-3">
<button
type="button"
disabled={locked || busy}
onClick={() => setActive(row, row.is_active ? 0 : 1)}
className={`btn border px-3 py-1 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
row.is_active
? "border-muted/30 text-muted hover:border-danger/50 hover:text-danger"
: "border-brand/40 text-link hover:bg-tint"
}`}
>
{row.is_active ? "Disable" : "Enable"}
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{/* Each rung adds to the one above it. Worth stating, because
"Editor" doesn't tell you where the line falls. */}
<dl className="mt-4 grid gap-x-6 gap-y-1.5 text-sm sm:grid-cols-2">
{ROLES.map((role) => (
<div key={role} className="flex gap-2">
<dt className="shrink-0 font-medium text-ink">
{ROLE_LABELS[role]}
</dt>
<dd className="text-muted">{ROLE_NOTES[role]}</dd>
</div>
))}
</dl>
<p className="mt-4 text-xs text-muted/80">
New accounts are created with <code>admin-cli.js</code> on the server, or by signing in
with Google while in one of the groups below.
</p>
</Block>
<AccessGroups access={access} onSynced={refresh} />
</div>
);
}