NGU-Web/src/pages/admin/AdminProfiles.tsx
Aidan Dona e4c7e165d1 Profile accounts: invites, any-Google sign-in, claiming People, visibility, Discord
Migration 076 adds a member role below viewer (the site and its own
profile, never the admin: /api/admin now needs viewer), invites, person
claims, a Discord link on accounts and people.hide_* switches. Public reads
of people go through v_people_public, which nulls hidden fields, and the
views that read people are rebuilt over it.

Admins invite an email from Data -> Profile accounts (link shown once,
emailed on request). The invitee sets a password or signs in with any
Google account under that email, asks to claim their People record, and
once approved edits it and chooses what shows at /account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:14:30 -05:00

450 lines
17 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
ADMIN: PROFILE ACCOUNTS (Data → Profile accounts, admins and up)
Profile accounts (076) are by invite: an email added here gets an
account with no password and a link to set one (or to sign in
with Google under that email). The link is shown once, to copy;
Email invite sends a fresh one through Gmail and shows it too
(the one before stops working). For an account already set up,
the same link is a way back in when a password is forgotten.
Then: the claims waiting (someone asking to be a People record),
and each account's record, Discord and whether it's on. Server
side: server/src/routes/profiles.js. Admin accounts (viewer and
up) are the Panel's, not this page's.
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useId, useState, type FormEvent } from "react";
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
import { preview } from "../../lib/text.ts";
const MUTED = "var(--color-muted)";
const button =
"btn border border-brand px-3 py-1.5 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
const primary =
"btn bg-action px-5 py-2.5 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25";
const danger =
"btn border border-danger/40 px-3 py-1.5 text-sm text-danger transition-colors hover:bg-danger-tint disabled:opacity-50";
const input =
"w-full border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
type Account = {
id: number;
email: string;
name: string | null;
is_active: number;
created_at: string;
last_login_at: string | null;
invited_at: string | null;
invite_expires_at: string | null;
invite_open: number;
signed_up: number;
person_id: string | null;
person_name: string | null;
discord_id: string | null;
discord_name: string | null;
};
type Claim = {
id: number;
account_id: number;
email: string;
name: string | null;
person_id: string;
person_name: string;
message: string | null;
created_at: string;
};
const message = (err: unknown) => (err instanceof ApiError ? err.message : "Couldn't reach the server.");
const day = (value: string | null) => (value ? value.slice(0, 10) : "-");
/* A link to copy, shown once. */
function LinkBox({ link, note }: { link: string; note: string }) {
const [copied, setCopied] = useState(false);
return (
<div className="mt-3 border border-brand/20 bg-tint p-3">
<p className="text-xs" style={{ color: MUTED }}>
{note}
</p>
<div className="mt-2 flex flex-wrap items-center gap-2">
<code className="min-w-0 flex-1 break-all text-xs text-body">{link}</code>
<button
type="button"
className={button}
onClick={async () => {
try {
await navigator.clipboard.writeText(link);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
setCopied(false);
}
}}
>
{copied ? "Copied" : "Copy link"}
</button>
</div>
</div>
);
}
export default function AdminProfiles() {
const [data, setData] = useState<{ accounts: Account[]; claims: Claim[]; mail: boolean } | null>(null);
const [people, setPeople] = useState<{ id: string; label: string }[]>([]);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
get("/admin/profiles", { ttl: 0 })
.then(setData)
.catch((err) => setError(message(err)));
}, []);
useEffect(() => {
load();
get("/admin/options?only=people", { ttl: 0 })
.then((body) => setPeople(body.options.people))
.catch(() => setPeople([]));
}, [load]);
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-link">Profile accounts</h1>
<p className="text-sm" style={{ color: MUTED }}>
People with an account on the site for their own profile. By invite only.
</p>
</div>
<Invite mail={Boolean(data?.mail)} onDone={load} />
{error && <p className="mt-6 text-danger">{error}</p>}
<section className="mt-8">
<h2 className="text-lg font-bold text-ink">Claims waiting</h2>
{!data ? null : data.claims.length === 0 ? (
<p className="notice mt-3 p-4 text-sm">Nobody is waiting.</p>
) : (
<ul className="mt-3 space-y-3">
{data.claims.map((claim) => (
<ClaimRow key={claim.id} claim={claim} onDone={load} />
))}
</ul>
)}
</section>
<section className="mt-8">
<h2 className="text-lg font-bold text-ink">Accounts</h2>
{!data ? (
<div className="skeleton mt-3 !min-h-40" aria-label="Loading the accounts" />
) : data.accounts.length === 0 ? (
<p className="notice mt-3 p-4 text-sm">No profile accounts yet. Invite someone above.</p>
) : (
<ul className="mt-3 space-y-3">
{data.accounts.map((account) => (
<AccountRow key={account.id} account={account} people={people} mail={data.mail} onDone={load} />
))}
</ul>
)}
</section>
</div>
);
}
function Invite({ mail, onDone }: { mail: boolean; onDone: () => void }) {
const emailId = useId();
const nameId = useId();
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [made, setMade] = useState<{ id: number; email: string; link: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(event: FormEvent) {
event.preventDefault();
setBusy(true);
setError(null);
try {
const result = await post("/admin/profiles", { email, name });
setMade({ id: result.id, email: email.trim().toLowerCase(), link: result.link });
setEmail("");
setName("");
onDone();
} catch (err) {
setError(message(err));
} finally {
setBusy(false);
}
}
return (
<section className="mt-6 bg-raised p-5 shadow-md">
<h2 className="text-lg font-bold text-ink">Invite someone</h2>
<form onSubmit={submit} className="mt-3 flex flex-wrap items-end gap-3">
<div className="min-w-56 flex-1">
<label htmlFor={emailId} className="block text-sm font-medium text-body">
Email
</label>
<input id={emailId} type="email" value={email} onChange={(e) => setEmail(e.target.value)} className={`mt-1 ${input}`} />
</div>
<div className="min-w-48 flex-1">
<label htmlFor={nameId} className="block text-sm font-medium text-body">
Name <span className="font-normal" style={{ color: MUTED }}>(optional)</span>
</label>
<input id={nameId} value={name} onChange={(e) => setName(e.target.value)} className={`mt-1 ${input}`} />
</div>
<button type="submit" disabled={busy || !email.trim()} className={primary}>
{busy ? "Inviting…" : "Invite"}
</button>
</form>
<p className="mt-2 text-xs" style={{ color: MUTED }}>
They can sign in with a password from the link, or with Google under this email (any Google account).
</p>
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
{made && (
<>
<LinkBox
link={made.link}
note={`${made.email}'s invite link, for 14 days. Shown once: copy it, or email it from the account below.`}
/>
{mail && <EmailInvite id={made.id} label="Email this invite" onDone={(link) => setMade({ ...made, link })} />}
</>
)}
</section>
);
}
/* Email a fresh link (the last one stops working). */
function EmailInvite({ id, label, onDone }: { id: number; label: string; onDone: (link: string) => void }) {
const [state, setState] = useState<"idle" | "busy" | "sent" | string>("idle");
return (
<div className="mt-3 flex flex-wrap items-center gap-3">
<button
type="button"
className={button}
disabled={state === "busy"}
onClick={async () => {
setState("busy");
try {
const result = await post(`/admin/profiles/${id}/invite`, { email: true });
onDone(result.link);
setState("sent");
} catch (err) {
setState(message(err));
}
}}
>
{state === "busy" ? "Sending…" : label}
</button>
{state === "sent" && <span className="text-sm text-body">Sent. The link above is the one in the email.</span>}
{!["idle", "busy", "sent"].includes(state) && <span className="text-sm text-danger">{state}</span>}
</div>
);
}
function ClaimRow({ claim, onDone }: { claim: Claim; onDone: () => void }) {
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function decide(answer: "approve" | "decline") {
setBusy(true);
setError(null);
try {
await post(`/admin/profiles/claims/${claim.id}/${answer}`, {});
onDone();
} catch (err) {
setError(message(err));
setBusy(false);
}
}
return (
<li className="bg-raised p-4 shadow-sm">
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-body">
<strong>{claim.name || claim.email}</strong>
{claim.name && <span style={{ color: MUTED }}> ({claim.email})</span>} asks to be{" "}
<a href={`/admin/people/${encodeURIComponent(claim.person_id)}`} className="text-link underline">
{claim.person_name}
</a>
<span className="text-xs" style={{ color: MUTED }}>
{" "}
· {day(claim.created_at)}
</span>
</p>
<div className="flex gap-2">
<button type="button" className={button} disabled={busy} onClick={() => decide("approve")}>
Approve
</button>
<button type="button" className={danger} disabled={busy} onClick={() => decide("decline")}>
Decline
</button>
</div>
</div>
{claim.message && <p className="mt-2 text-sm text-body">“{preview(claim.message, 300)}”</p>}
{error && <p className="mt-2 text-sm text-danger">{error}</p>}
</li>
);
}
function AccountRow({
account,
people,
mail,
onDone,
}: {
account: Account;
people: { id: string; label: string }[];
mail: boolean;
onDone: () => void;
}) {
const personId = useId();
const discordId = useId();
const discordName = useId();
const [person, setPerson] = useState(account.person_id ?? "");
const [discord, setDiscord] = useState(account.discord_id ?? "");
const [discordLabel, setDiscordLabel] = useState(account.discord_name ?? "");
const [link, setLink] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function run(action: () => Promise<unknown>) {
setBusy(true);
setError(null);
try {
await action();
onDone();
} catch (err) {
setError(message(err));
} finally {
setBusy(false);
}
}
const status = !account.is_active
? "Turned off"
: account.signed_up
? `Signed up · last in ${day(account.last_login_at)}`
: account.invite_open
? `Invited · link works until ${day(account.invite_expires_at)}`
: "Invited · link expired";
return (
<li className="bg-raised shadow-sm">
<details>
<summary className="flex cursor-pointer flex-wrap items-center gap-x-4 gap-y-1 p-4">
<span className="font-semibold text-body">{account.name || account.email}</span>
{account.name && <span className="text-sm" style={{ color: MUTED }}>{account.email}</span>}
<span className="text-sm" style={{ color: MUTED }}>{status}</span>
<span className="text-sm text-body">Profile: {account.person_name ?? "-"}</span>
<span className="text-sm text-body">Discord: {account.discord_name ?? account.discord_id ?? "-"}</span>
</summary>
<div className="space-y-5 border-t border-brand/10 p-4">
<div className="flex flex-wrap items-end gap-3">
<div className="min-w-56 flex-1">
<label htmlFor={personId} className="block text-sm font-medium text-body">
Profile (People record)
</label>
<select id={personId} value={person} onChange={(e) => setPerson(e.target.value)} className={`mt-1 ${input}`}>
<option value="">Default: none</option>
{people.map((p) => (
<option key={p.id} value={p.id}>
{p.label}
</option>
))}
</select>
</div>
<button
type="button"
className={button}
disabled={busy || person === (account.person_id ?? "")}
onClick={() => run(() => patch(`/admin/profiles/${account.id}`, { person_id: person || null }))}
>
Save profile
</button>
</div>
<div className="flex flex-wrap items-end gap-3">
<div className="min-w-48 flex-1">
<label htmlFor={discordId} className="block text-sm font-medium text-body">
Discord user ID
</label>
<input id={discordId} inputMode="numeric" value={discord} onChange={(e) => setDiscord(e.target.value)} className={`mt-1 ${input}`} />
</div>
<div className="min-w-40 flex-1">
<label htmlFor={discordName} className="block text-sm font-medium text-body">
Discord name
</label>
<input id={discordName} value={discordLabel} onChange={(e) => setDiscordLabel(e.target.value)} className={`mt-1 ${input}`} />
</div>
<button
type="button"
className={button}
disabled={busy}
onClick={() =>
run(() => patch(`/admin/profiles/${account.id}`, { discord_id: discord || null, discord_name: discordLabel }))
}
>
Save Discord
</button>
</div>
<p className="-mt-3 text-xs" style={{ color: MUTED }}>
They link it themselves from their profile; this overrides it. The ID is the long number from Discord (Developer Mode, then Copy User ID), eg. 80351110224678912. Blank unlinks it.
</p>
<div className="flex flex-wrap gap-2">
<button
type="button"
className={button}
disabled={busy}
onClick={() =>
run(async () => {
const result = await post(`/admin/profiles/${account.id}/invite`, {});
setLink(result.link);
})
}
>
{account.signed_up ? "New sign-in link" : "New invite link"}
</button>
{mail && (
<EmailInvite id={account.id} label={account.signed_up ? "Email a sign-in link" : "Email invite"} onDone={setLink} />
)}
<button
type="button"
className={button}
disabled={busy}
onClick={() => run(() => patch(`/admin/profiles/${account.id}`, { is_active: !account.is_active }))}
>
{account.is_active ? "Turn off" : "Turn on"}
</button>
<button
type="button"
className={danger}
disabled={busy}
onClick={() => {
if (window.confirm(`Remove ${account.email}'s account? Their People record stays.`)) {
run(() => del(`/admin/profiles/${account.id}`));
}
}}
>
Remove
</button>
</div>
{link && (
<LinkBox
link={link}
note={
account.signed_up
? "Opening it sets a new password. Any link before it stops working."
: "Their invite link, for 14 days. Any link before it stops working."
}
/>
)}
{error && <p className="text-sm text-danger">{error}</p>}
</div>
</details>
</li>
);
}