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
|
|
@ -40,6 +40,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.
|
||||
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
|
||||
- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`.
|
||||
- Profile accounts (migration 076): admins invite an email (Data → Profile accounts), the person sets a password from the link or signs in with any Google account under that email, claims their People record (an admin approves), then edits it and hides parts at `/account`. Public reads of people go through the `v_people_public` view, never `people`. Discord linking is off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set: `docs/profile-accounts.md`.
|
||||
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`.
|
||||
|
||||
## Git workflow
|
||||
|
|
@ -67,7 +68,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews), `/uploads/captions/` (videos' .vtt files); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`).
|
||||
|
||||
## Rules and gotchas
|
||||
- **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.
|
||||
- **Role checks must use ladder comparisons, never equality.** Roles rank member → viewer → editor → admin → superadmin (member is a profile account: the site and its own profile, never the admin; `/api/admin` needs viewer, `requireStaff`). Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `isStaff`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.
|
||||
- **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere.
|
||||
- **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names.
|
||||
- **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface.
|
||||
|
|
|
|||
|
|
@ -6,12 +6,16 @@ off until the service has an OAuth client ID and secret.
|
|||
|
||||
## Who gets in
|
||||
|
||||
Two kinds of account can sign in with Google:
|
||||
Three kinds of account can sign in with Google:
|
||||
|
||||
- **Group accounts**, when access groups are set up (below): anyone in
|
||||
one of the site's Workspace groups. Their account is made at their
|
||||
first sign-in, and their role follows the group.
|
||||
- **Accounts made with admin-cli**, as before.
|
||||
- **Profile accounts** (members, `docs/profile-accounts.md`), invited
|
||||
from Data → Profile accounts. These are the one case outside the
|
||||
Workspace: any Google account under the invited email, from the
|
||||
site's `/sign-in` page or the invite's welcome page.
|
||||
|
||||
Created with
|
||||
`admin-cli.js add <email>` (the password it asks for stays as a way in
|
||||
|
|
@ -23,7 +27,8 @@ changes. `admin-cli.js list` shows which accounts are linked.
|
|||
Refused, with a message on the login page: no admin account for that
|
||||
email (and in no access group), an email already linked to a different Google account, a
|
||||
disabled account, any account outside the Workspace domain (checked by
|
||||
Google's `hd` claim, not just the email), an unverified email.
|
||||
Google's `hd` claim, not just the email) unless it's a profile account's,
|
||||
an unverified email.
|
||||
|
||||
Code: `server/src/googleAuth.js` (the Google side),
|
||||
`server/src/routes/auth.js` (matching and linking accounts) and
|
||||
|
|
|
|||
78
docs/profile-accounts.md
Normal file
78
docs/profile-accounts.md
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
# Profile accounts
|
||||
|
||||
People can have an account on the site for their own profile (migration
|
||||
076). Nobody signs up: an admin invites them.
|
||||
|
||||
## How it goes
|
||||
|
||||
1. **Invite.** Data → Profile accounts → Invite someone (admins and up):
|
||||
an email, and a name if you like. That makes a *member* account with
|
||||
no password, and shows its invite link once, for 14 days. Copy it to
|
||||
send yourself, or press Email invite to send a fresh one through
|
||||
Gmail (needs Gmail set up, `docs/google-drive-and-mail.md`; the link
|
||||
shown before stops working).
|
||||
2. **Sign up.** The link opens `/account/welcome`: they set a password,
|
||||
or continue with Google under the invited email (any Google account,
|
||||
not only @nextgenerationofunity.org, when Google sign-in is on,
|
||||
`docs/google-sign-in.md`). Either takes up the invite.
|
||||
3. **Claim.** On `/account` (Your profile, also the footer's Sign in
|
||||
link) they pick the People record that's them and send the request.
|
||||
It waits under Claims on Data → Profile accounts until an admin
|
||||
approves or declines it. An admin can also set an account's record
|
||||
directly there.
|
||||
4. **Edit.** With a record, they edit its pronouns, tagline, location,
|
||||
public email and phone, bio and photo, and tick what to hide on the
|
||||
site. Their name, publishing and everything else stay the admin's.
|
||||
Changes are live as soon as they save.
|
||||
|
||||
A member is below viewer: signed in to the site, never to the admin
|
||||
(`/api/admin` refuses anything under viewer, `requireStaff` in
|
||||
`server/src/auth.js`). Staff accounts can claim a record too, from
|
||||
`/account`.
|
||||
|
||||
Forgotten password: on the account's row, New sign-in link (or Email a
|
||||
sign-in link); opening it sets a new password.
|
||||
|
||||
Turn off stops an account signing in and ends its sessions. Remove
|
||||
deletes the account; its People record stays.
|
||||
|
||||
## What "hidden" does
|
||||
|
||||
Each hidden part (photo, pronouns, tagline, bio, public email, public
|
||||
phone, location, links) stays in the record, and the admin's People
|
||||
editor shows the same switches (Hidden on the site). The site never
|
||||
shows it: every public read goes through the `v_people_public` view,
|
||||
which nulls hidden fields, and person links are left out when links are
|
||||
hidden (`loadLinks` in `server/src/shape.js`). When adding a public
|
||||
query on people, read `v_people_public`, not `people`.
|
||||
|
||||
## Discord
|
||||
|
||||
A profile can link its Discord account (the `identify` scope only: the
|
||||
Discord user id and name), kept for the gamification to come. Off until
|
||||
the service has a Discord application:
|
||||
|
||||
1. https://discord.com/developers/applications → New Application.
|
||||
2. OAuth2 → Redirects: add `https://nextgenerationofunity.org/api/account/discord/callback`
|
||||
(and the dev server's address, if you test there).
|
||||
3. Copy the Client ID and Client Secret into the service's environment
|
||||
(`systemctl edit ngu-api`):
|
||||
|
||||
```
|
||||
[Service]
|
||||
Environment=DISCORD_CLIENT_ID=...
|
||||
Environment=DISCORD_CLIENT_SECRET=...
|
||||
```
|
||||
|
||||
`DISCORD_REDIRECT_URI` overrides the return address (default: site.json's
|
||||
`url` plus `/api/account/discord/callback`).
|
||||
4. `systemctl restart ngu-api`.
|
||||
|
||||
An admin can set or clear an account's Discord id by hand on its row
|
||||
(the long number from Discord: Developer Mode, then Copy User ID).
|
||||
|
||||
Code: `server/src/invites.js`, `server/src/discordAuth.js`,
|
||||
`server/src/routes/account.js` (the member's own routes),
|
||||
`server/src/routes/profiles.js` (the admin's), `src/pages/Account.tsx`,
|
||||
`src/pages/AccountWelcome.tsx`, `src/pages/SignIn.tsx`,
|
||||
`src/pages/admin/AdminProfiles.tsx`.
|
||||
|
|
@ -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: [
|
||||
|
|
|
|||
|
|
@ -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
84
server/src/discordAuth.js
Normal 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 };
|
||||
}
|
||||
|
|
@ -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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
89
server/src/invites.js
Normal 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"),
|
||||
});
|
||||
}
|
||||
264
server/src/migrations/076_profile_accounts.sql
Normal file
264
server/src/migrations/076_profile_accounts.sql
Normal 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;
|
||||
|
|
@ -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) {
|
||||
|
|
|
|||
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;
|
||||
|
|
@ -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: {
|
||||
|
|
|
|||
14
src/App.tsx
14
src/App.tsx
|
|
@ -59,6 +59,10 @@ const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
|
|||
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
|
||||
const Terms = lazyPage(() => import("./pages/Terms.tsx"))
|
||||
const NotFound = lazyPage(() => import("./pages/NotFound.tsx"))
|
||||
// Profile accounts (076): signing in, an invite's welcome, the profile.
|
||||
const SignIn = lazyPage(() => import("./pages/SignIn.tsx"))
|
||||
const AccountWelcome = lazyPage(() => import("./pages/AccountWelcome.tsx"))
|
||||
const Account = lazyPage(() => import("./pages/Account.tsx"))
|
||||
|
||||
/*Entity Pages*/
|
||||
const EventDetail = lazyPage(() => import("./pages/EventDetail.tsx"))
|
||||
|
|
@ -82,12 +86,15 @@ const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
|
|||
const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
|
||||
const AdminVideoFrames = lazyPage(() => import("./pages/admin/AdminVideoFrames.tsx"))
|
||||
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
|
||||
const AdminProfiles = lazyPage(() => import("./pages/admin/AdminProfiles.tsx"))
|
||||
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
|
||||
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
{/* The whole app: the site shows a profile link and hidden pages by who's signed in. */}
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
{/* Layout renders the nav once and swaps page content into <Outlet /> */}
|
||||
<Route element={<Layout />}>
|
||||
|
|
@ -114,6 +121,9 @@ export default function App() {
|
|||
<Route path="give" element={<Giving />} />
|
||||
<Route path="privacy" element={<Privacy />} />
|
||||
<Route path="terms" element={<Terms />} />
|
||||
<Route path="sign-in" element={<SignIn />} />
|
||||
<Route path="account" element={<Account />} />
|
||||
<Route path="account/welcome" element={<AccountWelcome />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
{/* A schedule as a slideshow for a screen: full screen, no Layout. */}
|
||||
|
|
@ -127,11 +137,9 @@ export default function App() {
|
|||
/>
|
||||
<Route
|
||||
element={
|
||||
<AuthProvider>
|
||||
<Suspense fallback={null}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
</AuthProvider>
|
||||
}
|
||||
>
|
||||
<Route path="/admin/login" element={<AdminLogin />} />
|
||||
|
|
@ -152,6 +160,7 @@ export default function App() {
|
|||
</Route>
|
||||
<Route element={<RequireRole role="admin" />}>
|
||||
<Route path="clips" element={<AdminClips />} />
|
||||
<Route path="profiles" element={<AdminProfiles />} />
|
||||
</Route>
|
||||
<Route path=":entity" element={<EntityList />} />
|
||||
<Route path=":entity/:id" element={<EntityEdit />} />
|
||||
|
|
@ -159,6 +168,7 @@ export default function App() {
|
|||
</Route>
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Link } from "react-router-dom";
|
||||
import { useNavSections } from "../lib/navSections.ts";
|
||||
import { useSiteNav } from "../lib/useSiteNav.ts";
|
||||
import { useAuth } from "../lib/auth.tsx";
|
||||
import SiteLink from "./SiteLink.tsx";
|
||||
import siteLogo from "../assets/logos/NGU_Logo.svg";
|
||||
import PlatformIcon from "./PlatformIcon.tsx";
|
||||
|
|
@ -10,7 +11,8 @@ import { SOCIAL_LINKS } from "../data/socialLinks.ts";
|
|||
/* Every link here is Pages → Navigation's (useSiteNav): the filled
|
||||
header buttons (Give) beside the logo, Get in Touch, the site map
|
||||
(the header's pages, their sections and the pages set under them)
|
||||
and the bottom row. */
|
||||
and the bottom row. The bottom row ends with the profile account's
|
||||
way in (076): Sign in, or Your profile once signed in. */
|
||||
|
||||
const footerLinkClass =
|
||||
"text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors";
|
||||
|
|
@ -27,6 +29,7 @@ const headingClass = "text-white/90 text-sm font-semibold mb-4";
|
|||
export default function Footer() {
|
||||
const sectionsOf = useNavSections();
|
||||
const nav = useSiteNav();
|
||||
const { user } = useAuth();
|
||||
return (
|
||||
<footer className="py-16 px-6" style={{ background: "#001011" }}>
|
||||
<div className="max-w-6xl mx-auto">
|
||||
|
|
@ -144,12 +147,15 @@ export default function Footer() {
|
|||
|
||||
<div className="border-t border-white/10 pt-8 flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
<p className="text-white/65 text-sm">© 2026 Next Generation of Unity. All rights reserved.</p>
|
||||
<div className="flex gap-6">
|
||||
<div className="flex flex-wrap justify-center gap-x-6 gap-y-2">
|
||||
{nav.legal.map((link) => (
|
||||
<SiteLink key={`${link.label}${link.path}`} link={link} className={footerLinkClass}>
|
||||
{link.label}
|
||||
</SiteLink>
|
||||
))}
|
||||
<Link to={user ? "/account" : "/sign-in"} className={footerLinkClass}>
|
||||
{user ? "Your profile" : "Sign in"}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
12
src/components/GoogleLogo.tsx
Normal file
12
src/components/GoogleLogo.tsx
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
/* Google's "G", for the Sign in with Google buttons: a brand mark,
|
||||
so drawn as Google gives it rather than as a Phosphor icon. */
|
||||
export default function GoogleLogo({ className = 'h-5 w-5' }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 48 48" className={className} aria-hidden="true">
|
||||
<path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z" />
|
||||
<path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z" />
|
||||
<path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.5 39.6 16.2 44 24 44z" />
|
||||
<path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.4-.4-3.5z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
|
@ -83,6 +83,20 @@ export const people = {
|
|||
note: "Unpublished people are invisible everywhere.",
|
||||
fields: [PUBLISHED_FIELD, LISTED_FIELD],
|
||||
},
|
||||
{
|
||||
legend: "Hidden on the site",
|
||||
note: "Ticked parts stay here but don't show anywhere on the site. Someone with a profile account who has claimed this person sets these on their profile too (Data → Profile accounts).",
|
||||
fields: [
|
||||
["photo", "Photo"],
|
||||
["pronouns", "Pronouns"],
|
||||
["tagline", "Tagline"],
|
||||
["bio", "Bio"],
|
||||
["email", "Public email"],
|
||||
["phone", "Public phone"],
|
||||
["location", "Location"],
|
||||
["links", "Links"],
|
||||
].map(([key, label]) => ({ path: `hide_${key}`, label: `Hide ${label.toLowerCase()}`, widget: "checkbox" })),
|
||||
},
|
||||
],
|
||||
|
||||
children: [
|
||||
|
|
|
|||
|
|
@ -123,7 +123,7 @@ export function peek(path) {
|
|||
return settled.get(path);
|
||||
}
|
||||
|
||||
export function invalidate(path) {
|
||||
export function invalidate(path?: string) {
|
||||
if (path) {
|
||||
cache.delete(path);
|
||||
settled.delete(path);
|
||||
|
|
|
|||
|
|
@ -10,13 +10,19 @@
|
|||
RequireAuth guards routes. Worth being clear about what that
|
||||
does and doesn't do: it hides the interface, not the data. The
|
||||
protection is the 401 from /api/admin, this only stops someone
|
||||
staring at an empty table.
|
||||
staring at an empty table. A profile account (member) is signed
|
||||
in but has no admin, so it's sent to its page on the site.
|
||||
|
||||
The provider wraps the whole app, since the site shows a profile
|
||||
link and hidden pages by who's signed in. Signing in or out drops
|
||||
the API cache: the nav and hidden pages depend on it.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import { Navigate, Outlet, useLocation } from "react-router-dom";
|
||||
|
||||
import { get, post, ApiError } from "./api.ts";
|
||||
import { get, invalidate, post, ApiError } from "./api.ts";
|
||||
import { isStaff } from "./roles.ts";
|
||||
|
||||
const AuthContext = createContext<any>(null);
|
||||
|
||||
|
|
@ -45,6 +51,7 @@ export function AuthProvider({ children }) {
|
|||
|
||||
const login = useCallback(async (email, password) => {
|
||||
const data = await post("/auth/login", { email, password });
|
||||
invalidate();
|
||||
setUser(data.user);
|
||||
return data.user;
|
||||
}, []);
|
||||
|
|
@ -54,12 +61,19 @@ export function AuthProvider({ children }) {
|
|||
await post("/auth/logout", {});
|
||||
} finally {
|
||||
// Whatever the server said, this browser is done.
|
||||
invalidate();
|
||||
setUser(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// After a sign-in the server did itself (an invite's password).
|
||||
const signedIn = useCallback((next) => {
|
||||
invalidate();
|
||||
setUser(next);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, signedIn }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
|
@ -94,5 +108,7 @@ export function RequireAuth() {
|
|||
return <Navigate to="/admin/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
if (!isStaff(user)) return <Navigate to="/account" replace />;
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,18 +14,22 @@
|
|||
role to be added, and there's now a fourth.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
export const ROLES = ["viewer", "editor", "admin", "superadmin"] as const;
|
||||
/* member is a profile account (076): the site and their own profile,
|
||||
never the admin. */
|
||||
export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"] as const;
|
||||
|
||||
export type Role = (typeof ROLES)[number];
|
||||
|
||||
export const ROLE_RANK: Record<Role, number> = {
|
||||
viewer: 1,
|
||||
editor: 2,
|
||||
admin: 3,
|
||||
superadmin: 4,
|
||||
member: 1,
|
||||
viewer: 2,
|
||||
editor: 3,
|
||||
admin: 4,
|
||||
superadmin: 5,
|
||||
};
|
||||
|
||||
export const ROLE_LABELS: Record<Role, string> = {
|
||||
member: "Profile",
|
||||
viewer: "Viewer",
|
||||
editor: "Editor",
|
||||
admin: "Admin",
|
||||
|
|
@ -35,9 +39,10 @@ export const ROLE_LABELS: Record<Role, string> = {
|
|||
/* Each line is what that role adds to the one above it in the
|
||||
list. Read top to bottom, they describe the whole ladder. */
|
||||
export const ROLE_NOTES: Record<Role, string> = {
|
||||
member: "Signs in to the site to edit their own profile. No admin.",
|
||||
viewer: "Can read everything in the CMS and change nothing.",
|
||||
editor: "Can create and update records. Can't delete anything.",
|
||||
admin: "Can delete records, including feedback.",
|
||||
admin: "Can delete records, including feedback. Invites profile accounts and approves their claims.",
|
||||
superadmin: "Can manage accounts, roles and sessions.",
|
||||
};
|
||||
|
||||
|
|
@ -55,3 +60,5 @@ export function atLeast(user: MaybeUser, role: Role): boolean {
|
|||
export const canWrite = (user: MaybeUser) => atLeast(user, "editor");
|
||||
export const canDelete = (user: MaybeUser) => atLeast(user, "admin");
|
||||
export const isSuper = (user: MaybeUser) => atLeast(user, "superadmin");
|
||||
/* Uses the admin at all: a profile account (member) doesn't. */
|
||||
export const isStaff = (user: MaybeUser) => atLeast(user, "viewer");
|
||||
|
|
|
|||
44
src/lib/useAccount.ts
Normal file
44
src/lib/useAccount.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/* A profile account's own page (server/src/routes/account.js): the
|
||||
account, the People record it has (as its owner edits it), its
|
||||
claim, and Discord. Not cached: it changes as they edit it. */
|
||||
|
||||
import { useRecord, type Resource } from './useRecord.ts'
|
||||
|
||||
/* What an owner can take off the site (people.hide_*), in the order
|
||||
the profile page lists them. */
|
||||
export const HIDE_FIELDS = [
|
||||
['photo', 'Photo'],
|
||||
['pronouns', 'Pronouns'],
|
||||
['tagline', 'Tagline'],
|
||||
['bio', 'Bio'],
|
||||
['email', 'Public email'],
|
||||
['phone', 'Public phone'],
|
||||
['location', 'Location'],
|
||||
['links', 'Links'],
|
||||
] as const
|
||||
|
||||
export type HideField = (typeof HIDE_FIELDS)[number][0]
|
||||
|
||||
export type MyPerson = {
|
||||
id: string
|
||||
display_name: string
|
||||
is_published: boolean
|
||||
photo: string | null
|
||||
pronouns: string | null
|
||||
tagline: string | null
|
||||
bio: string | null
|
||||
public_email: string | null
|
||||
public_phone: string | null
|
||||
location_label: string | null
|
||||
hidden: Record<HideField, boolean>
|
||||
}
|
||||
|
||||
export type MyAccount = {
|
||||
user: { id: number; email: string; name: string | null; role: string }
|
||||
person: MyPerson | null
|
||||
claim: { id: number; person_id: string; display_name: string; status: 'pending' | 'approved' | 'declined' } | null
|
||||
discord: { enabled: boolean; id: string | null; name: string | null }
|
||||
}
|
||||
|
||||
export const useMyAccount = (enabled: boolean): Resource<MyAccount> =>
|
||||
useRecord(enabled ? '/account' : null, 'account')
|
||||
416
src/pages/Account.tsx
Normal file
416
src/pages/Account.tsx
Normal file
|
|
@ -0,0 +1,416 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
YOUR PROFILE: /account, a profile account's page (076)
|
||||
|
||||
Your account who's signed in, sign out (and the admin, for
|
||||
an admin account)
|
||||
Your profile before a record is theirs: ask to claim one (an
|
||||
admin approves it); after: edit its text and
|
||||
photo, and choose what of it shows on the site
|
||||
Discord link it (or unlink), for the gamification to come
|
||||
|
||||
Signed out, it's the sign-in page's job. Everything is saved
|
||||
through routes/account.js, which only ever writes the account's
|
||||
own person.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link, Navigate, useSearchParams } from 'react-router-dom'
|
||||
import { ArrowSquareOut, SignOut } from '@phosphor-icons/react'
|
||||
|
||||
import PageShell from '../components/PageShell.tsx'
|
||||
import { useAuth } from '../lib/auth.tsx'
|
||||
import { ApiError, del, get, patch, post, upload } from '../lib/api.ts'
|
||||
import { ACCENTS, BRAND } from '../lib/color.ts'
|
||||
import { mediaUrl } from '../lib/media.ts'
|
||||
import { personHref } from '../lib/hrefs.ts'
|
||||
import { ROLE_LABELS, isStaff, type Role } from '../lib/roles.ts'
|
||||
import { HIDE_FIELDS, useMyAccount, type MyAccount, type MyPerson } from '../lib/useAccount.ts'
|
||||
import { fieldClass, primaryButton } from './SignIn.tsx'
|
||||
|
||||
const quietButton =
|
||||
'btn border border-brand px-5 py-2.5 text-link transition-colors hover:bg-tint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:opacity-60'
|
||||
|
||||
/* What ?discord= says after the trip to Discord (routes/account.js). */
|
||||
const DISCORD_RESULTS: Record<string, string> = {
|
||||
linked: 'Your Discord account is linked.',
|
||||
canceled: 'Linking Discord was canceled.',
|
||||
expired: 'That took too long. Try again.',
|
||||
taken: 'That Discord account is already linked to another profile.',
|
||||
failed: "Discord didn't link. Try again in a moment.",
|
||||
}
|
||||
|
||||
const message = (err: unknown) =>
|
||||
err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment."
|
||||
|
||||
function Alert({ children, tone = 'danger' }: { children: React.ReactNode; tone?: 'danger' | 'ok' }) {
|
||||
return (
|
||||
<p
|
||||
role={tone === 'danger' ? 'alert' : 'status'}
|
||||
className={`mt-4 px-4 py-3 text-sm ${
|
||||
tone === 'danger' ? 'border border-danger/30 bg-danger-tint text-danger' : 'border border-brand/30 bg-tint text-body'
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Account() {
|
||||
const { user, loading, logout } = useAuth()
|
||||
const { data, error, reload } = useMyAccount(Boolean(user))
|
||||
|
||||
if (loading) return null
|
||||
if (!user) return <Navigate to="/sign-in" replace />
|
||||
|
||||
const content = (part: React.ReactNode) => <div className="mx-auto max-w-3xl px-6">{part}</div>
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
title="Your profile"
|
||||
intro="Your account on the site, the profile that's yours, and what of it shows."
|
||||
sections={[
|
||||
{
|
||||
id: 'account',
|
||||
title: 'Your account',
|
||||
accent: BRAND,
|
||||
content: content(
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 bg-raised p-6 shadow-md">
|
||||
<div>
|
||||
<p className="font-semibold text-ink">{user.name || user.email}</p>
|
||||
<p className="text-sm text-muted">
|
||||
{user.email} · {ROLE_LABELS[user.role as Role] ?? user.role}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{isStaff(user) && (
|
||||
<Link to="/admin/home" className={quietButton}>
|
||||
Admin
|
||||
</Link>
|
||||
)}
|
||||
<button type="button" onClick={logout} className={`${quietButton} inline-flex items-center gap-2`}>
|
||||
<SignOut size={18} weight="bold" aria-hidden="true" />
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>,
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'profile',
|
||||
title: 'Your profile',
|
||||
blurb: 'Your page on the site, eg. on a team or an event. Ask for yours, then edit it here.',
|
||||
accent: ACCENTS.green,
|
||||
content: content(
|
||||
error ? (
|
||||
<p className="text-danger">Couldn't load your profile. {error}</p>
|
||||
) : !data ? (
|
||||
<div className="skeleton !min-h-40" aria-label="Loading your profile" />
|
||||
) : data.person ? (
|
||||
<ProfileEditor key={data.person.id} person={data.person} onSaved={reload} />
|
||||
) : (
|
||||
<Claim account={data} onChange={reload} />
|
||||
),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'discord',
|
||||
title: 'Discord',
|
||||
blurb: 'Link your Discord account so what you do there can count here.',
|
||||
accent: ACCENTS.amber,
|
||||
content: content(data ? <Discord account={data} onChange={reload} /> : null),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Claiming a record ───────────────────────────────────────── */
|
||||
|
||||
function Claim({ account, onChange }: { account: MyAccount; onChange: () => void }) {
|
||||
const [people, setPeople] = useState<{ id: string; name: string }[] | null>(null)
|
||||
const [personId, setPersonId] = useState('')
|
||||
const [note, setNote] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const pending = account.claim?.status === 'pending' ? account.claim : null
|
||||
|
||||
useEffect(() => {
|
||||
if (pending) return
|
||||
get('/account/people', { ttl: 0 })
|
||||
.then((data) => setPeople(data.people))
|
||||
.catch((err) => setError(message(err)))
|
||||
}, [pending])
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await action()
|
||||
onChange()
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (pending) {
|
||||
return (
|
||||
<div className="notice p-5">
|
||||
<p className="text-body">
|
||||
You asked to be <strong>{pending.display_name}</strong>. An admin will look at it soon.
|
||||
</p>
|
||||
<button type="button" disabled={busy} onClick={() => run(() => del('/account/claim'))} className={`mt-4 ${quietButton}`}>
|
||||
Take back the request
|
||||
</button>
|
||||
{error && <Alert>{error}</Alert>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
run(() => post('/account/claim', { person_id: personId, message: note }))
|
||||
}}
|
||||
className="bg-raised p-6 shadow-md"
|
||||
>
|
||||
{account.claim?.status === 'declined' && (
|
||||
<p className="mb-4 text-sm text-muted">
|
||||
Your request to be {account.claim.display_name} wasn't approved. Pick again, or say more in the note.
|
||||
</p>
|
||||
)}
|
||||
<label htmlFor="claim-person" className="block text-sm font-medium text-body">
|
||||
Which person on the site is you?
|
||||
</label>
|
||||
<select
|
||||
id="claim-person"
|
||||
value={personId}
|
||||
onChange={(e) => setPersonId(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
disabled={!people}
|
||||
>
|
||||
<option value="">{people ? 'Choose your name' : 'Loading…'}</option>
|
||||
{people?.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="mt-1 text-xs text-muted">Not listed? Ask us through the Request page to add you.</p>
|
||||
<label htmlFor="claim-note" className="mt-5 block text-sm font-medium text-body">
|
||||
A note for the admin <span className="font-normal text-muted">(optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
id="claim-note"
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
{error && <Alert>{error}</Alert>}
|
||||
<button type="submit" disabled={busy || !personId} className={`mt-6 ${primaryButton}`}>
|
||||
{busy ? 'Sending…' : 'Ask for this profile'}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Editing it ──────────────────────────────────────────────── */
|
||||
|
||||
const TEXT_FIELDS: { key: keyof MyPerson; label: string; help?: string; long?: boolean; type?: string }[] = [
|
||||
{ key: 'pronouns', label: 'Pronouns', help: 'eg. she/her' },
|
||||
{ key: 'tagline', label: 'Tagline', help: 'A line under your name when you have no title, eg. Musician and youth leader' },
|
||||
{ key: 'location_label', label: 'Location', help: 'eg. Kansas City, MO' },
|
||||
{ key: 'public_email', label: 'Public email', type: 'email', help: 'Shown on your page. Leave it blank for none.' },
|
||||
{ key: 'public_phone', label: 'Public phone', type: 'tel' },
|
||||
{ key: 'bio', label: 'Bio', long: true, help: 'A blank line starts a new paragraph.' },
|
||||
]
|
||||
|
||||
function ProfileEditor({ person, onSaved }: { person: MyPerson; onSaved: () => void }) {
|
||||
const [values, setValues] = useState(() =>
|
||||
Object.fromEntries(TEXT_FIELDS.map(({ key }) => [key, (person[key] as string | null) ?? ''])),
|
||||
)
|
||||
const [hidden, setHidden] = useState(person.hidden)
|
||||
const [photo, setPhoto] = useState(person.photo)
|
||||
const [fields, setFields] = useState<Record<string, string>>({})
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
async function save(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setFields({})
|
||||
setSaved(false)
|
||||
try {
|
||||
await patch('/account/profile', { ...values, hidden })
|
||||
setSaved(true)
|
||||
onSaved()
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
if (err instanceof ApiError && err.fields) setFields(err.fields)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function sendPhoto(file: File | undefined) {
|
||||
if (!file) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
const data = await upload('/account/photo', form)
|
||||
setPhoto(data.person.photo)
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={save} noValidate className="bg-raised p-6 shadow-md sm:p-8">
|
||||
<div className="flex flex-wrap items-center gap-5">
|
||||
{photo ? (
|
||||
<img src={mediaUrl(photo) ?? undefined} alt="" className="h-24 w-24 object-cover" />
|
||||
) : (
|
||||
<div className="flex h-24 w-24 items-center justify-center bg-tint text-sm text-muted">No photo</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-xl font-bold text-ink">{person.display_name}</p>
|
||||
{person.is_published ? (
|
||||
<Link to={personHref(person.id)} className="inline-flex items-center gap-1 text-sm text-link underline">
|
||||
Your page on the site
|
||||
<ArrowSquareOut size={14} weight="bold" aria-hidden="true" />
|
||||
</Link>
|
||||
) : (
|
||||
<p className="text-sm text-muted">Your page isn't on the site yet.</p>
|
||||
)}
|
||||
<label className={`mt-3 inline-block cursor-pointer ${quietButton}`}>
|
||||
{photo ? 'Change photo' : 'Add a photo'}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="sr-only"
|
||||
disabled={busy}
|
||||
onChange={(e) => sendPhoto(e.target.files?.[0])}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-muted">Your name is changed by an admin: ask through the Request page.</p>
|
||||
|
||||
<div className="mt-8 grid gap-5 sm:grid-cols-2">
|
||||
{TEXT_FIELDS.map(({ key, label, help, long, type }) => (
|
||||
<div key={key} className={long ? 'sm:col-span-2' : ''}>
|
||||
<label htmlFor={`profile-${key}`} className="block text-sm font-medium text-body">
|
||||
{label}
|
||||
</label>
|
||||
{long ? (
|
||||
<textarea
|
||||
id={`profile-${key}`}
|
||||
rows={6}
|
||||
value={values[key]}
|
||||
onChange={(e) => setValues({ ...values, [key]: e.target.value })}
|
||||
aria-describedby={help ? `profile-${key}-help` : undefined}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
id={`profile-${key}`}
|
||||
type={type ?? 'text'}
|
||||
value={values[key]}
|
||||
onChange={(e) => setValues({ ...values, [key]: e.target.value })}
|
||||
aria-describedby={help ? `profile-${key}-help` : undefined}
|
||||
aria-invalid={Boolean(fields[key])}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
)}
|
||||
{fields[key] && <p className="mt-1 text-sm text-danger">{fields[key]}</p>}
|
||||
{help && (
|
||||
<p id={`profile-${key}-help`} className="mt-1 text-xs text-muted">
|
||||
{help}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<fieldset className="mt-8">
|
||||
<legend className="text-base font-semibold text-body">Hide on the site</legend>
|
||||
<p className="mt-1 text-sm text-muted">
|
||||
Ticked parts stay saved but don't show anywhere on the site: your page, team and event lists, people tiles.
|
||||
</p>
|
||||
<div className="mt-3 grid gap-2 sm:grid-cols-2">
|
||||
{HIDE_FIELDS.map(([key, label]) => (
|
||||
<label key={key} className="flex items-center gap-3 text-body">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={hidden[key]}
|
||||
onChange={(e) => setHidden({ ...hidden, [key]: e.target.checked })}
|
||||
className="h-4 w-4 accent-[var(--color-action)]"
|
||||
/>
|
||||
Hide {label.toLowerCase()}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
{error && <Alert>{error}</Alert>}
|
||||
{saved && !error && <Alert tone="ok">Saved. It's on the site now.</Alert>}
|
||||
<button type="submit" disabled={busy} className={`mt-6 ${primaryButton}`}>
|
||||
{busy ? 'Saving…' : 'Save profile'}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Discord ─────────────────────────────────────────────────── */
|
||||
|
||||
function Discord({ account, onChange }: { account: MyAccount; onChange: () => void }) {
|
||||
const [searchParams] = useSearchParams()
|
||||
const result = searchParams.get('discord')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const { discord } = account
|
||||
|
||||
async function unlink() {
|
||||
setError(null)
|
||||
try {
|
||||
await del('/account/discord')
|
||||
onChange()
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-raised p-6 shadow-md">
|
||||
{discord.id ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<p className="text-body">
|
||||
Linked to <strong>{discord.name ?? discord.id}</strong>.
|
||||
</p>
|
||||
<button type="button" onClick={unlink} className={quietButton}>
|
||||
Unlink
|
||||
</button>
|
||||
</div>
|
||||
) : discord.enabled ? (
|
||||
<a href="/api/account/discord" className={`inline-block ${primaryButton}`}>
|
||||
Link Discord
|
||||
</a>
|
||||
) : (
|
||||
<p className="text-muted">Linking Discord isn't switched on yet. An admin can link it for you.</p>
|
||||
)}
|
||||
{result && DISCORD_RESULTS[result] && (
|
||||
<Alert tone={result === 'linked' ? 'ok' : 'danger'}>{DISCORD_RESULTS[result]}</Alert>
|
||||
)}
|
||||
{error && <Alert>{error}</Alert>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
142
src/pages/AccountWelcome.tsx
Normal file
142
src/pages/AccountWelcome.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
WELCOME: /account/welcome?token=…, an invite's link (076)
|
||||
|
||||
Who the invite is for, then a password to set, or Google under the
|
||||
invited email. Either takes up the invite: the link stops working
|
||||
and the account is signed in (routes/account.js, routes/auth.js).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
|
||||
import PageShell from '../components/PageShell.tsx'
|
||||
import { useAuth } from '../lib/auth.tsx'
|
||||
import { ApiError, get, post } from '../lib/api.ts'
|
||||
import { BRAND } from '../lib/color.ts'
|
||||
import { GoogleButton, fieldClass, primaryButton } from './SignIn.tsx'
|
||||
|
||||
const MIN_PASSWORD = 12
|
||||
|
||||
type Invite = { email: string; name: string | null; google: boolean }
|
||||
|
||||
export default function AccountWelcome() {
|
||||
const [searchParams] = useSearchParams()
|
||||
const token = searchParams.get('token') ?? ''
|
||||
const navigate = useNavigate()
|
||||
const { signedIn } = useAuth()
|
||||
|
||||
const [invite, setInvite] = useState<Invite | null>(null)
|
||||
const [problem, setProblem] = useState<string | null>(null)
|
||||
const [password, setPassword] = useState('')
|
||||
const [again, setAgain] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setProblem('This page needs the link from your invite email.')
|
||||
return
|
||||
}
|
||||
get(`/account/invite?token=${encodeURIComponent(token)}`, { ttl: 0 })
|
||||
.then((data) => setInvite(data.invite))
|
||||
.catch((err) => setProblem(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment."))
|
||||
}, [token])
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
if (busy) return
|
||||
if (password.length < MIN_PASSWORD) return setError(`Use at least ${MIN_PASSWORD} characters.`)
|
||||
if (password !== again) return setError("The two passwords don't match.")
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const data = await post('/account/accept', { token, password })
|
||||
signedIn(data.user)
|
||||
navigate('/account', { replace: true })
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment.")
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
title="Welcome"
|
||||
intro="You've been invited to make a profile account."
|
||||
sections={[
|
||||
{
|
||||
id: 'welcome',
|
||||
title: invite?.name ? `Hi, ${invite.name}` : 'Your account',
|
||||
accent: BRAND,
|
||||
content: (
|
||||
<div className="mx-auto max-w-md px-6">
|
||||
{problem ? (
|
||||
<div className="notice p-5">
|
||||
<p className="text-body">{problem}</p>
|
||||
<p className="mt-2 text-sm text-muted">
|
||||
Already set up? <Link to="/sign-in" className="text-link underline">Sign in</Link>. Otherwise ask whoever invited you for a new link.
|
||||
</p>
|
||||
</div>
|
||||
) : !invite ? (
|
||||
<div className="skeleton !min-h-40" aria-label="Checking your invite" />
|
||||
) : (
|
||||
<form onSubmit={submit} noValidate className="bg-raised p-6 shadow-md sm:p-8">
|
||||
<p className="text-sm text-muted">
|
||||
Your account is <strong className="text-body">{invite.email}</strong>.
|
||||
</p>
|
||||
{invite.google && (
|
||||
<>
|
||||
<div className="mt-5">
|
||||
<GoogleButton label="Continue with Google" />
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted">Sign in to Google as {invite.email}.</p>
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-muted">
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
or set a password
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<label htmlFor="welcome-password" className={`${invite.google ? '' : 'mt-5 '}block text-sm font-medium text-body`}>
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="welcome-password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
aria-describedby="welcome-password-help"
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
<p id="welcome-password-help" className="mt-1 text-xs text-muted">
|
||||
At least {MIN_PASSWORD} characters.
|
||||
</p>
|
||||
<label htmlFor="welcome-again" className="mt-5 block text-sm font-medium text-body">
|
||||
Password again
|
||||
</label>
|
||||
<input
|
||||
id="welcome-again"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={again}
|
||||
onChange={(e) => setAgain(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
{error && (
|
||||
<p role="alert" className="mt-5 border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" disabled={busy || !password || !again} className={`mt-6 w-full ${primaryButton}`}>
|
||||
{busy ? 'Setting up…' : 'Set password and sign in'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
157
src/pages/SignIn.tsx
Normal file
157
src/pages/SignIn.tsx
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
SIGN IN: /sign-in, for profile accounts (076)
|
||||
|
||||
Accounts are by invite only (Data → Profile accounts), so there's
|
||||
no sign-up here: an invite's link (/account/welcome) sets the
|
||||
password, or the invited email signs in with Google, any Google
|
||||
account. The admin's own login (/admin/login) is the same accounts
|
||||
through another door; either lands an admin where they asked.
|
||||
|
||||
A Google refusal comes back here as ?error=<code> (routes/auth.js).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
|
||||
import PageShell from '../components/PageShell.tsx'
|
||||
import GoogleLogo from '../components/GoogleLogo.tsx'
|
||||
import { useAuth } from '../lib/auth.tsx'
|
||||
import { ApiError, get } from '../lib/api.ts'
|
||||
import { BRAND } from '../lib/color.ts'
|
||||
|
||||
export const SIGN_IN_TITLE = 'Sign in'
|
||||
|
||||
const GOOGLE_ERRORS: Record<string, string> = {
|
||||
canceled: 'Google sign-in was canceled.',
|
||||
expired: 'That sign-in took too long or was already used. Try again.',
|
||||
no_account: "There's no profile account for that Google account. Accounts are by invite: ask us to invite your email.",
|
||||
linked_elsewhere: "That email's account is linked to a different Google account.",
|
||||
disabled: 'That account has been turned off.',
|
||||
wrong_domain: 'Use your @nextgenerationofunity.org Google account for that one.',
|
||||
unverified: "That Google account's email isn't verified.",
|
||||
google_unreachable: "Couldn't reach Google. Try again in a moment.",
|
||||
google_failed: "Google sign-in didn't work. Try again, or use your password.",
|
||||
not_in_group: "That Google account isn't in a website access group.",
|
||||
groups_unreachable: "Couldn't check your Google groups just now. Try again in a moment.",
|
||||
}
|
||||
|
||||
export const fieldClass =
|
||||
'w-full border border-muted/50 bg-surface px-4 py-3 text-body outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25'
|
||||
|
||||
export const primaryButton =
|
||||
'btn bg-action px-6 py-3 text-white transition-colors hover:bg-action-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:bg-muted/25'
|
||||
|
||||
export function GoogleButton({ label = 'Sign in with Google' }: { label?: string }) {
|
||||
return (
|
||||
<a
|
||||
href="/api/auth/google?for=account"
|
||||
className="flex items-center justify-center gap-3 btn border border-muted/30 px-6 py-3 text-body transition-colors hover:bg-tint"
|
||||
>
|
||||
<GoogleLogo />
|
||||
{label}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
/* Whether the server has Google sign-in switched on. */
|
||||
export function useGoogleSignIn(): boolean {
|
||||
const [google, setGoogle] = useState(false)
|
||||
useEffect(() => {
|
||||
get('/auth/providers', { ttl: 0 })
|
||||
.then((data) => setGoogle(Boolean(data.google)))
|
||||
.catch(() => setGoogle(false))
|
||||
}, [])
|
||||
return google
|
||||
}
|
||||
|
||||
export default function SignIn() {
|
||||
const { user, loading, login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
const [searchParams] = useSearchParams()
|
||||
const googleError = searchParams.get('error')
|
||||
const google = useGoogleSignIn()
|
||||
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(
|
||||
googleError ? (GOOGLE_ERRORS[googleError] ?? GOOGLE_ERRORS.google_failed) : null,
|
||||
)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
if (!loading && user) return <Navigate to="/account" replace />
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await login(email.trim(), password)
|
||||
navigate('/account', { replace: true })
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment.")
|
||||
setPassword('')
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
title={SIGN_IN_TITLE}
|
||||
intro="For people with a profile account. Accounts are by invite: if you'd like one, ask us through the Request page."
|
||||
sections={[
|
||||
{
|
||||
id: 'sign-in',
|
||||
title: 'Your account',
|
||||
accent: BRAND,
|
||||
content: (
|
||||
<div className="mx-auto max-w-md px-6">
|
||||
<form onSubmit={submit} noValidate className="bg-raised p-6 shadow-md sm:p-8">
|
||||
{google && (
|
||||
<>
|
||||
<GoogleButton />
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-muted">
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
or with a password
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<label htmlFor="sign-in-email" className="block text-sm font-medium text-body">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="sign-in-email"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
<label htmlFor="sign-in-password" className="mt-5 block text-sm font-medium text-body">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="sign-in-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
{error && (
|
||||
<p role="alert" className="mt-5 border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" disabled={busy || !email || !password} className={`mt-6 w-full ${primaryButton}`}>
|
||||
{busy ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -18,6 +18,8 @@ import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
|
|||
|
||||
import { useAuth } from "../../lib/auth.tsx";
|
||||
import { ApiError, get } from "../../lib/api.ts";
|
||||
import { isStaff } from "../../lib/roles.ts";
|
||||
import GoogleLogo from "../../components/GoogleLogo.tsx";
|
||||
|
||||
/* What a ?error= from the Google callback means, in the words the
|
||||
person at the login page needs. */
|
||||
|
|
@ -74,8 +76,9 @@ export default function AdminLogin() {
|
|||
setError(null);
|
||||
|
||||
try {
|
||||
await login(email.trim(), password);
|
||||
navigate(destination, { replace: true });
|
||||
const user = await login(email.trim(), password);
|
||||
// A profile account has no admin: its page is on the site.
|
||||
navigate(isStaff(user) ? destination : "/account", { replace: true });
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError
|
||||
|
|
@ -106,12 +109,7 @@ export default function AdminLogin() {
|
|||
href={`/api/auth/google?next=${encodeURIComponent(destination)}`}
|
||||
className="flex items-center justify-center gap-3 btn border border-muted/30 px-6 py-3 text-body transition-colors hover:bg-tint"
|
||||
>
|
||||
<svg viewBox="0 0 48 48" className="h-5 w-5" aria-hidden="true">
|
||||
<path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z" />
|
||||
<path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z" />
|
||||
<path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.5 39.6 16.2 44 24 44z" />
|
||||
<path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.4-.4-3.5z" />
|
||||
</svg>
|
||||
<GoogleLogo />
|
||||
Sign in with Google
|
||||
</a>
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-muted">
|
||||
|
|
|
|||
450
src/pages/admin/AdminProfiles.tsx
Normal file
450
src/pages/admin/AdminProfiles.tsx
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
ADMIN: PROFILE ACCOUNTS (Data → Profile accounts, admins and up)
|
||||
|
||||
Profile accounts (076) are by invite: an email added here gets an
|
||||
account with no password and a link to set one (or to sign in
|
||||
with Google under that email). The link is shown once, to copy;
|
||||
Email invite sends a fresh one through Gmail and shows it too
|
||||
(the one before stops working). For an account already set up,
|
||||
the same link is a way back in when a password is forgotten.
|
||||
|
||||
Then: the claims waiting (someone asking to be a People record),
|
||||
and each account's record, Discord and whether it's on. Server
|
||||
side: server/src/routes/profiles.js. Admin accounts (viewer and
|
||||
up) are the Panel's, not this page's.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useCallback, useEffect, useId, useState, type FormEvent } from "react";
|
||||
|
||||
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
|
||||
import { preview } from "../../lib/text.ts";
|
||||
|
||||
const MUTED = "var(--color-muted)";
|
||||
|
||||
const button =
|
||||
"btn border border-brand px-3 py-1.5 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
|
||||
const primary =
|
||||
"btn bg-action px-5 py-2.5 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25";
|
||||
const danger =
|
||||
"btn border border-danger/40 px-3 py-1.5 text-sm text-danger transition-colors hover:bg-danger-tint disabled:opacity-50";
|
||||
const input =
|
||||
"w-full border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
|
||||
|
||||
type Account = {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string | null;
|
||||
is_active: number;
|
||||
created_at: string;
|
||||
last_login_at: string | null;
|
||||
invited_at: string | null;
|
||||
invite_expires_at: string | null;
|
||||
invite_open: number;
|
||||
signed_up: number;
|
||||
person_id: string | null;
|
||||
person_name: string | null;
|
||||
discord_id: string | null;
|
||||
discord_name: string | null;
|
||||
};
|
||||
|
||||
type Claim = {
|
||||
id: number;
|
||||
account_id: number;
|
||||
email: string;
|
||||
name: string | null;
|
||||
person_id: string;
|
||||
person_name: string;
|
||||
message: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
const message = (err: unknown) => (err instanceof ApiError ? err.message : "Couldn't reach the server.");
|
||||
const day = (value: string | null) => (value ? value.slice(0, 10) : "-");
|
||||
|
||||
/* A link to copy, shown once. */
|
||||
function LinkBox({ link, note }: { link: string; note: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return (
|
||||
<div className="mt-3 border border-brand/20 bg-tint p-3">
|
||||
<p className="text-xs" style={{ color: MUTED }}>
|
||||
{note}
|
||||
</p>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<code className="min-w-0 flex-1 break-all text-xs text-body">{link}</code>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(link);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
setCopied(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{copied ? "Copied" : "Copy link"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminProfiles() {
|
||||
const [data, setData] = useState<{ accounts: Account[]; claims: Claim[]; mail: boolean } | null>(null);
|
||||
const [people, setPeople] = useState<{ id: string; label: string }[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
get("/admin/profiles", { ttl: 0 })
|
||||
.then(setData)
|
||||
.catch((err) => setError(message(err)));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
get("/admin/options?only=people", { ttl: 0 })
|
||||
.then((body) => setPeople(body.options.people))
|
||||
.catch(() => setPeople([]));
|
||||
}, [load]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-baseline gap-3">
|
||||
<h1 className="text-2xl font-bold text-link">Profile accounts</h1>
|
||||
<p className="text-sm" style={{ color: MUTED }}>
|
||||
People with an account on the site for their own profile. By invite only.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Invite mail={Boolean(data?.mail)} onDone={load} />
|
||||
|
||||
{error && <p className="mt-6 text-danger">{error}</p>}
|
||||
|
||||
<section className="mt-8">
|
||||
<h2 className="text-lg font-bold text-ink">Claims waiting</h2>
|
||||
{!data ? null : data.claims.length === 0 ? (
|
||||
<p className="notice mt-3 p-4 text-sm">Nobody is waiting.</p>
|
||||
) : (
|
||||
<ul className="mt-3 space-y-3">
|
||||
{data.claims.map((claim) => (
|
||||
<ClaimRow key={claim.id} claim={claim} onDone={load} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="mt-8">
|
||||
<h2 className="text-lg font-bold text-ink">Accounts</h2>
|
||||
{!data ? (
|
||||
<div className="skeleton mt-3 !min-h-40" aria-label="Loading the accounts" />
|
||||
) : data.accounts.length === 0 ? (
|
||||
<p className="notice mt-3 p-4 text-sm">No profile accounts yet. Invite someone above.</p>
|
||||
) : (
|
||||
<ul className="mt-3 space-y-3">
|
||||
{data.accounts.map((account) => (
|
||||
<AccountRow key={account.id} account={account} people={people} mail={data.mail} onDone={load} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Invite({ mail, onDone }: { mail: boolean; onDone: () => void }) {
|
||||
const emailId = useId();
|
||||
const nameId = useId();
|
||||
const [email, setEmail] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [made, setMade] = useState<{ id: number; email: string; link: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await post("/admin/profiles", { email, name });
|
||||
setMade({ id: result.id, email: email.trim().toLowerCase(), link: result.link });
|
||||
setEmail("");
|
||||
setName("");
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mt-6 bg-raised p-5 shadow-md">
|
||||
<h2 className="text-lg font-bold text-ink">Invite someone</h2>
|
||||
<form onSubmit={submit} className="mt-3 flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-56 flex-1">
|
||||
<label htmlFor={emailId} className="block text-sm font-medium text-body">
|
||||
Email
|
||||
</label>
|
||||
<input id={emailId} type="email" value={email} onChange={(e) => setEmail(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<div className="min-w-48 flex-1">
|
||||
<label htmlFor={nameId} className="block text-sm font-medium text-body">
|
||||
Name <span className="font-normal" style={{ color: MUTED }}>(optional)</span>
|
||||
</label>
|
||||
<input id={nameId} value={name} onChange={(e) => setName(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<button type="submit" disabled={busy || !email.trim()} className={primary}>
|
||||
{busy ? "Inviting…" : "Invite"}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-2 text-xs" style={{ color: MUTED }}>
|
||||
They can sign in with a password from the link, or with Google under this email (any Google account).
|
||||
</p>
|
||||
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
|
||||
{made && (
|
||||
<>
|
||||
<LinkBox
|
||||
link={made.link}
|
||||
note={`${made.email}'s invite link, for 14 days. Shown once: copy it, or email it from the account below.`}
|
||||
/>
|
||||
{mail && <EmailInvite id={made.id} label="Email this invite" onDone={(link) => setMade({ ...made, link })} />}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/* Email a fresh link (the last one stops working). */
|
||||
function EmailInvite({ id, label, onDone }: { id: number; label: string; onDone: (link: string) => void }) {
|
||||
const [state, setState] = useState<"idle" | "busy" | "sent" | string>("idle");
|
||||
return (
|
||||
<div className="mt-3 flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={state === "busy"}
|
||||
onClick={async () => {
|
||||
setState("busy");
|
||||
try {
|
||||
const result = await post(`/admin/profiles/${id}/invite`, { email: true });
|
||||
onDone(result.link);
|
||||
setState("sent");
|
||||
} catch (err) {
|
||||
setState(message(err));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{state === "busy" ? "Sending…" : label}
|
||||
</button>
|
||||
{state === "sent" && <span className="text-sm text-body">Sent. The link above is the one in the email.</span>}
|
||||
{!["idle", "busy", "sent"].includes(state) && <span className="text-sm text-danger">{state}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ClaimRow({ claim, onDone }: { claim: Claim; onDone: () => void }) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function decide(answer: "approve" | "decline") {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await post(`/admin/profiles/claims/${claim.id}/${answer}`, {});
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li className="bg-raised p-4 shadow-sm">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<p className="text-body">
|
||||
<strong>{claim.name || claim.email}</strong>
|
||||
{claim.name && <span style={{ color: MUTED }}> ({claim.email})</span>} asks to be{" "}
|
||||
<a href={`/admin/people/${encodeURIComponent(claim.person_id)}`} className="text-link underline">
|
||||
{claim.person_name}
|
||||
</a>
|
||||
<span className="text-xs" style={{ color: MUTED }}>
|
||||
{" "}
|
||||
· {day(claim.created_at)}
|
||||
</span>
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className={button} disabled={busy} onClick={() => decide("approve")}>
|
||||
Approve
|
||||
</button>
|
||||
<button type="button" className={danger} disabled={busy} onClick={() => decide("decline")}>
|
||||
Decline
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{claim.message && <p className="mt-2 text-sm text-body">“{preview(claim.message, 300)}”</p>}
|
||||
{error && <p className="mt-2 text-sm text-danger">{error}</p>}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function AccountRow({
|
||||
account,
|
||||
people,
|
||||
mail,
|
||||
onDone,
|
||||
}: {
|
||||
account: Account;
|
||||
people: { id: string; label: string }[];
|
||||
mail: boolean;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const personId = useId();
|
||||
const discordId = useId();
|
||||
const discordName = useId();
|
||||
const [person, setPerson] = useState(account.person_id ?? "");
|
||||
const [discord, setDiscord] = useState(account.discord_id ?? "");
|
||||
const [discordLabel, setDiscordLabel] = useState(account.discord_name ?? "");
|
||||
const [link, setLink] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await action();
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const status = !account.is_active
|
||||
? "Turned off"
|
||||
: account.signed_up
|
||||
? `Signed up · last in ${day(account.last_login_at)}`
|
||||
: account.invite_open
|
||||
? `Invited · link works until ${day(account.invite_expires_at)}`
|
||||
: "Invited · link expired";
|
||||
|
||||
return (
|
||||
<li className="bg-raised shadow-sm">
|
||||
<details>
|
||||
<summary className="flex cursor-pointer flex-wrap items-center gap-x-4 gap-y-1 p-4">
|
||||
<span className="font-semibold text-body">{account.name || account.email}</span>
|
||||
{account.name && <span className="text-sm" style={{ color: MUTED }}>{account.email}</span>}
|
||||
<span className="text-sm" style={{ color: MUTED }}>{status}</span>
|
||||
<span className="text-sm text-body">Profile: {account.person_name ?? "-"}</span>
|
||||
<span className="text-sm text-body">Discord: {account.discord_name ?? account.discord_id ?? "-"}</span>
|
||||
</summary>
|
||||
<div className="space-y-5 border-t border-brand/10 p-4">
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-56 flex-1">
|
||||
<label htmlFor={personId} className="block text-sm font-medium text-body">
|
||||
Profile (People record)
|
||||
</label>
|
||||
<select id={personId} value={person} onChange={(e) => setPerson(e.target.value)} className={`mt-1 ${input}`}>
|
||||
<option value="">Default: none</option>
|
||||
{people.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || person === (account.person_id ?? "")}
|
||||
onClick={() => run(() => patch(`/admin/profiles/${account.id}`, { person_id: person || null }))}
|
||||
>
|
||||
Save profile
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-48 flex-1">
|
||||
<label htmlFor={discordId} className="block text-sm font-medium text-body">
|
||||
Discord user ID
|
||||
</label>
|
||||
<input id={discordId} inputMode="numeric" value={discord} onChange={(e) => setDiscord(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<div className="min-w-40 flex-1">
|
||||
<label htmlFor={discordName} className="block text-sm font-medium text-body">
|
||||
Discord name
|
||||
</label>
|
||||
<input id={discordName} value={discordLabel} onChange={(e) => setDiscordLabel(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
run(() => patch(`/admin/profiles/${account.id}`, { discord_id: discord || null, discord_name: discordLabel }))
|
||||
}
|
||||
>
|
||||
Save Discord
|
||||
</button>
|
||||
</div>
|
||||
<p className="-mt-3 text-xs" style={{ color: MUTED }}>
|
||||
They link it themselves from their profile; this overrides it. The ID is the long number from Discord (Developer Mode, then Copy User ID), eg. 80351110224678912. Blank unlinks it.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
run(async () => {
|
||||
const result = await post(`/admin/profiles/${account.id}/invite`, {});
|
||||
setLink(result.link);
|
||||
})
|
||||
}
|
||||
>
|
||||
{account.signed_up ? "New sign-in link" : "New invite link"}
|
||||
</button>
|
||||
{mail && (
|
||||
<EmailInvite id={account.id} label={account.signed_up ? "Email a sign-in link" : "Email invite"} onDone={setLink} />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => run(() => patch(`/admin/profiles/${account.id}`, { is_active: !account.is_active }))}
|
||||
>
|
||||
{account.is_active ? "Turn off" : "Turn on"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={danger}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Remove ${account.email}'s account? Their People record stays.`)) {
|
||||
run(() => del(`/admin/profiles/${account.id}`));
|
||||
}
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
{link && (
|
||||
<LinkBox
|
||||
link={link}
|
||||
note={
|
||||
account.signed_up
|
||||
? "Opening it sets a new password. Any link before it stops working."
|
||||
: "Their invite link, for 14 days. Any link before it stops working."
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
</div>
|
||||
</details>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
|
@ -95,6 +95,12 @@ export const DATA_NAV = {
|
|||
label: "Links/redirects",
|
||||
blurb: "Short /go/ links for the newsletter, with click counts, Plausible and UTM tracking.",
|
||||
},
|
||||
{
|
||||
to: "/admin/profiles",
|
||||
label: "Profile accounts",
|
||||
blurb: "Invite people to make a profile account, approve their claims to a People record, and link their Discord.",
|
||||
minRole: "admin",
|
||||
},
|
||||
{
|
||||
to: "/admin/blog_posts",
|
||||
label: "Blog posts",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue