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>
This commit is contained in:
Aidan Dona 2026-10-16 18:14:30 -05:00
parent 0cc2a3f721
commit e4c7e165d1
34 changed files with 2483 additions and 74 deletions

View file

@ -0,0 +1,198 @@
/* ═══════════════════════════════════════════════════════════════
PROFILE ACCOUNT ROUTES (076): Data → Profile accounts, mounted
under /api/admin, admins and up
GET /profiles every profile account, and the
claims waiting
POST /profiles { email, name }: a new account,
invited (its link comes back)
POST /profiles/:id/invite a new link, replacing the old;
{ email: true } also emails it
PATCH /profiles/:id { person_id, discord_id,
discord_name, is_active }: an
admin's own say
DELETE /profiles/:id remove the account
POST /profiles/claims/:id/approve the request's person is theirs
POST /profiles/claims/:id/decline
Only member accounts are listed or changed here. The admin roles
are the Panel's (superadmins), so an admin can't make or touch
another admin from this page.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { destroyAllSessionsFor, logSafe, requireRole } from "../auth.js";
import { tx } from "../db.js";
import { emailInvite, issueInvite } from "../invites.js";
import { mailReady } from "../googleService.js";
import { NO_STORE } from "../shape.js";
const profiles = new Hono();
profiles.use("/profiles", requireRole("admin"));
profiles.use("/profiles/*", requireRole("admin"));
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
async function body(c) {
try {
return (await c.req.json()) ?? {};
} catch {
return null;
}
}
const member = (db, id) =>
db.prepare(`SELECT * FROM admin_users WHERE id = ? AND role = 'member'`).get(Number(id)) ?? null;
profiles.get("/profiles", (c) => {
const db = c.get("db");
const accounts = db
.prepare(
`SELECT u.id, u.email, u.name, u.is_active, u.created_at, u.last_login_at,
u.invited_at, u.invite_expires_at,
(u.invite_hash IS NOT NULL AND u.invite_expires_at > datetime('now')) AS invite_open,
(u.password_hash IS NOT NULL OR u.google_sub IS NOT NULL) AS signed_up,
u.person_id, p.display_name AS person_name,
u.discord_id, u.discord_name
FROM admin_users u
LEFT JOIN people p ON p.id = u.person_id
WHERE u.role = 'member'
ORDER BY u.created_at DESC, u.id DESC`,
)
.all();
const claims = db
.prepare(
`SELECT c.id, c.account_id, u.email, u.name, c.person_id, p.display_name AS person_name,
c.message, c.created_at
FROM person_claims c
JOIN admin_users u ON u.id = c.account_id
JOIN people p ON p.id = c.person_id
WHERE c.status = 'pending'
ORDER BY c.created_at`,
)
.all();
return c.json({ accounts, claims, mail: mailReady() }, 200, NO_STORE);
});
profiles.post("/profiles", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const email = String(data.email ?? "").trim().toLowerCase().slice(0, 254);
const name = String(data.name ?? "").trim().slice(0, 120) || null;
if (!EMAIL.test(email)) return c.json({ error: "Enter an email address.", fields: { email: "Needed." } }, 422);
if (db.prepare(`SELECT 1 FROM admin_users WHERE email = ?`).get(email)) {
return c.json({ error: "That email already has an account.", fields: { email: "Already has one." } }, 409);
}
const id = db
.prepare(
`INSERT INTO admin_users (email, name, role, access_source) VALUES (?, ?, 'member', 'invite')`,
)
.run(email, name).lastInsertRowid;
const link = issueInvite(db, id, c.get("user").id);
console.log(`profile account ${logSafe(email)} invited by ${c.get("user").email}`);
return c.json({ id: Number(id), link }, 201, NO_STORE);
});
profiles.post("/profiles/:id/invite", async (c) => {
const db = c.get("db");
const account = member(db, c.req.param("id"));
if (!account) return c.json({ error: "No such profile account." }, 404);
const data = (await body(c)) ?? {};
const link = issueInvite(db, account.id, c.get("user").id);
if (data.email) {
try {
await emailInvite(db, account, link);
} catch (err) {
console.warn(`invite email to ${account.email} failed: ${err.message}`);
return c.json({ link, emailed: false, error: `The email didn't go: ${err.message}` }, 502, NO_STORE);
}
}
console.log(`invite for ${account.email} ${data.email ? "emailed" : "issued"} by ${c.get("user").email}`);
return c.json({ link, emailed: Boolean(data.email) }, 200, NO_STORE);
});
profiles.patch("/profiles/:id", async (c) => {
const db = c.get("db");
const account = member(db, c.req.param("id"));
if (!account) return c.json({ error: "No such profile account." }, 404);
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const sets = [];
const values = [];
if ("person_id" in data) {
const personId = data.person_id ? String(data.person_id) : null;
if (personId) {
if (!db.prepare(`SELECT 1 FROM people WHERE id = ?`).get(personId)) {
return c.json({ error: "No such person.", fields: { person_id: "Pick one." } }, 422);
}
const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ? AND id <> ?`).get(personId, account.id);
if (holder) return c.json({ error: `${holder.email} already has that profile.` }, 409);
}
sets.push("person_id = ?");
values.push(personId);
}
if ("discord_id" in data) {
const discordId = data.discord_id ? String(data.discord_id).trim() : null;
if (discordId && !/^\d{5,25}$/.test(discordId)) {
return c.json({ error: "A Discord id is the long number (Developer Mode → Copy User ID).", fields: { discord_id: "Digits only." } }, 422);
}
if (discordId && db.prepare(`SELECT 1 FROM admin_users WHERE discord_id = ? AND id <> ?`).get(discordId, account.id)) {
return c.json({ error: "Another account has that Discord id." }, 409);
}
sets.push("discord_id = ?", "discord_name = ?");
values.push(discordId, discordId ? String(data.discord_name ?? "").trim().slice(0, 100) || null : null);
}
if ("is_active" in data) {
sets.push("is_active = ?");
values.push(data.is_active ? 1 : 0);
}
if (!sets.length) return c.json({ error: "Nothing to change." }, 422);
db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run(...values, account.id);
if ("is_active" in data && !data.is_active) destroyAllSessionsFor(db, account.id);
console.log(`profile account ${account.email} changed by ${c.get("user").email}`);
return c.body(null, 204);
});
profiles.delete("/profiles/:id", (c) => {
const db = c.get("db");
const account = member(db, c.req.param("id"));
if (!account) return c.json({ error: "No such profile account." }, 404);
db.prepare(`DELETE FROM admin_users WHERE id = ?`).run(account.id);
console.log(`profile account ${account.email} removed by ${c.get("user").email}`);
return c.body(null, 204);
});
function decide(c, approve) {
const db = c.get("db");
const claim = db
.prepare(`SELECT * FROM person_claims WHERE id = ? AND status = 'pending'`)
.get(Number(c.req.param("id")));
if (!claim) return c.json({ error: "That request was already answered." }, 404);
const taken = tx(db, () => {
if (approve) {
const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ?`).get(claim.person_id);
if (holder) return holder.email;
db.prepare(`UPDATE admin_users SET person_id = ? WHERE id = ?`).run(claim.person_id, claim.account_id);
}
db.prepare(
`UPDATE person_claims SET status = ?, decided_at = datetime('now'), decided_by = ? WHERE id = ?`,
).run(approve ? "approved" : "declined", c.get("user").id, claim.id);
return null;
});
if (taken) return c.json({ error: `${taken} already has that profile. Decline this one.` }, 409);
console.log(`claim ${claim.id} (${claim.person_id}) ${approve ? "approved" : "declined"} by ${c.get("user").email}`);
return c.body(null, 204);
}
profiles.post("/profiles/claims/:id/approve", (c) => decide(c, true));
profiles.post("/profiles/claims/:id/decline", (c) => decide(c, false));
export default profiles;