Files
sso-manager-node/nodejs/middleware/auth.js
T
wmantly b91ef2792d Add self-service API tokens (PATs) with UI + Bearer auth (#35)
Personal access tokens so scripts/CI can call the management API without a
browser session. Each logged-in user mints their own token; it authenticates as
the creator (carries their LDAP group permissions, re-resolved live), so the
existing permission.byGroup checks apply unchanged.

- models/api_token.js: new ApiToken model (sso_<id>_<secret> format; id is the
  lookup key, secret bcrypt-hashed + isPrivate, shown once). add()/rotate()/
  authenticate(); optional expires_at; best-effort last_used_on. No _ttl
  (persists; lifetime via expires_at).
- routes/api_token.js: self-service CRUD (list/get/update/delete/rotate),
  owner-scoped (created_by === req.user.uid, 403 otherwise).
- middleware/auth.js + models/auth.js: accept `Authorization: Bearer sso_...`
  (precedence over the auth-token session header); checkApiToken collapses
  every failure to one generic 401 (no existence/secret/expiry leak).
- views/api_tokens.ejs + routes/index.js (GET /api-tokens): self-service page
  (forceLogin, no group gate) — create (token shown once), edit, rotate, revoke.
- views/top.ejs: "API Tokens" nav entry visible to all logged-in users.
- public/js/app.js: app.apiToken client module.
- DEPLOYMENT.md + docs/deployment.md: API tokens section.

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 17:12:35 -04:00

42 lines
973 B
JavaScript
Executable File

'use strict';
const {Auth} = require('../models/auth');
async function auth(req, res, next){
try{
// API-only token: `Authorization: Bearer sso_<id>_<secret>`.
// Takes precedence over the browser session header so a script can call
// the same /api/* routes the UI uses.
const authz = req.header('authorization') || '';
if(authz.slice(0, 7).toLowerCase() === 'bearer '){
const user = await Auth.checkApiToken(authz.slice(7));
if(user && user.uid){
req.user = user;
return next();
}
}
// Browser session: `auth-token: <AuthToken uuid>`.
let user = await Auth.checkToken({token: req.header('auth-token')});
if(user.uid){
req.user = user;
return next();
}
}catch(error){
next(error);
}
}
async function authIO(socket, next){
try{
let token = await Auth.checkToken(socket.handshake.auth.token || 0);
socket.user = await token.getUser();
next();
}catch(error){
next(error);
}
}
module.exports = {auth, authIO};