Files
wmantly 796e013234 Fix api-tokens date display + quiet authIO no-token log (#36)
- api_tokens.ejs: created_on/last_used_on come back from Redis as strings
  (model-redis only coerces fields with an explicit `type`), so `new Date(ms)`
  yielded "Invalid date". Use `moment(ms, "x")` (the hosts.ejs/dns.ejs
  precedent) which parses a numeric string-or-number as a Unix-ms timestamp.
- api_tokens.ejs: `isExpired` is a class getter not serialized to the client
  JSON, so the "expired" badge never showed — compute expiry in the view via
  `Date.now() > Number(expires_at)`. Also guard the `last_used_on: 0` / falsy
  case (string "0" is truthy) so unset timestamps render "—" not "1970".
- middleware/auth.js: authIO did `checkToken(socket.handshake.auth.token || 0)`,
  so any socket connect without a token (login page, pre-login) did an
  `AuthToken.get(0)` lookup and logged a noisy `EntryNotFound` trace. Guard:
  reject the socket with a generic 401 when there's no token (behavior-
  preserving — unauth sockets were already rejected; just no Redis lookup / 404).

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

47 lines
1.2 KiB
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{
// No token in the handshake (e.g. a page hit before login, or a socket
// opened while logged out) → reject the socket cleanly without doing an
// AuthToken.get(0) lookup that throws a noisy EntryNotFound trace.
let tok = socket.handshake.auth && socket.handshake.auth.token;
if(!tok) return next(Auth.errors.login());
let token = await Auth.checkToken(tok);
socket.user = await token.getUser();
next();
}catch(error){
next(error);
}
}
module.exports = {auth, authIO};