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 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;