17 lines
585 B
JavaScript
17 lines
585 B
JavaScript
const jwt = require('jsonwebtoken');
|
|
const SECRET = process.env.JWT_SECRET || 'dev-secret';
|
|
|
|
function authenticate(req, res, next) {
|
|
const h = req.headers.authorization;
|
|
if (!h?.startsWith('Bearer ')) return res.status(401).json({ error: 'Nicht eingeloggt' });
|
|
try { req.user = jwt.verify(h.slice(7), SECRET); next(); }
|
|
catch { res.status(401).json({ error: 'Token ungültig' }); }
|
|
}
|
|
|
|
function requireAdmin(req, res, next) {
|
|
if (req.user?.role !== 'admin') return res.status(403).json({ error: 'Kein Zugriff' });
|
|
next();
|
|
}
|
|
|
|
module.exports = { authenticate, requireAdmin };
|