'use strict'; const jwt = require('jsonwebtoken'); const { AppError } = require('./errors'); // Feature flag cache: orgId → { features: string[], fetchedAt: number } const featureCache = new Map(); const FEATURE_CACHE_TTL = 5 * 60 * 1000; // 5 minutes function authenticateToken(req, res, next) { const header = req.headers.authorization; // ?token= fallback for browser-native requests (video/audio elements, downloads) const token = (header && header.startsWith('Bearer ')) ? header.slice(7) : req.query.token; if (!token) { return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401)); } jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, async (err, decoded) => { if (err) { return next(new AppError('AUTH_INVALID', 'Invalid or expired token.', 401)); } try { const { models } = require('./db'); const user = await models.User.findByPk(decoded.id, { attributes: ['id', 'username', 'role', 'organizationId', 'isActive', 'passwordChangedAt'], }); if (!user || !user.isActive) { return next(new AppError('AUTH_INVALID', 'User not found or inactive.', 401)); } if (user.passwordChangedAt && decoded.iat * 1000 < user.passwordChangedAt.getTime()) { return next(new AppError('AUTH_INVALID', 'Token issued before last password change.', 401)); } req.user = { id: user.id, username: user.username, role: user.role, organizationId: user.organizationId, }; // Allow SystemAdmin to scope API calls to a specific org via header or query param if (user.role === 'SystemAdmin') { const fromHeader = parseInt(req.headers['x-org-id'], 10); const fromQuery = parseInt(req.query.orgId, 10); const orgId = !isNaN(fromHeader) ? fromHeader : !isNaN(fromQuery) ? fromQuery : NaN; if (!isNaN(orgId)) req.user.organizationId = orgId; } next(); } catch (dbErr) { next(dbErr); } }); } function authenticateRole(roles) { return (req, res, next) => { if (!req.user) { return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401)); } if (!roles.includes(req.user.role)) { return next(new AppError('AUTH_FORBIDDEN', 'You do not have permission to perform this action.', 403)); } next(); }; } function requireFeature(feature) { return async (req, res, next) => { if (!req.user) { return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401)); } const orgId = req.user.organizationId; const cached = featureCache.get(orgId); if (cached && Date.now() - cached.fetchedAt < FEATURE_CACHE_TTL) { if (!cached.features.includes(feature)) { return next(new AppError('FEATURE_DISABLED', 'This feature is not enabled for your organization.', 403)); } return next(); } try { const { models } = require('./db'); const org = await models.Organization.findByPk(orgId, { attributes: ['features'] }); const features = org ? org.features : []; featureCache.set(orgId, { features, fetchedAt: Date.now() }); if (!features.includes(feature)) { return next(new AppError('FEATURE_DISABLED', 'This feature is not enabled for your organization.', 403)); } next(); } catch (err) { next(err); } }; } module.exports = { authenticateToken, authenticateRole, requireFeature };