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>
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
'use strict';
|
||||
|
||||
// Self-service API token (PAT) management. Every endpoint is owner-scoped: a
|
||||
// user only sees / mutates tokens where created_by === req.user.uid. No admin
|
||||
// group is required (unlike routes/oauth_client.js); the Bearer-authed requests
|
||||
// these tokens enable carry the creator's own LDAP group permissions.
|
||||
|
||||
const router = require('express').Router();
|
||||
const { ApiToken } = require('../models/api_token');
|
||||
|
||||
function forbidden() {
|
||||
const e = new Error('Forbidden');
|
||||
e.name = 'Forbidden';
|
||||
e.message = 'You do not own this API token.';
|
||||
e.status = 403;
|
||||
return e;
|
||||
}
|
||||
|
||||
// Resolve a token the caller owns. Missing or not-yours both raise 403 (no
|
||||
// existence leak across users; ids are unguessable random hex anyway).
|
||||
async function getOwned(req, id) {
|
||||
let token;
|
||||
try {
|
||||
token = await ApiToken.get(id);
|
||||
} catch (e) {
|
||||
throw forbidden();
|
||||
}
|
||||
if (!token || token.created_by !== req.user.uid) throw forbidden();
|
||||
return token;
|
||||
}
|
||||
|
||||
// Accept `expires_in_days` from the UI and resolve it to an epoch-ms
|
||||
// `expires_at` (0 = never). Mutates `body` in place.
|
||||
function resolveExpiry(body) {
|
||||
if (body.expires_in_days !== undefined && body.expires_in_days !== '') {
|
||||
const days = Number(body.expires_in_days);
|
||||
body.expires_at = days > 0 ? (new Date).getTime() + days * 86400000 : 0;
|
||||
delete body.expires_in_days;
|
||||
} else if (body.expires_in_days !== undefined) {
|
||||
body.expires_at = 0;
|
||||
delete body.expires_in_days;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
router.get('/', async function(req, res, next) {
|
||||
try {
|
||||
return res.json({ results: await ApiToken.listDetail({ created_by: req.user.uid }) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/', async function(req, res, next) {
|
||||
try {
|
||||
req.body.created_by = req.user.uid;
|
||||
resolveExpiry(req.body);
|
||||
|
||||
const token = await ApiToken.add(req.body);
|
||||
|
||||
return res.json({
|
||||
results: token,
|
||||
token: token._raw_token,
|
||||
message: `API token '${token.name}' created. Save it now — it will not be shown again.`,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:id', async function(req, res, next) {
|
||||
try {
|
||||
return res.json({ results: await getOwned(req, req.params.id) });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/:id', async function(req, res, next) {
|
||||
try {
|
||||
const token = await getOwned(req, req.params.id);
|
||||
|
||||
const update = {};
|
||||
for (const k of ['name', 'description']) {
|
||||
if (req.body[k] !== undefined) update[k] = req.body[k];
|
||||
}
|
||||
// Allow extending/shortening the lifetime. Accept expires_in_days (UI)
|
||||
// or expires_at (epoch ms); 0 / '' / missing means "no expiry".
|
||||
if (req.body.expires_in_days !== undefined && req.body.expires_in_days !== '') {
|
||||
const days = Number(req.body.expires_in_days);
|
||||
update.expires_at = days > 0 ? (new Date).getTime() + days * 86400000 : 0;
|
||||
} else if (req.body.expires_at !== undefined) {
|
||||
update.expires_at = Number(req.body.expires_at) || 0;
|
||||
}
|
||||
|
||||
return res.json({
|
||||
results: await token.update(update),
|
||||
message: `API token '${token.name}' updated.`,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', async function(req, res, next) {
|
||||
try {
|
||||
const token = await getOwned(req, req.params.id);
|
||||
await token.remove();
|
||||
|
||||
return res.json({
|
||||
id: req.params.id,
|
||||
message: `API token '${token.name}' revoked.`,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/rotate', async function(req, res, next) {
|
||||
try {
|
||||
const token = await getOwned(req, req.params.id);
|
||||
const raw = await token.rotate();
|
||||
|
||||
return res.json({
|
||||
token: raw,
|
||||
message: `API token '${token.name}' rotated. Save it — it will not be shown again.`,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user