Add Google sign-in for @nextgenerationofunity.org admin accounts
The login page offers "Sign in with Google" above email and password, once GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are set on the service. It's the server-side authorization-code flow with PKCE; the ID token comes straight from Google's token endpoint and is checked for issuer, audience, expiry, a verified email and the Workspace domain (Google's hd claim). Only accounts admin-cli has made get in. The first Google sign-in links the account with the same email; later ones match by the link. A disabled account, one linked to another Google account, or a missing account is refused, with a message on the login page, and a refused sign-in never changes the account. admin-cli list shows which accounts are linked. Setup is in docs/google-sign-in.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
64cb2ec56a
commit
d4b39251d9
8 changed files with 392 additions and 28 deletions
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue