feat: let a signed-in administrator add and remove other administrators

This commit is contained in:
blake committed 2026-10-26 14:00:29 -05:00
1 parent 58da832bac
commit e7c99a788e
6 files changed
+618 -7

No files matched your search

+91
View File
@@ -60,15 +60,18 @@ import {
templateEndPrompt,
templateRemovalPrompt,
type ConfirmPrompt,
adminRemovalPrompt,
contactRemovalPrompt,
ContactPage,
ContactsPage,
AdminsPage,
SettingsPage,
ShiftEditor,
ShiftRoster,
TemplateEditor,
type WalkInState,
} from './admin-pages.js';
import { addAdmin, deactivateAdmin, listAdmins, readAdminRemoval, type AdminErrors, type AdminForm } from './admins.js';
import { writeAudit } from './auth/audit.js';
import { consumeLoginLink, issueLoginProof, loginLinkOpen, loginProofMatches, requestMagicLink } from './auth/login.js';
import { csrfMatches, readSession, revokeSession, sessionClearCookie, sessionSetCookie, type CoordinatorSession } from './auth/session.js';
@@ -141,6 +144,10 @@ export function registerAdmin(app: Hono, services: AdminServices): void {
app.get(appPath(config, '/admin'), (c) => showHome(c, services));
app.get(appPath(config, '/admin/settings'), (c) => showSettings(c, services));
app.post(appPath(config, '/admin/settings'), (c) => submitSettings(c, services));
app.get(appPath(config, '/admin/admins'), (c) => showAdmins(c, services));
app.post(appPath(config, '/admin/admins'), (c) => submitNewAdmin(c, services));
app.get(appPath(config, '/admin/admins/:id/remove'), (c) => showRemoveAdmin(c, services));
app.post(appPath(config, '/admin/admins/:id/remove'), (c) => submitRemoveAdmin(c, services));
app.post(appPath(config, '/admin/export'), (c) => submitExportRange(c, services));
app.get(appPath(config, '/admin/contacts'), (c) => showContacts(c, services));
app.post(appPath(config, '/admin/contacts/new'), (c) => submitNewContact(c, services));
@@ -631,6 +638,87 @@ async function submitSettings(c: Context, services: AdminServices): Promise<Resp
return c.redirect(appPath(services.config, '/admin/settings?notice=settings-saved'), 303);
}
function showAdmins(
c: Context,
services: AdminServices,
state?: { values?: AdminForm; errors?: AdminErrors; status?: 200 | 400 | 403; confirm?: ConfirmPrompt },
) {
const session = requireSession(c, services);
if (session instanceof Response) return session;
return html(
c,
services,
'Administrators · Hope Volunteer',
<AdminsPage
config={services.config}
csrf={session.csrf}
currentId={session.coordinatorId}
admins={listAdmins(services.db)}
notice={state?.status === 400 ? undefined : knownNotice(c.req.query('notice'))}
form={state?.values ? { values: state.values, errors: state.errors ?? {} } : undefined}
confirm={state?.confirm}
/>,
{ account: session, status: state?.status ?? 200 },
);
}
async function submitNewAdmin(c: Context, services: AdminServices): Promise<Response> {
const session = await postedSession(c, services);
if (session instanceof Response) return session;
const values = { name: textField(session.body, 'name'), email: textField(session.body, 'email') };
try {
const saved = addAdmin(services.db, session.coordinatorId, values, services.now());
if (!saved.ok) return showAdmins(c, services, { values, errors: saved.errors, status: 400 });
const notice = saved.status === 'restored' ? 'admin-restored' : 'admin-added';
return c.redirect(appPath(services.config, `/admin/admins?notice=${notice}`), 303);
} catch (err) {
return saveFailed(c, services, session, err);
}
}
function showRemoveAdmin(c: Context, services: AdminServices, error?: string, status: 200 | 400 | 403 = 200) {
const session = requireSession(c, services);
if (session instanceof Response) return session;
const removal = readAdminRemoval(services.db, idFrom(c));
if (!removal) return missing(c, services);
const prompt = adminRemovalPrompt({
name: removal.admin.name,
email: removal.admin.email,
self: removal.admin.id === session.coordinatorId,
last: removal.last,
});
return showAdmins(c, services, {
status,
confirm: {
...prompt,
body: error && error !== prompt.body ? error : prompt.body,
submit: error ? undefined : prompt.submit,
error: error && error !== prompt.body ? error : undefined,
action: appPath(services.config, `/admin/admins/${removal.admin.id}/remove`),
},
});
}
async function submitRemoveAdmin(c: Context, services: AdminServices): Promise<Response> {
const session = await postedSession(c, services);
if (session instanceof Response) return session;
const id = idFrom(c);
try {
const removed = deactivateAdmin(services.db, session.coordinatorId, id, services.now());
if (!removed.ok) {
if (removed.reason === 'missing') return missing(c, services);
return showRemoveAdmin(c, services, 'Add another administrator before removing this one.', 400);
}
if (id === session.coordinatorId) {
c.header('Set-Cookie', sessionClearCookie(services.config));
return c.redirect(appPath(services.config, '/login'), 303);
}
return c.redirect(appPath(services.config, '/admin/admins?notice=admin-removed'), 303);
} catch (err) {
return saveFailed(c, services, session, err);
}
}
function settingsFormFromBody(body: Record<string, unknown>): SettingsForm {
return {
reminderFar: textField(body, 'reminder_far'),
@@ -1520,6 +1608,9 @@ function knownNotice(value: string | undefined): string | undefined {
value === 'template-removed' ||
value === 'event-removed' ||
value === 'settings-saved' ||
value === 'admin-added' ||
value === 'admin-restored' ||
value === 'admin-removed' ||
value === 'contact-removed' ||
value === 'contact-saved' ||
value === 'contact-updated' ||
+100 -1
View File
@@ -16,6 +16,7 @@ import {
import type { SignupErrors, SignupValues } from './signup-form.js';
import { addLocalDays, formatInstantInZone, todayInZone } from './time.js';
import { ShiftTargetOptions } from './shift-options.js';
import type { AdminAccount, AdminErrors, AdminForm } from './admins.js';
import { assetHref } from './static-assets.js';
import { appPath } from './url.js';
@@ -140,6 +141,27 @@ export function contactRemovalPrompt(contact: { name: string; email: string }):
};
}
export function adminRemovalPrompt(admin: { name: string; email: string; self: boolean; last: boolean }): Omit<ConfirmPrompt, 'action'> {
const title = admin.self ? 'Remove your access' : `Remove ${admin.name}`;
if (admin.last) {
return { title, detail: admin.email, body: 'Add another administrator before removing this one.' };
}
if (admin.self) {
return {
title,
detail: admin.email,
body: 'This signs you out. Your sign-in links stop working. Someone else who still has access can add you again. It does not send email.',
submit: 'Remove your access',
};
}
return {
title,
detail: admin.email,
body: 'This removes their access. Their sign-in links stop working. It does not send email.',
submit: 'Remove this administrator',
};
}
export function templateRemovalPrompt(
template: { role: string; weekday: number; active: boolean },
error?: string,
@@ -226,6 +248,7 @@ export function AdminHome(props: {
<nav class="desk-links" aria-label="Coordinator">
<a href={appPath(props.config, '/admin/contacts')}>Contacts</a>
<a href={appPath(props.config, '/admin/settings')}>Settings</a>
<a href={appPath(props.config, '/admin/admins')}>Administrators</a>
</nav>
</div>
</header>
@@ -356,6 +379,78 @@ export function SettingsPage(props: {
);
}
export function AdminsPage(props: {
config: AppConfig;
csrf: string;
currentId: number;
admins: AdminAccount[];
notice?: string;
form?: { values: AdminForm; errors: AdminErrors };
confirm?: ConfirmPrompt;
}) {
const form = props.form ?? { values: { name: '', email: '' }, errors: {} };
const only = props.admins.length === 1;
return (
<>
<Crumb items={[{ href: appPath(props.config, '/admin'), label: 'Coordinator' }, { label: 'Administrators' }]} />
<h1>Administrators</h1>
<Notice notice={props.notice} />
<p>
These people can sign in and manage the pantry. Adding someone does not send email. They request a sign-in link on the coordinator sign-in page. Removing someone signs them out and stops unused sign-in links. The last administrator stays until another one is added. Saving an address you removed earlier gives that person access again.
</p>
<form method="post" action={appPath(props.config, '/admin/admins')} class="signup-form">
<input type="hidden" name="csrf" value={props.csrf} />
<h2>Add an administrator</h2>
<WalkInField id="admin-name" label="Name" name="name" type="text" value={form.values.name} error={form.errors.name} required />
<WalkInField
id="admin-email"
label="Email"
name="email"
type="email"
value={form.values.email}
error={form.errors.email}
hint="This is the address they use to request a sign-in link."
required
/>
<button type="submit">Add this administrator</button>
</form>
<section class="desk-events" aria-labelledby="admins-heading">
<h2 id="admins-heading">{props.admins.length === 1 ? '1 administrator' : `${props.admins.length} administrators`}</h2>
{only ? <p class="panel-note">This is the only administrator. Add another one before removing anyone.</p> : null}
{props.admins.length === 0 ? <p class="empty">No administrators yet.</p> : null}
{props.admins.length > 0 ? (
<ul class="admin-list">
{props.admins.map((person) => {
const self = person.id === props.currentId;
return (
<li class="admin-row" key={person.id}>
<p>
<strong>{person.name}</strong>
{self ? <span class="admin-you">You</span> : null}
</p>
<p>{person.email}</p>
{only ? null : (
<p>
<ConfirmAnchor
href={appPath(props.config, `/admin/admins/${person.id}/remove`)}
label={self ? 'Remove your access' : `Remove ${person.name}`}
prompt={adminRemovalPrompt({ name: person.name, email: person.email, self, last: false })}
>
Remove
</ConfirmAnchor>
</p>
)}
</li>
);
})}
</ul>
) : null}
</section>
<ConfirmDialog config={props.config} csrf={props.csrf} prompt={props.confirm} />
</>
);
}
function contactListHref(config: AppConfig, query: string, shown: number): string {
const params = new URLSearchParams();
if (query) params.set('q', query);
@@ -1009,11 +1104,12 @@ function monthBounds(today: string, offset: number): { from: string; to: string
return { from: start.toString(), to: end.toString() };
}
function ConfirmAnchor(props: { href: string; class?: string; prompt: Omit<ConfirmPrompt, 'action'>; children: string }) {
function ConfirmAnchor(props: { href: string; class?: string; label?: string; prompt: Omit<ConfirmPrompt, 'action'>; children: string }) {
return (
<a
class={props.class}
href={props.href}
aria-label={props.label}
data-confirm=""
data-confirm-action={props.href}
data-confirm-title={props.prompt.title}
@@ -1805,6 +1901,9 @@ const NOTICES: Record<string, string> = {
'template-removed': 'That weekly template is removed. Shifts already on the schedule stay, and they are no longer tied to the weekly pattern.',
'event-removed': 'That event is removed.',
'settings-saved': 'Settings saved.',
'admin-added': 'That person can sign in. Ask them to request a sign-in link. This did not send email.',
'admin-restored': 'That person can sign in again.',
'admin-removed': 'That person can no longer sign in.',
'contact-removed': 'That person is removed from the contact list.',
'contact-saved': 'That contact is saved.',
'contact-updated': 'That contact is updated.',
+133
View File
@@ -0,0 +1,133 @@
import type Database from 'better-sqlite3';
import { writeAudit } from './auth/audit.js';
import { EmailAddressError, normalizeEmail } from './email.js';
import { isUniqueConstraint } from './sqlite-error.js';
const MAX_NAME = 80;
const MAX_EMAIL = 254;
const CONTROL = /[\u0000-\u001F\u007F]/;
export type AdminAccount = {
id: number;
name: string;
email: string;
};
export type AdminForm = {
name: string;
email: string;
};
export type AdminErrors = Partial<Record<'name' | 'email', string>>;
type AdminRow = { id: number; name: string; email: string; active: number };
export function listAdmins(db: Database.Database): AdminAccount[] {
return db
.prepare(
`SELECT id AS id, name AS name, email AS email
FROM coordinators
WHERE active = 1 AND role = 'admin'
ORDER BY name COLLATE NOCASE, email, id`,
)
.all() as AdminAccount[];
}
export function addAdmin(
db: Database.Database,
actorId: number,
values: AdminForm,
now: string,
): { ok: true; id: number; status: 'added' | 'restored' } | { ok: false; errors: AdminErrors } {
const parsed = parseAdminForm(values);
if (!parsed.ok) return parsed;
try {
return db.transaction(() => {
const existing = db
.prepare('SELECT id AS id, active AS active FROM coordinators WHERE email = ?')
.get(parsed.email) as { id: number; active: number } | undefined;
if (existing?.active === 1) return { ok: false as const, errors: { email: 'That address already has access.' } };
if (existing) {
db.prepare(`UPDATE coordinators SET name = ?, role = 'admin', active = 1 WHERE id = ?`).run(parsed.name, existing.id);
writeAudit(db, actorId, 'admins.restore', { coordinatorId: existing.id }, now);
return { ok: true as const, id: existing.id, status: 'restored' as const };
}
const inserted = db
.prepare(
`INSERT INTO coordinators (email, name, role, password_hash, active, created_at)
VALUES (?, ?, 'admin', NULL, 1, ?)`,
)
.run(parsed.email, parsed.name, now);
const id = Number(inserted.lastInsertRowid);
writeAudit(db, actorId, 'admins.add', { coordinatorId: id }, now);
return { ok: true as const, id, status: 'added' as const };
}).immediate();
} catch (err) {
if (isUniqueConstraint(err)) return { ok: false, errors: { email: 'That address already has access.' } };
throw err;
}
}
export function readAdminRemoval(db: Database.Database, id: number): { admin: AdminAccount; last: boolean } | null {
const admin = activeAdmin(db, id);
if (!admin) return null;
return { admin: { id: admin.id, name: admin.name, email: admin.email }, last: activeAdminCount(db) <= 1 };
}
export function deactivateAdmin(
db: Database.Database,
actorId: number,
id: number,
now: string,
): { ok: true } | { ok: false; reason: 'missing' | 'last' } {
return db.transaction(() => {
const admin = activeAdmin(db, id);
if (!admin) return { ok: false as const, reason: 'missing' as const };
if (activeAdminCount(db) <= 1) return { ok: false as const, reason: 'last' as const };
db.prepare('UPDATE coordinators SET active = 0 WHERE id = ?').run(id);
db.prepare('DELETE FROM sessions WHERE coordinator_id = ?').run(id);
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(now, id);
db.prepare(
`UPDATE outbox
SET status = 'cancelled', last_error = ?
WHERE kind = 'magic_link' AND status = 'pending' AND to_email = ?`,
).run('An administrator removed this sign-in link.', admin.email);
writeAudit(db, actorId, 'admins.remove', { coordinatorId: id }, now);
return { ok: true as const };
}).immediate();
}
function activeAdmin(db: Database.Database, id: number): AdminRow | null {
const row = db
.prepare(
`SELECT id AS id, name AS name, email AS email, active AS active
FROM coordinators
WHERE id = ? AND active = 1 AND role = 'admin'`,
)
.get(id) as AdminRow | undefined;
return row ?? null;
}
function activeAdminCount(db: Database.Database): number {
const row = db.prepare(`SELECT COUNT(*) AS n FROM coordinators WHERE active = 1 AND role = 'admin'`).get() as { n: number };
return row.n;
}
function parseAdminForm(values: AdminForm): { ok: true; name: string; email: string } | { ok: false; errors: AdminErrors } {
const errors: AdminErrors = {};
const nameRaw = values.name.normalize('NFC').trim();
if (!nameRaw) errors.name = 'Enter a name.';
else if (CONTROL.test(values.name)) errors.name = 'Enter a name without line breaks.';
else if (nameRaw.length > MAX_NAME) errors.name = `Use ${MAX_NAME} characters or fewer.`;
let email = '';
try {
email = normalizeEmail(values.email);
if (email.length > MAX_EMAIL || CONTROL.test(values.email)) errors.email = 'Enter an email address.';
} catch (err) {
if (!(err instanceof EmailAddressError)) throw err;
errors.email = 'Enter an email address.';
}
if (errors.name || errors.email) return { ok: false, errors };
return { ok: true, name: nameRaw, email };
}