Files
redlight/server/middleware/auth.js
Michelle 7466f3513d
All checks were successful
Build & Push Docker Image / build (push) Successful in 6m25s
Enhance security and validation across multiple routes:
- Escape XML and HTML special characters to prevent injection attacks.
- Implement rate limiting for various endpoints to mitigate abuse.
- Add validation for email formats, password lengths, and field limits.
- Ensure proper access control for recordings and room management.
2026-02-28 19:49:29 +01:00

59 lines
1.8 KiB
JavaScript

import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
import { getDb } from '../config/database.js';
import redis from '../config/redis.js';
if (!process.env.JWT_SECRET) {
console.error('FATAL: JWT_SECRET environment variable is not set. ');
process.exit(1);
}
const JWT_SECRET = process.env.JWT_SECRET;
export async function authenticateToken(req, res, next) {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
// Check JWT blacklist in DragonflyDB (revoked tokens via logout)
if (decoded.jti) {
try {
const revoked = await redis.get(`blacklist:${decoded.jti}`);
if (revoked) {
return res.status(401).json({ error: 'Token has been revoked' });
}
} catch (redisErr) {
// Graceful degradation: if Redis is unavailable, allow the request
console.warn('Redis blacklist check skipped:', redisErr.message);
}
}
const db = getDb();
const user = await db.get('SELECT id, name, display_name, email, role, theme, language, avatar_color, avatar_image, email_verified FROM users WHERE id = ?', [decoded.userId]);
if (!user) {
return res.status(401).json({ error: 'User not found' });
}
req.user = user;
next();
} catch (err) {
return res.status(403).json({ error: 'Invalid token' });
}
}
export function requireAdmin(req, res, next) {
if (req.user.role !== 'admin') {
return res.status(403).json({ error: 'Admin rights required' });
}
next();
}
export function generateToken(userId) {
const jti = uuidv4();
return jwt.sign({ userId, jti }, JWT_SECRET, { expiresIn: '7d' });
}