Compare commits

..

2 commits

Author SHA1 Message Date
Zaldimmar
36c9226bd9 Version v1.9.8-content-display
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:54:33 -05:00
Zaldimmar
80877a4659 Let Google Workspace groups grant admin access
Site settings → Access names a group for each of admin, editor and
viewer (migration 047). Someone in one who signs in with Google gets a
Google-only account with their highest group's role, and the role
follows the groups: at every sign-in, hourly while signed in, and on
Panel → Google groups → Re-sync now. Out of every group, the account
is disabled and signed out until they're back in one.

Group accounts' roles are locked in the Panel; a superadmin's Disable
sticks. Superadmins and admin-cli accounts are never changed. If
Google can't be asked, sign-ins are refused but the hourly check
leaves accounts alone. Panel → Check their groups tests an email.

Lookups use the service account through the Directory API as
GOOGLE_DIRECTORY_AS. Setup: docs/google-sign-in.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:44:04 -05:00
14 changed files with 564 additions and 37 deletions

View file

@ -38,7 +38,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. 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`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.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
- Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`.

View file

@ -82,7 +82,9 @@ For the service account to send as a Workspace user:
1. Google Admin console → Security → Access and data control → API
controls → **Manage domain wide delegation** → Add new.
2. Client ID: the service account's Client ID from step 1.
OAuth scopes: `https://www.googleapis.com/auth/gmail.send`
OAuth scopes: `https://www.googleapis.com/auth/gmail.send` (and,
for access groups, `https://www.googleapis.com/auth/admin.directory.group.member.readonly`,
comma separated: `docs/google-sign-in.md`)
3. `GOOGLE_MAIL_FROM` is the address it sends as. It must be a
**user** in the Workspace, one that signs in and has Gmail: not a
group (eg. `webb-admin@`, even mail-enabled), not an alias. The

View file

@ -6,7 +6,14 @@ off until the service has an OAuth client ID and secret.
## Who gets in
Only accounts that already exist. Create them as before with
Two 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.
Created with
`admin-cli.js add <email>` (the password it asks for stays as a way in
if Google is ever unavailable). The first time that person signs in with
Google, their Google account is linked to the admin account with the
@ -14,12 +21,79 @@ same email; after that it matches by the link, even if the email later
changes. `admin-cli.js list` shows which accounts are linked.
Refused, with a message on the login page: no admin account for that
email, an email already linked to a different Google account, a
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.
Code: `server/src/googleAuth.js` (the Google side) and
`server/src/routes/auth.js` (matching and linking accounts).
Code: `server/src/googleAuth.js` (the Google side),
`server/src/routes/auth.js` (matching and linking accounts) and
`server/src/accessGroups.js` (access groups).
## Access groups
Panel → Site settings → **Access (Google groups)** names a Workspace
group for each of Admin, Editor and Viewer, eg.
`web-admins@nextgenerationofunity.org`. Any of them may be blank.
- **First sign-in:** someone in one of the groups signs in with Google
and gets an account with the highest role their groups give (in both
the editors and viewers groups: editor). No password: Google only.
Groups inside groups count.
- **The role follows the group**, checked at every sign-in, about once
an hour while they're signed in, and whenever a superadmin presses
Panel → Google groups → **Re-sync now**. Moved to another group: the
role changes. Out of every group: the account is disabled and signed
out; put back in one, it's turned on again at the next sign-in or
re-sync.
- **In the Panel**, a group account says "Google group" and its role
can't be changed there (change the membership instead). Disable still
works, and sticks: no group check turns back on an account a
superadmin disabled.
- **Not affected:** superadmins (there's no superadmin group) and
accounts made with admin-cli, which keep the role set in the Panel
whatever groups they're in.
- **If Google can't be asked** (an outage, a setup mistake), a sign-in
is refused ("Couldn't check your Google groups"), but the hourly
check leaves accounts as they are and tries again; nobody is signed
out because Google was down. Password and admin-cli accounts still
get in.
Panel → Google groups → **Check their groups** shows what role an email
would get, changing nothing: the quickest check of the setup.
### Setting it up
Group lookups use the service account from
`docs/google-drive-and-mail.md` (step 1 there), through the Admin SDK
Directory API:
1. Cloud Console, the service account's project → APIs & Services →
Library → enable the **Admin SDK API**.
2. Admin console → Security → Access and data control → API controls →
Manage domain wide delegation → the service account's entry → Edit.
Add the scope (comma separated, beside `gmail.send`):
`https://www.googleapis.com/auth/admin.directory.group.member.readonly`
3. Pick a Workspace **user** who can see the groups' members: a super
admin, or an admin with a role that includes Groups → Read. The
lookups are made as them. Set it on the service:
```ini
Environment=GOOGLE_DIRECTORY_AS=<that user, eg. it-admin@nextgenerationofunity.org>
```
4. Make the groups in Google Admin (or Groups), add people, and put the
addresses in Site settings → Access. Restart `ngu-api` after the
`systemctl edit`.
`GOOGLE_SERVICE_ACCOUNT` and `GOOGLE_DIRECTORY_AS` without any groups
set changes nothing; groups set without them show a warning in the
Panel and Google sign-in works as before.
Errors in the Panel or journal (`grep access`): `groupKey` means a group
address in Site settings isn't a group Google knows; `unauthorized_client`
means the delegation or scope (step 2) is missing, or
`GOOGLE_DIRECTORY_AS` isn't a user; `Not Authorized to access this
resource` means that user can't read the group.
## Setting up the OAuth client

132
server/src/accessGroups.js Normal file
View file

@ -0,0 +1,132 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN ACCESS BY GOOGLE GROUP
Panel → Site settings → Access names a Workspace group for each of
viewer, editor and admin. Someone in one of them who signs in with
Google gets an account (access_source 'group', no password) with
the highest of those roles; routes/auth.js calls groupRole() and
applyGroupRole() at every Google sign-in.
The role then follows the group:
at sign-in always checked
while signed in startGroupSync() rechecks accounts with a
live session every SYNC_EVERY_MS, once
their last check is STALE_AFTER_MS old
Panel → Re-sync now every group account, straight away
Out of every group: the account is disabled (group_disabled = 1)
and signed out; back in one, the next sign-in or sync turns it on
again. A superadmin's Disable in the Panel sets group_disabled = 0,
which no group check undoes.
Never touched: superadmins and 'manual' accounts (admin-cli, which
may also sign in with Google as before).
If Google can't be asked, a sign-in is refused (it can't be shown
to be allowed), but a background recheck leaves the account as it
is and tries again next time: an outage shouldn't sign everyone out.
Needs GOOGLE_DIRECTORY_AS (googleService.js) and at least one group.
Setup: docs/google-sign-in.md.
═══════════════════════════════════════════════════════════════ */
import { directoryReady, isGroupMember } from "./googleService.js";
const SYNC_EVERY_MS = 10 * 60 * 1000;
const STALE_AFTER_MS = 30 * 60 * 1000;
// Highest first: the first group someone is in gives their role.
const GROUP_ROLES = ["admin", "editor", "viewer"];
/* [[role, group address], ...], highest role first, set ones only. */
export function accessGroups(db) {
const row =
db
.prepare(
`SELECT access_group_viewer, access_group_editor, access_group_admin
FROM site_settings WHERE id = 'site'`,
)
.get() ?? {};
return GROUP_ROLES.map((role) => [role, String(row[`access_group_${role}`] ?? "").trim().toLowerCase()]).filter(
([, group]) => group,
);
}
export const accessEnabled = (db) => directoryReady() && accessGroups(db).length > 0;
/* The role someone's groups give them, or null for none. Throws a
GoogleError when Google can't say. */
export async function groupRole(db, email) {
for (const [role, group] of accessGroups(db)) {
if (await isGroupMember(group, email)) return role;
}
return null;
}
/* Brings a group account in line with `role` (null: in no group).
Returns what changed, as text for the log and the Panel, or null. */
export function applyGroupRole(db, user, role) {
let change = null;
if (!role) {
if (user.is_active === 1) {
db.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ?`).run(user.id);
db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id);
change = "disabled: in no access group";
}
} else if (user.is_active !== 1 || user.role !== role) {
db.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ?`).run(role, user.id);
change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`;
}
db.prepare(`UPDATE admin_users SET groups_checked_at = datetime('now') WHERE id = ?`).run(user.id);
if (change) console.log(`access: ${user.email} ${change}`);
return change;
}
/* Rechecks group accounts: all of them (Panel → Re-sync now), or only
those signed in whose last check is stale (the timer). Accounts a
superadmin disabled are left alone. */
export async function syncGroupAccounts(db, { all = false } = {}) {
const users = db
.prepare(
`SELECT u.id, u.email, u.role, u.is_active FROM admin_users u
WHERE u.access_source = 'group' AND u.role <> 'superadmin'
AND (u.is_active = 1 OR u.group_disabled = 1)
${
all
? ""
: `AND u.is_active = 1
AND EXISTS (SELECT 1 FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now'))
AND (u.groups_checked_at IS NULL OR u.groups_checked_at <= datetime('now', ?))`
}`,
)
.all(...(all ? [] : [`-${STALE_AFTER_MS / 1000} seconds`]));
const result = { checked: 0, changes: [], failed: [] };
for (const user of users) {
try {
const change = applyGroupRole(db, user, await groupRole(db, user.email));
result.checked++;
if (change) result.changes.push(`${user.email}: ${change}`);
} catch (err) {
console.warn(`access: couldn't check ${user.email}: ${err.message}`);
result.failed.push(`${user.email}: ${err.message}`);
}
}
return result;
}
export function startGroupSync(db) {
let running = false;
const tick = async () => {
if (running || !accessEnabled(db)) return;
running = true;
try {
await syncGroupAccounts(db);
} catch (err) {
console.error("access sync failed", err);
} finally {
running = false;
}
};
setInterval(tick, SYNC_EVERY_MS).unref();
}

View file

@ -31,6 +31,9 @@ export const siteSettings = {
enumeration("indexing", ["on", "off"]),
text("privacy_email"),
text("notify_emails"),
text("access_group_viewer"),
text("access_group_editor"),
text("access_group_admin"),
],
children: [

View file

@ -4,7 +4,7 @@
The server acting as itself (not a person signing in, that's
googleAuth.js). A service account's key signs a short JWT, which
Google swaps for an access token (RS256 with node:crypto, no
library). Two uses:
library). Three uses:
Drive one shared drive (a service account has no storage of
its own), with a folder per use: "Requests" for files sent
@ -13,6 +13,9 @@
"Blog/2026" makes each level.
Gmail new-request notices, sent as a Workspace user through
domain-wide delegation.
Groups who is in the admin access groups (accessGroups.js), read
through the Directory API as a Workspace admin, the same
delegation.
Configured by the service environment:
@ -21,6 +24,8 @@
GOOGLE_SHARED_DRIVE the shared drive's id: only the last part
of its address, not the whole URL
GOOGLE_MAIL_FROM the Workspace address notices come from
GOOGLE_DIRECTORY_AS a Workspace admin (a user) whose view of
groups is read
Each part is off until its settings are there: without a shared drive
the form offers no uploads, and without a sender no mail goes out.
@ -32,6 +37,7 @@ import { createSign } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
const GROUPS_SCOPE = "https://www.googleapis.com/auth/admin.directory.group.member.readonly";
const DRIVE = "https://www.googleapis.com/drive/v3/files";
const DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
@ -51,6 +57,7 @@ function serviceKey() {
export const driveReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_SHARED_DRIVE);
export const mailReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_MAIL_FROM);
export const directoryReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_DIRECTORY_AS);
/* ── Access tokens, kept until a minute before they run out ──── */
@ -220,3 +227,23 @@ export async function sendMail({ to, subject, text, replyTo }) {
from,
);
}
/* ── Groups ──────────────────────────────────────────────────── */
/* Whether someone is in a group, directly or through a group inside
it (the Directory API's hasMember follows nesting in the domain). */
export async function isGroupMember(group, email) {
const url =
"https://admin.googleapis.com/admin/directory/v1/groups/" +
`${encodeURIComponent(group)}/hasMember/${encodeURIComponent(email)}`;
try {
const res = await call(url, {}, GROUPS_SCOPE, process.env.GOOGLE_DIRECTORY_AS);
return (await res.json()).isMember === true;
} catch (err) {
// An address Google doesn't know ("Invalid Input: memberKey",
// "Resource Not Found: memberKey") is in no group of ours. A group
// it doesn't know (groupKey) is a setup mistake, and throws.
if (/^40[04] .*memberKey/i.test(err.message)) return false;
throw new GoogleError(`${group}: ${err.message}`);
}
}

View file

@ -40,6 +40,7 @@ import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { ENTITIES } from "./admin-schema.js";
const HOST = process.env.HOST ?? "127.0.0.1";
@ -213,6 +214,7 @@ app.use(
app.route("/", pages);
startSessionSweeper(db);
startGroupSync(db);
startClipWorker(db);
console.log(`clips ${CLIPS_DIR}`);

View file

@ -0,0 +1,29 @@
-- ═══════════════════════════════════════════════════════════════
-- 047 ACCESS BY GOOGLE GROUP
--
-- Admin access from Google Workspace groups (accessGroups.js).
-- Panel → Site settings → Access names a group for each of viewer,
-- editor and admin. Someone in one of them who signs in with Google
-- gets an account with the highest of those roles, and keeps it only
-- while they're in the group. Superadmins and admin-cli accounts are
-- never touched.
--
-- admin_users.access_source 'manual' (admin-cli, the Panel) or
-- 'group' (made by a group sign-in;
-- Google only, role follows the group)
-- admin_users.group_disabled 1 when a group check turned it off
-- (back in a group turns it on again);
-- a superadmin's Disable sets 0, and
-- that one sticks
-- admin_users.groups_checked_at the last group check, UTC
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE admin_users ADD COLUMN access_source TEXT NOT NULL DEFAULT 'manual'
CHECK (access_source IN ('manual', 'group'));
ALTER TABLE admin_users ADD COLUMN group_disabled INTEGER NOT NULL DEFAULT 0
CHECK (group_disabled IN (0, 1));
ALTER TABLE admin_users ADD COLUMN groups_checked_at TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_viewer TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_editor TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_admin TEXT;

View file

@ -19,12 +19,14 @@
A failed login still runs a hash. Otherwise the response time
itself says whether the account exists.
Nothing here creates accounts. See admin-cli.js. Google sign-in
only lets in an account that already exists: matched by its
linked Google id, or on first use by its 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.
Accounts come from admin-cli.js, with one exception: with access
groups set up (accessGroups.js), a Google sign-in by someone in
one makes a group account, whose role then follows the group.
Otherwise Google sign-in only lets in an account that already
exists: matched by its linked Google id, or on first use by its
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.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
@ -41,6 +43,7 @@ import {
verifyPassword,
} from "../auth.js";
import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js";
import { accessEnabled, applyGroupRole, groupRole } from "../accessGroups.js";
import { failureLimit } from "../rateLimit.js";
import { NO_STORE } from "../shape.js";
@ -208,25 +211,66 @@ auth.get("/google/callback", async (c) => {
}
const db = c.get("db");
const columns = `id, email, name, role, is_active, google_sub`;
const columns = `id, email, name, role, is_active, google_sub, access_source, group_disabled`;
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);
// 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.
const roleFromGroups = async () => {
try {
return { role: await groupRole(db, identity.email) };
} catch (err) {
console.warn(`google login: groups unreadable for ${identity.email}: ${err.message}`);
return { failed: true };
}
};
if (!user) {
const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
if (!byEmail) {
if (!accessEnabled(db)) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
}
if (byEmail.google_sub) {
// 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.role) {
console.warn(`google login: ${identity.email} is in no access group`);
return backToLogin(c, "not_in_group");
}
const id = db
.prepare(
`INSERT INTO admin_users (email, name, role, google_sub, access_source, groups_checked_at)
VALUES (?, ?, ?, ?, 'group', datetime('now'))`,
)
.run(identity.email, identity.name, found.role, identity.sub).lastInsertRowid;
console.log(`account ${identity.email} made from access group (${found.role})`);
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");
}
} else {
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "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;
}
}
// A group account's role follows its groups, checked every time.
// One a superadmin disabled stays disabled whatever its groups say.
if (user.access_source === "group" && user.role !== "superadmin" && accessEnabled(db)) {
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
applyGroupRole(db, user, found.role);
if (!found.role) return backToLogin(c, "not_in_group");
user = byId(user.id);
}
if (user.is_active !== 1) return backToLogin(c, "disabled");

View file

@ -5,6 +5,8 @@
PATCH /api/admin/panel/users/:id role, is_active
DELETE /api/admin/panel/users/:id/sessions sign out everywhere
POST /api/admin/panel/test-notice { to }: a test email
POST /api/admin/panel/access-sync recheck every group account
POST /api/admin/panel/access-check { email }: what their groups give
Everything here is superadmin-only, enforced once at the top
rather than per route; there's no read here that an ordinary
@ -28,8 +30,9 @@ import { Hono } from "hono";
import { requireAuth, requireRole, ROLES } from "../auth.js";
import { tx } from "../db.js";
import { NO_STORE } from "../shape.js";
import { mailReady, sendMail } from "../googleService.js";
import { directoryReady, mailReady, sendMail } from "../googleService.js";
import { addresses } from "../notify.js";
import { accessEnabled, accessGroups, groupRole, syncGroupAccounts } from "../accessGroups.js";
const panel = new Hono();
@ -57,7 +60,8 @@ panel.get("/overview", (c) => {
const users = db
.prepare(
`SELECT u.id, u.email, u.name, u.role, u.is_active,
u.created_at, u.last_login_at,
u.created_at, u.last_login_at, u.access_source, u.group_disabled,
u.groups_checked_at,
(SELECT COUNT(*) FROM sessions s
WHERE s.user_id = u.id
AND s.expires_at > datetime('now')) AS sessions
@ -85,6 +89,12 @@ panel.get("/overview", (c) => {
},
content,
users,
// Google groups (accessGroups.js): which are set, and whether the
// server can read them.
access: {
directory: directoryReady(),
groups: Object.fromEntries(accessGroups(db)),
},
},
200,
NO_STORE,
@ -127,10 +137,17 @@ panel.patch("/users/:id", async (c) => {
}
const target = db
.prepare("SELECT id, email, role, is_active FROM admin_users WHERE id = ?")
.prepare("SELECT id, email, role, is_active, access_source FROM admin_users WHERE id = ?")
.get(id);
if (!target) return c.json({ error: "No such account." }, 404);
if (target.access_source === "group" && body.role !== undefined && body.role !== target.role) {
return c.json(
{ error: "This account's role comes from its Google group. Change the group membership instead." },
409,
);
}
const sets = [];
const params = [];
@ -155,6 +172,8 @@ panel.patch("/users/:id", async (c) => {
if (body.is_active !== undefined) {
sets.push("is_active = ?");
params.push(Number(body.is_active) ? 1 : 0);
// A superadmin's choice: no group check undoes it (accessGroups.js).
sets.push("group_disabled = 0");
}
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
@ -208,7 +227,8 @@ function userRow(db, id) {
return db
.prepare(
`SELECT u.id, u.email, u.name, u.role, u.is_active,
u.created_at, u.last_login_at,
u.created_at, u.last_login_at, u.access_source, u.group_disabled,
u.groups_checked_at,
(SELECT COUNT(*) FROM sessions s
WHERE s.user_id = u.id
AND s.expires_at > datetime('now')) AS sessions
@ -255,4 +275,46 @@ panel.post("/test-notice", async (c) => {
return c.json({ sent: to, from }, 200, NO_STORE);
});
/* ── Access by Google group ──────────────────────────────────────
access-sync every group account against its groups now (the
timer only rechecks signed-in ones, hourly)
access-check what someone's groups would give them, changing
nothing: for checking the setup
───────────────────────────────────────────────────────────── */
const accessOff = (c, db) =>
accessEnabled(db)
? null
: c.json(
{
error: directoryReady()
? "No access groups set: Panel → Site settings → Access."
: "Group lookups aren't set up on the server: GOOGLE_SERVICE_ACCOUNT and GOOGLE_DIRECTORY_AS (docs/google-sign-in.md).",
},
400,
);
panel.post("/access-sync", async (c) => {
const db = c.get("db");
const off = accessOff(c, db);
if (off) return off;
const result = await syncGroupAccounts(db, { all: true });
console.log(`access re-sync by ${c.get("user").email}: ${result.checked} checked, ${result.changes.length} changed, ${result.failed.length} failed`);
return c.json(result, 200, NO_STORE);
});
panel.post("/access-check", async (c) => {
const db = c.get("db");
const off = accessOff(c, db);
if (off) return off;
const body = (await c.req.json().catch(() => null)) ?? {};
const email = String(body.email ?? "").trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return c.json({ error: "Enter an email address." }, 422);
try {
return c.json({ email, role: await groupRole(db, email) }, 200, NO_STORE);
} catch (err) {
return c.json({ error: `Google couldn't say: ${err.message}` }, 502);
}
});
export default panel;

View file

@ -122,6 +122,27 @@ export const siteSettings = {
},
],
},
{
legend: "Access (Google groups)",
note: "Anyone in one of these Workspace groups can sign in to the admin with Google; their account is made at first sign-in, with the highest role their groups give. Their role follows the groups (checked at sign-in, hourly, and by Panel → Re-sync now); out of every group, the account is disabled. Superadmins and accounts made with admin-cli aren't affected. Needs GOOGLE_DIRECTORY_AS on the server (docs/google-sign-in.md).",
fields: [
{
path: "access_group_admin",
label: "Admins group",
help: "Its members sign in as admins: edit and delete anything. eg. web-admins@nextgenerationofunity.org. Default: none.",
},
{
path: "access_group_editor",
label: "Editors group",
help: "Its members sign in as editors: create and edit, not delete. eg. web-editors@nextgenerationofunity.org. Default: none.",
},
{
path: "access_group_viewer",
label: "Viewers group",
help: "Its members sign in as viewers: read only. eg. web-viewers@nextgenerationofunity.org. Default: none.",
},
],
},
{
legend: "Notices",
fields: [

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.9.7-content-display";
export const SITE_VERSION = "NGU-Web.v1.9.8-content-display";

View file

@ -33,6 +33,9 @@ const GOOGLE_ERRORS: Record<string, string> = {
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. Ask a superadmin to add you to one.",
groups_unreachable: "Couldn't check your Google groups just now. Try again in a moment.",
};
const fieldClass =

View file

@ -6,11 +6,16 @@
assumes neither: it renders whatever the API gives it and shows
whatever the API refuses.
Three blocks, deliberately boring:
Four blocks, deliberately boring:
System what's actually running, for when something is off
Content row counts, the cheapest "is the database there"
Accounts roles, access and live sessions
Google groups check someone's groups, re-sync every group
account (server/src/accessGroups.js)
A group account's role comes from its Google group, so its role
select is locked; Disable still works, and sticks.
The role select is driven by ROLES from lib/roles.ts, so a new
rung on the ladder appears here without this file changing. The
@ -25,7 +30,7 @@
═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useState } from "react";
import { del, get, patch } from "../../lib/api.ts";
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { useNavigate } from "react-router-dom";
import { ROLES, ROLE_LABELS, ROLE_NOTES, isSuper } from "../../lib/roles.ts";
@ -73,6 +78,107 @@ function Stat({ label, value }) {
);
}
/* Google groups: what's set, who a group would let in, and a
re-sync of every group account. */
function AccessGroups({ access, onSynced }) {
const [email, setEmail] = useState("");
const [busy, setBusy] = useState<"check" | "sync" | null>(null);
const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
const [changes, setChanges] = useState<string[]>([]);
const groups = Object.entries(access?.groups ?? {});
async function send(kind: "check" | "sync") {
setBusy(kind);
setNote(null);
setChanges([]);
try {
if (kind === "check") {
const { role } = await post("/admin/panel/access-check", { email });
setNote(
role
? { tone: "ok", text: `${email} would sign in as ${ROLE_LABELS[role] ?? role}.` }
: { tone: "error", text: `${email} isn't in any of these groups.` },
);
} else {
const result = await post("/admin/panel/access-sync", {});
setNote({
tone: result.failed.length ? "error" : "ok",
text:
`Checked ${result.checked} group account${result.checked === 1 ? "" : "s"}, ` +
`${result.changes.length} changed` +
(result.failed.length ? `, ${result.failed.length} couldn't be checked.` : "."),
});
setChanges([...result.changes, ...result.failed]);
onSynced();
}
} catch (err) {
setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." });
} finally {
setBusy(null);
}
}
const button =
"rounded-full border border-brand px-4 py-1.5 text-sm font-medium text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
return (
<Block
title="Google groups"
note="Members of these groups sign in with Google and get the group's role. Set them in Site settings → Access."
>
{!access?.directory && (
<p className="mb-3 text-sm text-danger">
Group lookups aren't set up on the server (GOOGLE_DIRECTORY_AS, docs/google-sign-in.md).
</p>
)}
{groups.length > 0 ? (
<dl className="mb-4 grid gap-x-6 gap-y-1.5 text-sm sm:grid-cols-3">
{groups.map(([role, group]) => (
<div key={role}>
<dt className="font-medium text-ink">{ROLE_LABELS[role] ?? role}</dt>
<dd className="break-all text-muted">{group as string}</dd>
</div>
))}
</dl>
) : (
<p className="mb-4 text-sm text-muted">No groups set: accounts come from admin-cli only.</p>
)}
<div className="flex flex-wrap items-center gap-3">
<label htmlFor="access-check" className="sr-only">
Email to check
</label>
<input
id="access-check"
type="email"
value={email}
placeholder="someone@nextgenerationofunity.org"
onChange={(e) => setEmail(e.target.value)}
className="min-w-0 flex-1 rounded-lg border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25 sm:max-w-sm"
/>
<button type="button" className={button} disabled={busy !== null || !email.trim()} onClick={() => send("check")}>
{busy === "check" ? "Checking…" : "Check their groups"}
</button>
<button type="button" className={button} disabled={busy !== null} onClick={() => send("sync")}>
{busy === "sync" ? "Re-syncing…" : "Re-sync now"}
</button>
</div>
{note && (
<p role="status" className={`mt-3 text-sm ${note.tone === "ok" ? "text-link" : "text-danger"}`}>
{note.text}
</p>
)}
{changes.length > 0 && (
<ul className="mt-2 space-y-1 text-xs text-muted">
{changes.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
)}
</Block>
);
}
export default function AdminPanel() {
const { user: me } = useAuth();
const navigate = useNavigate();
@ -103,6 +209,16 @@ export default function AdminPanel() {
load();
}, [load]);
// After a re-sync: the accounts table again, without the loading
// screen (which would clear the sync's result).
const refresh = async () => {
try {
setData(await get("/admin/panel/overview", { ttl: 0 }));
} catch {
// The table stays as it was; the next load shows any error.
}
};
/* Replace the one row the server returns rather than refetching
the whole overview; the counts didn't change. */
function mergeUser(updated) {
@ -164,7 +280,7 @@ export default function AdminPanel() {
);
}
const { system, content, users } = data;
const { system, content, users, access } = data;
const activeSupers = users.filter(
(u) => isSuper(u) && u.is_active === 1,
).length;
@ -227,6 +343,7 @@ export default function AdminPanel() {
const lastSuper =
isSuper(row) && row.is_active === 1 && activeSupers <= 1;
const locked = isMe || lastSuper;
const fromGroup = row.access_source === "group";
const busy = busyId === row.id;
return (
@ -243,6 +360,12 @@ export default function AdminPanel() {
{row.name && (
<div className="text-xs text-muted/80">{row.email}</div>
)}
{fromGroup && (
<div className="mt-1 text-xs text-muted">
Google group
{row.group_disabled === 1 && ": in no access group"}
</div>
)}
{rowError?.id === row.id && (
<div className="mt-1 text-xs text-danger">
{rowError.message}
@ -253,11 +376,13 @@ export default function AdminPanel() {
<td className="px-4 py-3">
<select
value={row.role}
disabled={locked || busy}
disabled={locked || busy || fromGroup}
onChange={(e) => changeRole(row, e.target.value)}
className="rounded-lg border border-brand/30 bg-surface px-2 py-1 text-sm text-ink disabled:cursor-not-allowed disabled:bg-tint-soft disabled:text-muted/60"
title={
isMe
fromGroup
? "The role comes from this person's Google group."
: isMe
? "You can't change your own role."
: lastSuper
? "The last active superadmin can't be demoted."
@ -323,9 +448,12 @@ export default function AdminPanel() {
</dl>
<p className="mt-4 text-xs text-muted/80">
New accounts are still created with <code>admin-cli.js</code> on the server.
New accounts are created with <code>admin-cli.js</code> on the server, or by signing in
with Google while in one of the groups below.
</p>
</Block>
<AccessGroups access={access} onSynced={refresh} />
</div>
);
}