All checks were successful
Build & Push Docker Image / build (push) Successful in 1m9s
38 lines
1.1 KiB
JavaScript
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' });
|
|
}
|