Files
redlight/server/middleware/auth.js
Michelle 7426ae8088
All checks were successful
Build & Push Docker Image / build (push) Successful in 1m9s
Update language, add LICENSE and README
2026-02-24 21:04:19 +01:00

38 lines
1.1 KiB
JavaScript

import jwt from 'jsonwebtoken';
import { getDb } from '../config/database.js';
const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret-change-me';
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);
const db = getDb();
const user = await db.get('SELECT id, name, email, role, theme, language, avatar_color, avatar_image 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) {
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '7d' });
}