Files
Showy/backend/middleware/authMiddleware.js
T
X4Lo 0a79ee9768 Add named-token auth support to middleware and configService
authMiddleware now falls back to checking named tokens from settings
when JWT verification fails. configService.getNamedTokens() filters by
endDate, skipping expired tokens. Tokens without an endDate never expire.
2026-06-30 23:54:04 +01:00

66 lines
1.5 KiB
JavaScript

const jwt = require("jsonwebtoken");
const configService = require("../services/configService");
function validateToken(tokenValue) {
const settings = configService.getSettings();
const jwtSecret = settings.jwtSecret || "showy-default-secret";
// 1. Check dedicated dashboardToken
if (settings.dashboardToken && settings.dashboardToken === tokenValue) {
return true;
}
// 2. Check named tokens (supports expiration)
const namedTokens = configService.getNamedTokens();
if (namedTokens.some((t) => t.value === tokenValue)) {
return true;
}
// 3. Try JWT
try {
jwt.verify(tokenValue, jwtSecret);
return true;
} catch {
// not a valid JWT
}
return false;
}
function extractToken(req) {
// Authorization: Bearer <token>
const auth = req.headers.authorization;
if (auth && auth.startsWith("Bearer ")) {
return auth.slice(7);
}
// ?token= query parameter
if (req.query.token) {
return req.query.token;
}
return null;
}
function authMiddleware(req, res, next) {
// Skip auth for login/verify/media endpoints
if (
req.path === "/auth/login" ||
req.path === "/auth/verify" ||
req.path.startsWith("/media/")
) {
return next();
}
const tokenValue = extractToken(req);
if (!tokenValue) {
return res.status(401).json({ error: "Authentication required" });
}
if (!validateToken(tokenValue)) {
return res.status(401).json({ error: "Invalid or expired token" });
}
next();
}
module.exports = authMiddleware;