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

@ -42,6 +42,9 @@ export const people = {
text("location_label"),
bool("is_published"),
bool("is_listed"),
// What's taken off the site (076): its owner's choice on their
// profile, or an admin's. v_people_public applies it.
...["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"].map((key) => bool(`hide_${key}`)),
],
extensions: [

View file

@ -219,14 +219,27 @@ export async function requireAuth(c, next) {
await next();
}
export const ROLES = ["viewer", "editor", "admin", "superadmin"];
const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 };
/* member is a profile account (076): signed in to the site and their
own profile, below every admin role, so it passes no admin check.
/api/admin as a whole needs viewer (index.js, requireStaff). */
export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"];
const RANK = { member: 1, viewer: 2, editor: 3, admin: 4, superadmin: 5 };
/* Whether a user is at least this rank. A ladder, never equality. */
export function hasRole(user, role) {
return (RANK[user?.role] ?? 0) >= (RANK[role] ?? Infinity);
}
/* Anyone who uses the admin: a signed-in account of viewer and up.
A profile account (member) is signed in but gets 403 here. */
export async function requireStaff(c, next) {
const user = currentUser(c.get("db"), c);
if (!user) return c.json({ error: "Not signed in." }, 401);
if (!hasRole(user, "viewer")) return c.json({ error: "Not allowed." }, 403);
c.set("user", user);
await next();
}
export function requireRole(...roles) {
const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity));
return async (c, next) => {

84
server/src/discordAuth.js Normal file
View file

@ -0,0 +1,84 @@
/* ═══════════════════════════════════════════════════════════════
DISCORD LINKING
A profile account links its Discord account (076): OAuth 2.0 with
the identify scope only, which gives the Discord user's id and
name and nothing else (no servers, no messages). The routes are in
routes/account.js; an admin can also set or clear it by hand
(routes/profiles.js). Kept for the gamification to come, which
matches Discord members to people by this id.
DISCORD_CLIENT_ID from the Discord developer portal
DISCORD_CLIENT_SECRET the same; never in the repo
DISCORD_REDIRECT_URI default <site.json url>/api/account/discord/callback
With no client id or secret it's off: the profile page doesn't
offer it and the routes answer 404. Setup: docs/profile-accounts.md.
═══════════════════════════════════════════════════════════════ */
import { randomBytes } from "node:crypto";
import { loadSite } from "./pageMeta.js";
const AUTHORIZE = "https://discord.com/oauth2/authorize";
const TOKEN = "https://discord.com/api/oauth2/token";
const ME = "https://discord.com/api/users/@me";
export function discordConfig() {
const clientId = process.env.DISCORD_CLIENT_ID;
const clientSecret = process.env.DISCORD_CLIENT_SECRET;
if (!clientId || !clientSecret) return null;
let redirectUri = process.env.DISCORD_REDIRECT_URI ?? null;
if (!redirectUri) {
try {
const origin = (loadSite().url ?? "").replace(/\/$/, "");
if (origin) redirectUri = `${origin}/api/account/discord/callback`;
} catch {
redirectUri = null;
}
}
return { clientId, clientSecret, redirectUri };
}
/* Where to send the browser, and the state to keep until it's back. */
export function startLink(config) {
const state = randomBytes(24).toString("base64url");
const url = new URL(AUTHORIZE);
url.search = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
scope: "identify",
state,
prompt: "consent",
});
return { url: url.toString(), state };
}
/* Trade the code for a token, then ask who it is. Returns
{ id, name } or throws. */
export async function finishLink(config, code) {
const res = await fetch(TOKEN, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: "authorization_code",
code,
redirect_uri: config.redirectUri,
}),
signal: AbortSignal.timeout(10_000),
});
const token = await res.json().catch(() => ({}));
if (!res.ok || !token.access_token) throw new Error(`Discord didn't accept the link (${res.status}).`);
const me = await fetch(ME, {
headers: { Authorization: `Bearer ${token.access_token}` },
signal: AbortSignal.timeout(10_000),
});
const user = await me.json().catch(() => ({}));
if (!me.ok || !user.id) throw new Error(`Discord didn't say who you are (${me.status}).`);
return { id: String(user.id), name: String(user.global_name || user.username || "").slice(0, 100) || null };
}

View file

@ -30,6 +30,12 @@
Nothing here creates an account. A Google login is only let in
if admin-cli has already made one for that email (see auth.js
routes), and is linked to it on first use.
Profile accounts (076) are the one case outside the domain: an
invited member may sign in with any Google account under the
invited email. finishLogin says whether the identity is in the
Workspace domain (inDomain) instead of refusing it, and the
callback lets an outside identity reach a member account only.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
@ -70,8 +76,10 @@ export function googleConfig() {
}
/* The first leg: where to send the browser, and the state and PKCE
verifier to keep (in a short-lived cookie) until it comes back. */
export function startLogin(config) {
verifier to keep (in a short-lived cookie) until it comes back.
anyDomain: a profile account's sign-in, so the account chooser
isn't narrowed to the Workspace. */
export function startLogin(config, { anyDomain = false } = {}) {
const state = base64url(randomBytes(24));
const verifier = base64url(randomBytes(48));
const challenge = base64url(createHash("sha256").update(verifier).digest());
@ -87,7 +95,7 @@ export function startLogin(config) {
code_challenge_method: "S256",
// Only a hint to Google's account chooser; the hd claim is what's
// actually checked on the way back.
hd: config.domain,
...(anyDomain ? {} : { hd: config.domain }),
prompt: "select_account",
});
@ -102,7 +110,7 @@ export class GoogleLoginError extends Error {
}
/* The second leg: trade the code for tokens and check the identity.
Returns { sub, email, name } or throws GoogleLoginError. */
Returns { sub, email, name, inDomain } or throws GoogleLoginError. */
export async function finishLogin(config, code, verifier) {
let res;
try {
@ -145,9 +153,7 @@ export async function finishLogin(config, code, verifier) {
if (!claims.email_verified || !email) {
throw new GoogleLoginError("unverified", "That Google account's email isn't verified.");
}
if (String(claims.hd ?? "").toLowerCase() !== config.domain || !email.endsWith(`@${config.domain}`)) {
throw new GoogleLoginError("wrong_domain", `Use your @${config.domain} account.`);
}
const inDomain = String(claims.hd ?? "").toLowerCase() === config.domain && email.endsWith(`@${config.domain}`);
return { sub: String(claims.sub), email, name: claims.name ?? null };
return { sub: String(claims.sub), email, name: claims.name ?? null, inDomain };
}

View file

@ -32,6 +32,8 @@ import pages from "./routes/pages.js";
import feedback from "./routes/feedback.js";
import requests from "./routes/requests.js";
import auth from "./routes/auth.js";
import account from "./routes/account.js";
import profiles from "./routes/profiles.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
@ -43,7 +45,7 @@ import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { logSafe, requireStaff, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
@ -134,7 +136,7 @@ app.use(
so each is capped well above its longest real body (a 5000
character message) and far below nginx's limit. */
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login"]) app.use(path, smallBody);
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile"]) app.use(path, smallBody);
/* What the policy above would have blocked. Browsers post these on
their own; a short line per report is plenty to go on. */
@ -206,9 +208,18 @@ app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
// Looser than a password guess: each Google sign-in is two requests,
// and Google has already checked the person by the second.
app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 }));
// The whole admin is for viewer and up; a profile account (member)
// is signed in but kept out. Each router still checks its own.
app.use("/api/admin/*", requireStaff);
app.route("/api/admin/panel", panel);
app.route("/api/auth", auth);
// A profile account's own page (076); setting a password from an
// invite is held to the login's pace.
app.use("/api/account/accept", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
app.use("/api/account/photo", rateLimit({ windowMs: 15 * 60_000, max: 20 }));
app.route("/api/account", account);
app.route("/api/admin", admin);
app.route("/api/admin", profiles);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", imports);

89
server/src/invites.js Normal file
View file

@ -0,0 +1,89 @@
/* ═══════════════════════════════════════════════════════════════
INVITES: how a profile account (076) comes to exist
Nobody signs up. An admin adds an email (Data → Profile
accounts, routes/profiles.js), which makes a member account with
no password, and issues an invite: a link to /account/welcome
with a random token. The token itself is shown once, to the
admin, and emailed if they press Email invite; the database
keeps only its SHA-256, like a session's. Issuing a new one
replaces the old, so a link sent to the wrong place can be
killed by sending another.
The link lets its holder set a password (routes/account.js).
Signing in with Google under the invited email takes it up too
(routes/auth.js). Either way the token is cleared.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
import { loadSite } from "./pageMeta.js";
import { mailReady, sendMail } from "./googleService.js";
export const INVITE_DAYS = 14;
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
/* A new invite for this account, replacing any before it. Returns
the link, which is never stored. */
export function issueInvite(db, accountId, invitedBy) {
const token = randomBytes(32).toString("base64url");
db.prepare(
`UPDATE admin_users
SET invite_hash = ?, invite_expires_at = datetime('now', ?),
invited_at = datetime('now'), invited_by = ?
WHERE id = ?`,
).run(sha256(token), `+${INVITE_DAYS} days`, invitedBy, accountId);
return inviteLink(token);
}
export function inviteLink(token) {
let origin = "";
try {
origin = (loadSite().url ?? "").replace(/\/$/, "");
} catch {
origin = "";
}
return `${origin}/account/welcome?token=${encodeURIComponent(token)}`;
}
/* The account an unexpired invite token belongs to, or null. */
export function accountForInvite(db, token) {
if (typeof token !== "string" || token.length < 20 || token.length > 100) return null;
return (
db
.prepare(
`SELECT id, email, name, role, is_active
FROM admin_users
WHERE invite_hash = ? AND invite_expires_at > datetime('now') AND is_active = 1`,
)
.get(sha256(token)) ?? null
);
}
/* The invite as an email, through Gmail (googleService.js). */
export async function emailInvite(db, account, link) {
if (!mailReady()) throw new Error("Gmail isn't set up on the server (docs/google-drive-and-mail.md).");
let site = { title: "Next Generation of Unity" };
try {
site = loadSite();
} catch {
// The default name will do.
}
const hello = account.name ? `Hi ${account.name},` : "Hi,";
await sendMail({
to: account.email,
subject: `Your ${site.title} profile`,
text: [
hello,
"",
`You're invited to make a profile account on the ${site.title} website. Open this link to set a password, or to sign in with Google under this email:`,
"",
link,
"",
`The link works once, for ${INVITE_DAYS} days. Once you're in, you can find your profile on the site, ask to claim it, and choose what of it shows.`,
"",
"If you weren't expecting this, you can ignore it.",
].join("\n"),
});
}

View file

@ -0,0 +1,264 @@
-- ═══════════════════════════════════════════════════════════════
-- 076 PROFILE ACCOUNTS
--
-- Accounts for people, not only for the admin. An admin invites an
-- email (Data → Profile accounts); nobody signs up on their own. The
-- invite's link lets them set a password, or they sign in with
-- Google under that email, any Google account, not only
-- @nextgenerationofunity.org. Then they claim their People record,
-- an admin approves it, and they edit their profile and choose what
-- of it shows.
--
-- admin_users is rebuilt (its CHECKs can't change in place):
-- role takes 'member', below viewer: signs in to the
-- site and their own profile, never to the admin
-- access_source takes 'invite', an account made by an invite
-- person_id the People record it claimed (one account each)
-- invite_hash SHA-256 of the invite link's token, until used
-- invite_expires_at, invited_at, invited_by
-- discord_id, discord_name the linked Discord account, set by
-- its owner through Discord or by an admin
--
-- person_claims: a request to be a People record, approved or
-- declined by an admin.
--
-- people.hide_*: what its owner (or an admin) took off the site.
-- The value stays, for the admin; v_people_public is the record as
-- the site shows it, the hidden fields null, and every public read
-- goes through it, the views below included.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE admin_users_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
-- Stored lowercased. The application lowercases on every read
-- and write, so the UNIQUE index is genuinely case-insensitive
-- without depending on a collation.
email TEXT NOT NULL UNIQUE,
name TEXT,
-- Null for a Google-only account, or an invite not yet taken up.
-- A row with both can use either route in.
password_hash TEXT,
-- Google's stable subject id. Nullable, unique when present,
-- SQLite allows any number of NULLs in a unique index.
google_sub TEXT UNIQUE,
-- Listed low to high. The application treats these as a ladder,
-- not a set: each one passes every check the one below it
-- passes. The default stays 'admin' so no existing tooling
-- starts creating accounts with different powers than it did
-- yesterday.
--
-- member their own profile, on the site; no admin
-- viewer read the admin
-- editor + create and update
-- admin + delete, invite members, approve claims
-- superadmin + accounts, roles and sessions
role TEXT NOT NULL DEFAULT 'admin'
CHECK (role IN ('member', 'viewer', 'editor', 'admin', 'superadmin')),
is_active INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
last_login_at TEXT,
access_source TEXT NOT NULL DEFAULT 'manual'
CHECK (access_source IN ('manual', 'group', 'invite')),
group_disabled INTEGER NOT NULL DEFAULT 0 CHECK (group_disabled IN (0, 1)),
groups_checked_at TEXT,
person_id TEXT UNIQUE REFERENCES people (id) ON DELETE SET NULL,
invite_hash TEXT UNIQUE,
invite_expires_at TEXT,
invited_at TEXT,
invited_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
discord_id TEXT UNIQUE,
discord_name TEXT
) STRICT;
INSERT INTO admin_users_new
(id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
access_source, group_disabled, groups_checked_at)
SELECT id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
access_source, group_disabled, groups_checked_at
FROM admin_users;
-- sessions, media, clip_jobs and drive_files name admin_users;
-- legacy mode leaves them alone through the rename.
PRAGMA legacy_alter_table = ON;
DROP TABLE admin_users;
ALTER TABLE admin_users_new RENAME TO admin_users;
PRAGMA legacy_alter_table = OFF;
CREATE TABLE person_claims (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id INTEGER NOT NULL REFERENCES admin_users (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
message TEXT,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'approved', 'declined')),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
decided_at TEXT,
decided_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL
) STRICT;
CREATE INDEX person_claims_status_idx ON person_claims (status, created_at);
CREATE INDEX person_claims_account_idx ON person_claims (account_id);
-- One open request per account.
CREATE UNIQUE INDEX person_claims_one_pending ON person_claims (account_id) WHERE status = 'pending';
ALTER TABLE people ADD COLUMN hide_photo INTEGER NOT NULL DEFAULT 0 CHECK (hide_photo IN (0, 1));
ALTER TABLE people ADD COLUMN hide_pronouns INTEGER NOT NULL DEFAULT 0 CHECK (hide_pronouns IN (0, 1));
ALTER TABLE people ADD COLUMN hide_tagline INTEGER NOT NULL DEFAULT 0 CHECK (hide_tagline IN (0, 1));
ALTER TABLE people ADD COLUMN hide_bio INTEGER NOT NULL DEFAULT 0 CHECK (hide_bio IN (0, 1));
ALTER TABLE people ADD COLUMN hide_email INTEGER NOT NULL DEFAULT 0 CHECK (hide_email IN (0, 1));
ALTER TABLE people ADD COLUMN hide_phone INTEGER NOT NULL DEFAULT 0 CHECK (hide_phone IN (0, 1));
ALTER TABLE people ADD COLUMN hide_location INTEGER NOT NULL DEFAULT 0 CHECK (hide_location IN (0, 1));
ALTER TABLE people ADD COLUMN hide_links INTEGER NOT NULL DEFAULT 0 CHECK (hide_links IN (0, 1));
-- A person as the site shows them. Every public read uses this, not
-- people; the admin reads people.
CREATE VIEW v_people_public AS
SELECT
id,
display_name,
sort_name,
CASE WHEN hide_pronouns = 0 THEN pronouns END AS pronouns,
CASE WHEN hide_tagline = 0 THEN tagline END AS tagline,
CASE WHEN hide_photo = 0 THEN photo END AS photo,
CASE WHEN hide_email = 0 THEN public_email END AS public_email,
CASE WHEN hide_phone = 0 THEN public_phone END AS public_phone,
CASE WHEN hide_location = 0 THEN locality END AS locality,
CASE WHEN hide_location = 0 THEN state_code END AS state_code,
country,
CASE WHEN hide_location = 0 THEN location_label END AS location_label,
is_published,
created_at,
updated_at,
CASE WHEN hide_bio = 0 THEN bio END AS bio,
primary_org_id,
is_listed,
specialty,
hide_links
FROM people;
-- The views that read people's public fields, over v_people_public.
DROP VIEW v_event_people;
CREATE VIEW v_event_people AS
SELECT
ep.event_id, ep.person_id, ep.role, ep.title, ep.sort_order,
p.display_name, p.pronouns, p.tagline, p.photo
FROM event_people ep
JOIN v_people_public p ON p.id = ep.person_id AND p.is_published = 1
WHERE ep.is_public = 1;
DROP VIEW v_timeline;
CREATE VIEW v_timeline AS
SELECT
t.id,
t.kind,
t.ref_kind,
t.ref_id,
t.precision,
t.is_featured,
t.is_published,
t.sort_order,
COALESCE(t.occurred_on, e.starts_on, pa.awarded_on) AS effective_date,
COALESCE(
t.title,
e.title,
o.name,
aw.name,
p.display_name,
tm.name
) AS effective_title,
COALESCE(t.blurb, e.tagline, o.tagline, aw.description, p.tagline, tm.tagline)
AS effective_blurb,
t.meta,
t.link_url,
-- Filename only. The directory is the frontend's business.
COALESCE(e.event_logo, e.org_logo, o.logo, aw.logo, p.photo, tm.logo)
AS effective_logo,
o.kind AS org_kind,
tm.org_id AS team_org_id,
tm.name AS team_name,
-- Whether the referenced record is itself visible. An entry must not
-- outlive the thing it points at being unpublished, a draft event
-- would otherwise leak its title and date onto a public page. Null
-- for a standalone milestone, which answers to nothing but its own
-- is_published.
CASE t.ref_kind
WHEN 'event' THEN e.is_published
WHEN 'organization' THEN o.is_published
WHEN 'person' THEN p.is_published
WHEN 'team' THEN tm.is_published
ELSE NULL
END AS ref_is_published,
t.occurred_on,
t.title AS title_override
FROM timeline_entries t
LEFT JOIN events e ON t.ref_kind = 'event' AND e.id = t.ref_id
LEFT JOIN organizations o ON t.ref_kind = 'organization' AND o.id = t.ref_id
LEFT JOIN awards aw ON t.ref_kind = 'award' AND aw.id = t.ref_id
LEFT JOIN v_people_public p ON t.ref_kind = 'person' AND p.id = t.ref_id
LEFT JOIN teams tm ON t.ref_kind = 'team' AND tm.id = t.ref_id
LEFT JOIN person_awards pa ON t.ref_kind = 'award' AND pa.award_id = t.ref_id
AND pa.id = (SELECT MIN(id) FROM person_awards
WHERE award_id = t.ref_id);
DROP VIEW v_org_leadership;
CREATE VIEW v_org_leadership AS
SELECT
a.org_id,
a.team_id,
t.name AS team_name,
t.sort_order AS team_sort_order,
a.person_id,
a.title,
a.role,
a.is_owner,
a.sort_order,
p.display_name,
p.sort_name,
p.pronouns,
p.tagline,
p.photo,
p.public_email,
p.location_label,
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM affiliations a
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
LEFT JOIN teams t ON t.id = a.team_id
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE a.is_public = 1
AND a.ended_on IS NULL
ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;
DROP VIEW v_event_hosts;
CREATE VIEW v_event_hosts AS
SELECT
eh.id,
eh.event_id,
eh.sort_order,
CASE WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
AS host_kind,
COALESCE(eh.org_id, eh.person_id) AS host_id,
COALESCE(o.name, p.display_name) AS host_name,
o.kind AS host_org_kind,
o.logo AS host_logo,
o.color AS host_color,
p.photo AS host_photo,
COALESCE(o.is_published, p.is_published) AS host_is_published,
t.id AS host_team_id,
t.name AS host_team_name
FROM event_hosts eh
LEFT JOIN organizations o ON o.id = eh.org_id
LEFT JOIN v_people_public p ON p.id = eh.person_id
LEFT JOIN teams t ON t.id = eh.team_id AND eh.org_id IS NOT NULL AND t.is_published = 1;

View file

@ -302,7 +302,7 @@ function awardMeta(site, db, id, meta) {
}
function personMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM people WHERE id = ? AND is_published = 1`).get(id);
const row = db.prepare(`SELECT * FROM v_people_public WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
return {
...meta,
@ -332,7 +332,7 @@ function blogMeta(site, db, id, meta) {
.prepare(
`SELECT p.display_name AS name
FROM blog_post_authors a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id = ? ORDER BY a.sort_order`,
)
.all(id)
@ -364,6 +364,10 @@ function blogMeta(site, db, id, meta) {
};
}
/* The profile account pages and their titles (src/pages/SignIn.tsx,
Account.tsx, AccountWelcome.tsx say the same). */
const ACCOUNT_PAGES = { "/sign-in": "Sign in", "/account": "Your profile", "/account/welcome": "Welcome" };
/* The metadata for one request path, for this visitor (the signed-in
user or null, who decides whether a hidden page is there). */
export function metaFor(db, rawPath, user = null) {
@ -402,6 +406,10 @@ export function metaFor(db, rawPath, user = null) {
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
// A profile account's pages (076): there for anyone, about no one
// in particular, so never indexed or in the sitemap.
if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true };
const page = site.pages?.[pathname];
if (page && hiddenFrom(db, user, pathname)) return notFound(meta);
if (page) {

View file

@ -0,0 +1,333 @@
/* ═══════════════════════════════════════════════════════════════
ACCOUNT ROUTES: a profile account's own page (076), mounted
under /api/account
GET /invite?token= who an invite link is for (welcome page)
POST /accept { token, password }: set the password,
sign in, take up the invite
GET / me: the account, my person (as I edit
it), my claim, Discord
GET /people the People records I could claim
POST /claim { person_id, message }: ask to be one
DELETE /claim take back the open request
PATCH /profile my person's text and what of it shows
POST /photo my person's photo (multipart, `file`)
GET /discord off to Discord to link it
GET /discord/callback back from it
DELETE /discord unlink it
Every route but the first two needs a session; any role will do,
so an admin with a claimed record has a profile too. Only the
account's own person is ever written, and only the fields in
PROFILE_FIELDS: name, published and listed stay the admin's.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import { SECURE_COOKIE, createSession, currentUser, hashPassword } from "../auth.js";
import { accountForInvite } from "../invites.js";
import { discordConfig, finishLink, startLink } from "../discordAuth.js";
import { googleConfig } from "../googleAuth.js";
import { MAX_UPLOAD_BYTES, MediaError, publicPath } from "../media.js";
import { addToLibrary } from "./media.js";
import { NO_STORE } from "../shape.js";
const account = new Hono();
const MIN_PASSWORD = 12;
/* What an owner edits on their own record, and its longest. */
const PROFILE_FIELDS = {
pronouns: 40,
tagline: 160,
bio: 4000,
public_email: 254,
public_phone: 40,
location_label: 120,
};
/* What an owner can take off the site (people.hide_*). */
export const HIDE_FIELDS = ["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"];
async function body(c) {
try {
return (await c.req.json()) ?? {};
} catch {
return null;
}
}
/* ── Invites ─────────────────────────────────────────────────── */
account.get("/invite", (c) => {
const invited = accountForInvite(c.get("db"), c.req.query("token"));
if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404, NO_STORE);
return c.json({ invite: { email: invited.email, name: invited.name, google: Boolean(googleConfig()) } }, 200, NO_STORE);
});
account.post("/accept", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const invited = accountForInvite(db, data.token);
if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404);
const password = String(data.password ?? "");
if (password.length < MIN_PASSWORD) {
return c.json({ error: `Use at least ${MIN_PASSWORD} characters.`, fields: { password: "Too short." } }, 422);
}
if (password.length > 200) return c.json({ error: "That password is too long." }, 422);
db.prepare(
`UPDATE admin_users
SET password_hash = ?, invite_hash = NULL, invite_expires_at = NULL, last_login_at = datetime('now')
WHERE id = ?`,
).run(hashPassword(password), invited.id);
createSession(db, c, invited.id);
console.log(`invite taken up by ${invited.email}`);
return c.json({ user: { id: invited.id, email: invited.email, name: invited.name, role: invited.role } }, 200, NO_STORE);
});
/* ── Signed in from here ─────────────────────────────────────── */
account.use("*", async (c, next) => {
const path = c.req.path;
if (path.endsWith("/invite") || path.endsWith("/accept")) return next();
const user = currentUser(c.get("db"), c);
if (!user) return c.json({ error: "Not signed in." }, 401, NO_STORE);
c.set("user", user);
await next();
});
/* My person as I edit it: the stored values, not the public view,
with what's hidden said separately. */
function myPerson(db, accountId) {
const row = db
.prepare(
`SELECT p.* FROM people p JOIN admin_users u ON u.person_id = p.id WHERE u.id = ?`,
)
.get(accountId);
if (!row) return null;
return {
id: row.id,
display_name: row.display_name,
is_published: row.is_published === 1,
photo: row.photo,
...Object.fromEntries(Object.keys(PROFILE_FIELDS).map((key) => [key, row[key]])),
hidden: Object.fromEntries(HIDE_FIELDS.map((key) => [key, row[`hide_${key}`] === 1])),
};
}
account.get("/", (c) => {
const db = c.get("db");
const user = c.get("user");
const row = db.prepare(`SELECT discord_id, discord_name FROM admin_users WHERE id = ?`).get(user.id);
const claim = db
.prepare(
`SELECT c.id, c.person_id, p.display_name, c.status, c.created_at, c.decided_at
FROM person_claims c JOIN people p ON p.id = c.person_id
WHERE c.account_id = ? ORDER BY c.id DESC LIMIT 1`,
)
.get(user.id);
return c.json(
{
account: {
user,
person: myPerson(db, user.id),
claim: claim ?? null,
discord: { enabled: Boolean(discordConfig()), id: row?.discord_id ?? null, name: row?.discord_name ?? null },
},
},
200,
NO_STORE,
);
});
/* Published records nobody has claimed, to pick from. */
account.get("/people", (c) => {
const people = c
.get("db")
.prepare(
`SELECT p.id, p.display_name AS name
FROM people p
WHERE p.is_published = 1
AND NOT EXISTS (SELECT 1 FROM admin_users u WHERE u.person_id = p.id)
ORDER BY COALESCE(p.sort_name, p.display_name)`,
)
.all();
return c.json({ people }, 200, NO_STORE);
});
account.post("/claim", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const user = c.get("user");
if (db.prepare(`SELECT person_id FROM admin_users WHERE id = ?`).get(user.id)?.person_id) {
return c.json({ error: "Your account already has a profile." }, 409);
}
const personId = String(data.person_id ?? "");
const person = db.prepare(`SELECT id FROM people WHERE id = ? AND is_published = 1`).get(personId);
if (!person) return c.json({ error: "Pick a person from the list.", fields: { person_id: "Pick one." } }, 422);
if (db.prepare(`SELECT 1 FROM admin_users WHERE person_id = ?`).get(personId)) {
return c.json({ error: "Someone has already claimed that profile." }, 409);
}
const message = String(data.message ?? "").trim().slice(0, 1000) || null;
try {
db.prepare(`INSERT INTO person_claims (account_id, person_id, message) VALUES (?, ?, ?)`).run(
user.id,
personId,
message,
);
} catch (err) {
if (/UNIQUE/.test(err.message)) return c.json({ error: "You already have a request waiting." }, 409);
throw err;
}
console.log(`claim: ${user.email} asked for ${personId}`);
return c.body(null, 204);
});
account.delete("/claim", (c) => {
c.get("db")
.prepare(`DELETE FROM person_claims WHERE account_id = ? AND status = 'pending'`)
.run(c.get("user").id);
return c.body(null, 204);
});
account.patch("/profile", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const person = myPerson(db, c.get("user").id);
if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
const sets = [];
const values = [];
const fields = {};
for (const [key, max] of Object.entries(PROFILE_FIELDS)) {
if (!(key in data)) continue;
const value = data[key] == null ? "" : String(data[key]).trim();
if (value.length > max) fields[key] = `Up to ${max} characters.`;
sets.push(`${key} = ?`);
values.push(value || null);
}
if (data.public_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(data.public_email).trim())) {
fields.public_email = "That doesn't look like an email address.";
}
if (Object.keys(fields).length) return c.json({ error: "Check the highlighted fields.", fields }, 422);
for (const key of HIDE_FIELDS) {
if (data.hidden && key in data.hidden) {
sets.push(`hide_${key} = ?`);
values.push(data.hidden[key] ? 1 : 0);
}
}
if (sets.length) {
db.prepare(`UPDATE people SET ${sets.join(", ")}, updated_at = datetime('now') WHERE id = ?`).run(
...values,
person.id,
);
console.log(`profile ${person.id} updated by ${c.get("user").email}`);
}
return c.json({ person: myPerson(db, c.get("user").id) }, 200, NO_STORE);
});
account.post(
"/photo",
bodyLimit({ maxSize: MAX_UPLOAD_BYTES + 64 * 1024, onError: (c) => c.json({ error: "That file is too large." }, 413) }),
async (c) => {
const db = c.get("db");
const user = c.get("user");
const person = myPerson(db, user.id);
if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
let form;
try {
form = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = form.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
if (!/^image\/(jpeg|png|webp)$/.test(file.type)) {
return c.json({ error: "Use a JPEG, PNG or WebP photo." }, 415);
}
let row;
try {
row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
originalName: person.display_name,
folder: "images",
userId: user.id,
});
} catch (err) {
if (err instanceof MediaError) return c.json({ error: err.message }, err.status ?? 422);
throw err;
}
db.prepare(`UPDATE people SET photo = ?, updated_at = datetime('now') WHERE id = ?`).run(
publicPath(row.filename),
person.id,
);
console.log(`profile ${person.id} photo ${row.filename} by ${user.email}`);
return c.json({ person: myPerson(db, user.id) }, 200, NO_STORE);
},
);
/* ── Discord ─────────────────────────────────────────────────── */
const DISCORD_COOKIE = SECURE_COOKIE ? "__Host-site_discord" : "site_discord";
const DISCORD_COOKIE_OPTIONS = { httpOnly: true, secure: SECURE_COOKIE, sameSite: "Lax", path: "/" };
const backToAccount = (c, result) => c.redirect(`/account?discord=${encodeURIComponent(result)}`, 302);
account.get("/discord", (c) => {
const config = discordConfig();
if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
if (!config.redirectUri) {
console.error("discord link: no return address. Set DISCORD_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.");
return backToAccount(c, "failed");
}
const { url, state } = startLink(config);
setCookie(c, DISCORD_COOKIE, state, { ...DISCORD_COOKIE_OPTIONS, maxAge: 600 });
return c.redirect(url, 302);
});
account.get("/discord/callback", async (c) => {
const config = discordConfig();
if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
const state = getCookie(c, DISCORD_COOKIE);
deleteCookie(c, DISCORD_COOKIE, DISCORD_COOKIE_OPTIONS);
if (c.req.query("error")) return backToAccount(c, "canceled");
const code = c.req.query("code");
if (!state || !code || c.req.query("state") !== state) return backToAccount(c, "expired");
let who;
try {
who = await finishLink(config, code);
} catch (err) {
console.warn(`discord link failed: ${err.message}`);
return backToAccount(c, "failed");
}
const db = c.get("db");
const user = c.get("user");
const taken = db.prepare(`SELECT id FROM admin_users WHERE discord_id = ? AND id <> ?`).get(who.id, user.id);
if (taken) return backToAccount(c, "taken");
db.prepare(`UPDATE admin_users SET discord_id = ?, discord_name = ? WHERE id = ?`).run(who.id, who.name, user.id);
console.log(`discord ${who.id} linked to ${user.email}`);
return backToAccount(c, "linked");
});
account.delete("/discord", (c) => {
c.get("db").prepare(`UPDATE admin_users SET discord_id = NULL, discord_name = NULL WHERE id = ?`).run(c.get("user").id);
return c.body(null, 204);
});
export default account;

View file

@ -5,7 +5,9 @@
POST /api/auth/logout deletes the session row and cookie
GET /api/auth/me who am I, or 401
GET /api/auth/providers which ways in are switched on
GET /api/auth/google off to Google's account chooser
GET /api/auth/google off to Google's account chooser;
?for=account from the site's sign-in
page (any Google account, back there)
GET /api/auth/google/callback back from it: sign in, or
back to the login page with ?error=
@ -27,6 +29,11 @@
email, which then links it. A matching email already linked to a
different Google account is refused rather than relinked.
googleAuth.js checks the identity itself.
Profile accounts (076) are made by an admin's invite
(routes/profiles.js). One may sign in with a Google account
outside the Workspace, under the invited email; an outside
identity reaches nothing else. Signing in takes up the invite.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
@ -153,7 +160,11 @@ const OAUTH_COOKIE_OPTIONS = {
const safeNext = (value) =>
typeof value === "string" && /^\/admin(\/[\w\-/]*)?$/.test(value) ? value : "/admin/home";
const backToLogin = (c, code) => c.redirect(`/admin/login?error=${encodeURIComponent(code)}`, 302);
// The page a sign-in started from: the admin's, or the site's
// (/sign-in, for profile accounts) when `from` is 'account'.
const SIGN_IN_PAGES = { admin: "/admin/login", account: "/sign-in" };
const backToLogin = (c, code, from = "admin") =>
c.redirect(`${SIGN_IN_PAGES[from] ?? SIGN_IN_PAGES.admin}?error=${encodeURIComponent(code)}`, 302);
auth.get("/providers", (c) =>
c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE),
@ -162,17 +173,18 @@ auth.get("/providers", (c) =>
auth.get("/google", (c) => {
const config = googleConfig();
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
const from = c.req.query("for") === "account" ? "account" : "admin";
if (!config.redirectUri) {
// Said in the log, where whoever runs the box will look; the
// person at the login page just learns it didn't work.
console.error(
"google login: no return address. Set GOOGLE_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.",
);
return backToLogin(c, "google_failed");
return backToLogin(c, "google_failed", from);
}
const { url, state, verifier } = startLogin(config);
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), {
const { url, state, verifier } = startLogin(config, { anyDomain: from === "account" });
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, from, next: safeNext(c.req.query("next")) }), {
...OAUTH_COOKIE_OPTIONS,
maxAge: 600,
});
@ -190,13 +202,15 @@ auth.get("/google/callback", async (c) => {
saved = null;
}
deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS);
const from = saved?.from === "account" ? "account" : "admin";
const back = (code) => backToLogin(c, code, from);
// Pressing Cancel on Google's screen comes back as ?error=.
if (c.req.query("error")) return backToLogin(c, "canceled");
if (c.req.query("error")) return back("canceled");
const code = c.req.query("code");
if (!saved?.state || !code || c.req.query("state") !== saved.state) {
return backToLogin(c, "expired");
return back("expired");
}
let identity;
@ -205,7 +219,7 @@ auth.get("/google/callback", async (c) => {
} catch (err) {
if (err instanceof GoogleLoginError) {
console.warn(`google login refused: ${err.code}`);
return backToLogin(c, err.code);
return back(err.code);
}
throw err;
}
@ -215,6 +229,20 @@ auth.get("/google/callback", async (c) => {
const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id);
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
// From outside the Workspace, only a profile account: by its
// linked Google id, or its invited email.
if (!identity.inDomain) {
user ??= db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
if (!user || user.role !== "member") {
console.warn(`google login: ${identity.email} is outside the Workspace and has no profile account`);
return back(user ? "wrong_domain" : "no_account");
}
if (user.google_sub && user.google_sub !== identity.sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return back("linked_elsewhere");
}
}
// What the access groups give this person (accessGroups.js), asked
// only when it matters. Unanswerable is a refusal: a sign-in has to
// be shown to be allowed.
@ -232,14 +260,14 @@ auth.get("/google/callback", async (c) => {
if (!byEmail) {
if (!accessEnabled(db)) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
return back("no_account");
}
// In an access group: the account is made now, Google only.
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
if (found.failed) return back("groups_unreachable");
if (!found.role) {
console.warn(`google login: ${identity.email} is in no access group`);
return backToLogin(c, "not_in_group");
return back("not_in_group");
}
const id = db
.prepare(
@ -251,10 +279,10 @@ auth.get("/google/callback", async (c) => {
user = byId(id);
} else if (byEmail.google_sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return backToLogin(c, "linked_elsewhere");
return back("linked_elsewhere");
} else {
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
if (byEmail.is_active !== 1) return back("disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
@ -266,23 +294,30 @@ auth.get("/google/callback", async (c) => {
// and with access groups switched off none gets in (it can't be
// rechecked, so it would keep its last role for good).
if (user.access_source === "group" && user.role !== "superadmin") {
if (!accessEnabled(db)) return backToLogin(c, "not_in_group");
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
if (!accessEnabled(db)) return back("not_in_group");
if (user.is_active !== 1 && user.group_disabled !== 1) return back("disabled");
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
if (found.failed) return back("groups_unreachable");
applyGroupRole(db, user, found.role);
if (!found.role) return backToLogin(c, "not_in_group");
if (!found.role) return back("not_in_group");
user = byId(user.id);
}
if (user.is_active !== 1) return backToLogin(c, "disabled");
if (user.is_active !== 1) return back("disabled");
createSession(db, c, user.id);
// The invite is taken up: its link stops working.
db.prepare(
`UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`,
).run(identity.name, user.id);
`UPDATE admin_users
SET last_login_at = datetime('now'), name = COALESCE(name, ?), google_sub = COALESCE(google_sub, ?),
invite_hash = NULL, invite_expires_at = NULL
WHERE id = ?`,
).run(identity.name, identity.sub, user.id);
console.log(`login ${user.email} (google)`);
// A profile account, or a sign-in from the site, goes to the
// profile page; the admin's goes back where it was headed.
if (user.role === "member" || from === "account") return c.redirect("/account", 302);
// Checked again: the cookie came back from the browser.
return c.redirect(safeNext(saved.next), 302);
});

View file

@ -45,7 +45,7 @@ function loadAuthors(db, ids) {
.prepare(
`SELECT a.post_id, p.id, p.display_name, p.pronouns, p.tagline, p.photo
FROM blog_post_authors a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id IN (${marks(ids.length)})
ORDER BY a.post_id, a.sort_order`,
)

View file

@ -437,7 +437,7 @@ function attachAwards(db, orgs) {
`SELECT a.id, a.org_id, a.name, a.description, a.logo,
(SELECT COUNT(*)
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a
WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 AND a.is_listed = 1
@ -579,7 +579,7 @@ content.get("/events/:id", (c) => {
pa.person_id, p.display_name, p.photo
FROM person_awards pa
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.event_id = ? AND pa.is_public = 1
ORDER BY a.sort_order, a.name, COALESCE(p.sort_name, p.display_name)`,
)
@ -774,7 +774,7 @@ content.get("/awards", (c) => {
`SELECT a.*, o.name AS org_name, o.kind AS org_kind,
(SELECT COUNT(*)
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a
LEFT JOIN organizations o ON o.id = a.org_id AND o.is_published = 1
@ -818,7 +818,7 @@ content.get("/awards/:id", (c) => {
p.display_name, p.photo, p.tagline,
e.id AS event_id, e.title AS event_title
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
LEFT JOIN events e ON e.id = pa.event_id AND e.is_published = 1
WHERE pa.award_id = ? AND pa.is_public = 1
ORDER BY pa.awarded_on DESC, COALESCE(p.sort_name, p.display_name)`,

View file

@ -188,7 +188,7 @@ function loadRosters(db, rows) {
`SELECT tep.entry_id, tep.person_id, tep.note,
p.display_name, p.photo
FROM timeline_entry_people tep
JOIN people p ON p.id = tep.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = tep.person_id AND p.is_published = 1
WHERE tep.entry_id IN (${marks(ids.length)})
ORDER BY tep.entry_id, tep.sort_order`,
)

View file

@ -66,7 +66,7 @@ const STAT_QUERIES = {
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
awards_given: `SELECT COUNT(*) AS n
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
WHERE pa.is_public = 1`,
};

View file

@ -129,7 +129,7 @@ people.get("/people", (c) => {
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM people p
FROM v_people_public p
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE p.id IN (${marks(ids.length)})
AND p.is_published = 1`,
@ -167,7 +167,7 @@ people.get("/directories/:tag", (c) => {
o.id AS primary_org_id,
o.name AS primary_org_name
FROM person_tags t
JOIN people p ON p.id = t.person_id AND p.is_published = 1 AND p.is_listed = 1
JOIN v_people_public p ON p.id = t.person_id AND p.is_published = 1 AND p.is_listed = 1
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE t.tag_id = ?
ORDER BY COALESCE(p.sort_name, p.display_name)`,
@ -221,7 +221,7 @@ people.get("/people/:id", (c) => {
o.id AS primary_org_id,
o.name AS primary_org_name,
o.kind AS primary_org_kind
FROM people p
FROM v_people_public p
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE p.id = ? AND p.is_published = 1`,
)

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;

View file

@ -27,11 +27,14 @@ export function loadLinks(db, ownerKind, ids) {
const out = new Map();
if (ids.length === 0) return out;
// A person who took their links off the site (people.hide_links,
// 076) has none here.
const rows = db
.prepare(
`SELECT owner_id, kind, platform, label, url, is_primary
FROM links
WHERE owner_kind = ? AND owner_id IN (${placeholders(ids.length)})
AND NOT (owner_kind = 'person' AND owner_id IN (SELECT id FROM people WHERE hide_links = 1))
ORDER BY owner_id, sort_order`,
)
.all(ownerKind, ...ids);
@ -106,7 +109,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
p.id AS person_id, p.display_name AS person_name,
p.photo AS person_photo, p.tagline AS person_tagline
FROM content_block_items i
LEFT JOIN people p ON p.id = i.person_id AND p.is_published = 1
LEFT JOIN v_people_public p ON p.id = i.person_id AND p.is_published = 1
WHERE i.block_id IN (${placeholders(blockIds.length)})
ORDER BY i.block_id, i.sort_order`,
)
@ -266,7 +269,7 @@ const FEATURED_REFS = {
person: {
sql: (marks) =>
`SELECT id, display_name AS title, tagline AS blurb, photo
FROM people WHERE is_published = 1 AND id IN (${marks})`,
FROM v_people_public WHERE is_published = 1 AND id IN (${marks})`,
image: (row) => (row.photo ? { file: row.photo, kind: "person" } : null),
},
team: {