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:
parent
0cc2a3f721
commit
e4c7e165d1
34 changed files with 2483 additions and 74 deletions
333
server/src/routes/account.js
Normal file
333
server/src/routes/account.js
Normal 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;
|
||||
|
|
@ -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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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`,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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)`,
|
||||
|
|
|
|||
|
|
@ -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`,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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`,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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`,
|
||||
)
|
||||
|
|
|
|||
198
server/src/routes/profiles.js
Normal file
198
server/src/routes/profiles.js
Normal 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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue