feat: registration and login with JWT auth
- users table: email, password_hash (bcrypt), role, is_active - POST /auth/register — checks blocklist, hashes password, returns JWT - POST /auth/login — verifies password, returns JWT - Auth middleware: accepts env tokens (dev) OR valid JWTs - end-user role → 403 Insufficient permissions on all /api/* routes - JWT_SECRET + JWT_EXPIRES_IN env vars Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,12 +1,24 @@
|
||||
const TOKENS = (process.env.API_TOKENS || '').split(',').map(t => t.trim()).filter(Boolean);
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const ENV_TOKENS = (process.env.API_TOKENS || '').split(',').map(t => t.trim()).filter(Boolean);
|
||||
|
||||
module.exports = function auth(req, res, next) {
|
||||
const header = req.headers['authorization'] || '';
|
||||
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
|
||||
|
||||
if (!token || !TOKENS.includes(token)) {
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
}
|
||||
if (!token) return res.status(401).json({ error: 'Unauthorized' });
|
||||
|
||||
next();
|
||||
// Dev/admin tokens aus Env — keine Rollenprüfung
|
||||
if (ENV_TOKENS.includes(token)) return next();
|
||||
|
||||
// JWT verifizieren
|
||||
try {
|
||||
const payload = jwt.verify(token, process.env.JWT_SECRET);
|
||||
if (payload.role === 'end-user')
|
||||
return res.status(403).json({ error: 'Insufficient permissions' });
|
||||
req.user = payload;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: 'Invalid or expired token' });
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user