This commit is contained in:
37
server/middleware/auth.js
Normal file
37
server/middleware/auth.js
Normal file
@@ -0,0 +1,37 @@
|
||||
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: 'Authentifizierung erforderlich' });
|
||||
}
|
||||
|
||||
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: 'Benutzer nicht gefunden' });
|
||||
}
|
||||
req.user = user;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(403).json({ error: 'Ungültiges Token' });
|
||||
}
|
||||
}
|
||||
|
||||
export function requireAdmin(req, res, next) {
|
||||
if (req.user.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Administratorrechte erforderlich' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
export function generateToken(userId) {
|
||||
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '7d' });
|
||||
}
|
||||
Reference in New Issue
Block a user