Feature fixes: admin nav, hero event, schedule block, SEO, site settings, Google sign-in, QR tool #12

Merged
ngu-git-admin merged 14 commits from feature-fixes into main 2026-09-28 08:12:29 +01:00
8 changed files with 392 additions and 28 deletions
Showing only changes of commit d4b39251d9 - Show all commits

View file

@ -33,6 +33,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Never run commands against the production server or database unless explicitly asked.
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html). nginx setup: `docs/seo.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`.
## Git workflow
- Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`.

67
docs/google-sign-in.md Normal file
View file

@ -0,0 +1,67 @@
# Google sign-in
The admin login offers "Sign in with Google" for
@nextgenerationofunity.org accounts, alongside email and password. It's
off until the service has an OAuth client ID and secret.
## Who gets in
Only accounts that already exist. Create them as before 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
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
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).
## Setting up the OAuth client
In [Google Cloud Console](https://console.cloud.google.com/), signed in
as a Workspace admin for nextgenerationofunity.org:
1. **Create or pick a project**, eg. "NGU Website".
2. **APIs & Services → OAuth consent screen** (Google Auth Platform →
Branding / Audience):
- User type / audience: **Internal**. Only accounts in the Workspace
can use it, and Google doesn't need to review the app.
- App name: NGU Admin. Support email: yours.
- Scopes: `openid`, `email`, `profile` (nothing else is needed).
3. **APIs & Services → Credentials → Create credentials → OAuth client
ID** (Google Auth Platform → Clients):
- Application type: **Web application**. Name: NGU admin.
- Authorized redirect URIs:
- `https://nextgenerationofunity.org/api/auth/google/callback`
- for local work, also the dev address, eg.
`http://localhost:5174/api/auth/google/callback`
- No JavaScript origins are needed: the browser never talks to Google
directly.
4. Copy the **Client ID** and **Client secret**.
## Turning it on
On the server, add them to the `ngu-api` unit (`systemctl edit ngu-api`)
and restart. Never commit the secret or paste it into the repo:
```ini
[Service]
Environment=GOOGLE_CLIENT_ID=<client id>
Environment=GOOGLE_CLIENT_SECRET=<client secret>
```
Optional:
| Variable | Default |
| --- | --- |
| `GOOGLE_REDIRECT_URI` | `<site.json url>/api/auth/google/callback`. Set it for local work, eg. `http://localhost:5174/api/auth/google/callback`, and add the same URI in step 3. |
| `GOOGLE_ALLOWED_DOMAIN` | `nextgenerationofunity.org` |
The login page asks `/api/auth/providers` whether Google is set up, so
the button appears as soon as the service restarts with both values.
Locally, also set `COOKIE_SECURE=false` when working over plain http.

View file

@ -209,6 +209,7 @@ function list(db) {
const rows = db
.prepare(
`SELECT u.email, u.name, u.role, u.is_active, u.last_login_at,
u.google_sub IS NOT NULL AS google,
(SELECT COUNT(*) FROM sessions s
WHERE s.user_id = u.id AND s.expires_at > datetime('now')) AS sessions
FROM admin_users u
@ -228,7 +229,8 @@ function list(db) {
const state = r.is_active ? r.role : `${r.role} (disabled)`;
const seen = r.last_login_at ?? "never";
console.log(
`${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)`,
`${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)` +
(r.google ? " google linked" : ""),
);
}
}

View file

@ -31,7 +31,7 @@ const SESSION_DAYS = 30;
const REFRESH_WITHIN_DAYS = 7;
// Off only for plain-http local work. Production is behind TLS.
const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false";
export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false";
const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex");

143
server/src/googleAuth.js Normal file
View file

@ -0,0 +1,143 @@
/* ═══════════════════════════════════════════════════════════════
GOOGLE SIGN-IN
The OAuth 2.0 authorization-code flow with PKCE, done on the
server, for @nextgenerationofunity.org accounts. The routes are
in routes/auth.js; this is the part that talks to Google and
decides whether an answer is good enough.
Configured by the service environment:
GOOGLE_CLIENT_ID from Google Cloud Console
GOOGLE_CLIENT_SECRET the same; never in the repo
GOOGLE_REDIRECT_URI default <site.json url>/api/auth/google/callback
GOOGLE_ALLOWED_DOMAIN default nextgenerationofunity.org
With no client id or secret it's off: the login page doesn't
offer it and the routes answer 404. Setup: docs/google-sign-in.md.
── Why the ID token isn't signature-checked ──
The token comes straight from Google's token endpoint, over TLS,
in answer to a request this server made with its own secret.
Google's documentation says a token received that way can be
trusted without verifying its signature. Everything else is
checked: issuer, audience (our client id), expiry, a verified
email, and the Workspace domain in the `hd` claim, which only
Google sets, not just the email's suffix.
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.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
import { loadSite } from "./pageMeta.js";
const AUTHORIZE = "https://accounts.google.com/o/oauth2/v2/auth";
const TOKEN = "https://oauth2.googleapis.com/token";
const ISSUERS = new Set(["accounts.google.com", "https://accounts.google.com"]);
const base64url = (buf) => buf.toString("base64url");
export function googleConfig() {
const clientId = process.env.GOOGLE_CLIENT_ID;
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
if (!clientId || !clientSecret) return null;
let redirectUri = process.env.GOOGLE_REDIRECT_URI;
if (!redirectUri) {
const origin = (loadSite().url ?? "").replace(/\/$/, "");
redirectUri = `${origin}/api/auth/google/callback`;
}
return {
clientId,
clientSecret,
redirectUri,
domain: (process.env.GOOGLE_ALLOWED_DOMAIN ?? "nextgenerationofunity.org").toLowerCase(),
};
}
/* 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) {
const state = base64url(randomBytes(24));
const verifier = base64url(randomBytes(48));
const challenge = base64url(createHash("sha256").update(verifier).digest());
const url = new URL(AUTHORIZE);
url.search = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
scope: "openid email profile",
state,
code_challenge: challenge,
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,
prompt: "select_account",
});
return { url: url.toString(), state, verifier };
}
export class GoogleLoginError extends Error {
constructor(code, message) {
super(message);
this.code = code; // shown to the login page as ?error=<code>
}
}
/* The second leg: trade the code for tokens and check the identity.
Returns { sub, email, name } or throws GoogleLoginError. */
export async function finishLogin(config, code, verifier) {
let res;
try {
res = await fetch(TOKEN, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
code,
client_id: config.clientId,
client_secret: config.clientSecret,
redirect_uri: config.redirectUri,
grant_type: "authorization_code",
code_verifier: verifier,
}),
signal: AbortSignal.timeout(10_000),
});
} catch {
throw new GoogleLoginError("google_unreachable", "Couldn't reach Google.");
}
const body = await res.json().catch(() => ({}));
if (!res.ok || !body.id_token) {
console.warn(`google token exchange failed: ${res.status} ${body.error ?? ""}`);
throw new GoogleLoginError("google_failed", "Google didn't accept the sign-in.");
}
let claims;
try {
claims = JSON.parse(Buffer.from(body.id_token.split(".")[1], "base64url").toString("utf8"));
} catch {
throw new GoogleLoginError("google_failed", "Google's answer couldn't be read.");
}
const now = Math.floor(Date.now() / 1000);
if (!ISSUERS.has(claims.iss) || claims.aud !== config.clientId || !(claims.exp > now)) {
throw new GoogleLoginError("google_failed", "Google's answer didn't check out.");
}
const email = String(claims.email ?? "").toLowerCase();
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.`);
}
return { sub: String(claims.sub), email, name: claims.name ?? null };
}

View file

@ -76,6 +76,9 @@ app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
app.route("/api/feedback", feedback);
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 }));
app.route("/api/admin/panel", panel);
app.route("/api/auth", auth);
app.route("/api/admin", admin);

View file

@ -4,6 +4,10 @@
POST /api/auth/login email + password → session cookie
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/callback back from it: sign in, or
back to the login page with ?error=
Three deliberate choices:
@ -14,18 +18,27 @@
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.
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.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import {
SECURE_COOKIE,
createSession,
destroySession,
currentUser,
hashPassword,
verifyPassword,
} from "../auth.js";
import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js";
const auth = new Hono();
@ -96,4 +109,103 @@ auth.get("/me", (c) => {
return c.json({ user }, 200, NO_STORE);
});
/* ── Google ──────────────────────────────────────────────────── */
// The state and PKCE verifier between the two legs. Scoped to the
// Google routes and gone in ten minutes; Lax so it comes back on
// the redirect from Google, which is a top-level navigation.
const OAUTH_COOKIE = "ngu_oauth";
const OAUTH_COOKIE_OPTIONS = {
httpOnly: true,
secure: SECURE_COOKIE,
sameSite: "Lax",
path: "/api/auth/google",
};
// Where to land afterwards: an admin page, never anywhere else.
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);
auth.get("/providers", (c) =>
c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE),
);
auth.get("/google", (c) => {
const config = googleConfig();
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
const { url, state, verifier } = startLogin(config);
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), {
...OAUTH_COOKIE_OPTIONS,
maxAge: 600,
});
return c.redirect(url, 302);
});
auth.get("/google/callback", async (c) => {
const config = googleConfig();
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
let saved = null;
try {
saved = JSON.parse(getCookie(c, OAUTH_COOKIE) ?? "null");
} catch {
saved = null;
}
deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS);
// Pressing Cancel on Google's screen comes back as ?error=.
if (c.req.query("error")) return backToLogin(c, "cancelled");
const code = c.req.query("code");
if (!saved?.state || !code || c.req.query("state") !== saved.state) {
return backToLogin(c, "expired");
}
let identity;
try {
identity = await finishLogin(config, code, saved.verifier);
} catch (err) {
if (err instanceof GoogleLoginError) {
console.warn(`google login refused: ${err.code}`);
return backToLogin(c, err.code);
}
throw err;
}
const db = c.get("db");
const columns = `id, email, name, role, is_active, google_sub`;
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
if (!user) {
const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
if (!byEmail) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
}
if (byEmail.google_sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return backToLogin(c, "linked_elsewhere");
}
// 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;
}
if (user.is_active !== 1) return backToLogin(c, "disabled");
createSession(db, c, user.id);
db.prepare(
`UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`,
).run(identity.name, user.id);
console.log(`login ${user.email} (google)`);
return c.redirect(saved.next ?? "/admin/home", 302);
});
export default auth;

View file

@ -5,18 +5,35 @@
page of the website; it's the door to the back office, and it
shouldn't carry a banner, a subnav, or a footer site map.
The Google button is stubbed and disabled until the OAuth
routes exist. It's here so the layout doesn't change when it
starts working.
Google first, when the server has it set up (/auth/providers
says so; it's off until GOOGLE_CLIENT_ID and _SECRET are on the
service). It's a plain link: the server sends the browser to
Google and back, and a refusal comes back here as ?error=<code>,
worded below. Email and password stay underneath as the way in
if Google is ever unavailable.
═══════════════════════════════════════════════════════════════ */
import { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { useAuth } from "../../lib/auth.tsx";
import { ApiError } from "../../lib/api.ts";
import { ApiError, get } from "../../lib/api.ts";
const GOOGLE_ENABLED = false;
/* What a ?error= from the Google callback means, in the words the
person at the login page needs. */
const GOOGLE_ERRORS: Record<string, string> = {
cancelled: "Google sign-in was cancelled.",
expired: "That sign-in took too long or was already used. Try again.",
no_account:
"There's no admin account for that Google account. Ask a superadmin to add your email.",
linked_elsewhere:
"That email's admin account is linked to a different Google account.",
disabled: "That account has been disabled.",
wrong_domain: "Use your @nextgenerationofunity.org Google account.",
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.",
};
const fieldClass =
"w-full rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 text-[#26454c] " +
@ -27,9 +44,21 @@ export default function AdminLogin() {
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams();
const googleError = searchParams.get("error");
const [google, setGoogle] = useState(false);
useEffect(() => {
get("/auth/providers", { ttl: 0 })
.then((data) => setGoogle(Boolean(data.google)))
.catch(() => setGoogle(false));
}, []);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<any>(null);
const [error, setError] = useState<any>(
googleError ? (GOOGLE_ERRORS[googleError] ?? GOOGLE_ERRORS.google_failed) : null,
);
const [busy, setBusy] = useState(false);
const destination = location.state?.from?.pathname ?? "/admin/home";
@ -60,7 +89,7 @@ export default function AdminLogin() {
<div className="w-full max-w-sm">
<h1 className="text-3xl font-bold text-[#138ba0]">NGU admin</h1>
<p className="mt-2 text-sm text-[#4a6b72]">
Sign in to read and triage site feedback.
Sign in to edit the site.
</p>
<form
@ -68,6 +97,28 @@ export default function AdminLogin() {
noValidate
className="mt-8 rounded-2xl border border-[#138ba0]/20 bg-white p-6"
>
{google && (
<>
<a
href={`/api/auth/google?next=${encodeURIComponent(destination)}`}
className="flex items-center justify-center gap-3 rounded-full border border-[#4a6b72]/30 px-6 py-3 font-semibold text-[#26454c] transition-colors hover:bg-[#eef9fb]"
>
<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>
Sign in with Google
</a>
<div className="my-6 flex items-center gap-3 text-xs text-[#4a6b72]">
<span className="h-px flex-1 bg-[#4a6b72]/20" />
or with a password
<span className="h-px flex-1 bg-[#4a6b72]/20" />
</div>
</>
)}
<label
htmlFor="admin-email"
className="block text-sm font-medium text-[#26454c]"
@ -78,7 +129,7 @@ export default function AdminLogin() {
id="admin-email"
type="email"
autoComplete="username"
autoFocus
autoFocus={!google}
value={email}
onChange={(e) => setEmail(e.target.value)}
className={`mt-2 ${fieldClass}`}
@ -116,21 +167,6 @@ export default function AdminLogin() {
{busy ? "Signing in…" : "Sign in"}
</button>
{GOOGLE_ENABLED && (
<>
<div className="my-6 flex items-center gap-3 text-xs text-[#4a6b72]">
<span className="h-px flex-1 bg-[#4a6b72]/20" />
or
<span className="h-px flex-1 bg-[#4a6b72]/20" />
</div>
<a
href="/api/auth/google"
className="block rounded-full border border-[#4a6b72]/30 px-6 py-3 text-center font-semibold text-[#26454c] transition-colors hover:bg-[#eef9fb]"
>
Continue with Google
</a>
</>
)}
</form>
<p className="mt-6 text-center text-xs text-[#4a6b72]">