first commit
This commit is contained in:
31
backend/src/middleware/auth.js
Normal file
31
backend/src/middleware/auth.js
Normal file
@@ -0,0 +1,31 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'donmarco-lan-secret-change-in-prod';
|
||||
|
||||
export function signToken(user) {
|
||||
return jwt.sign(
|
||||
{ id: user.id, username: user.username, isAdmin: !!user.is_admin },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '12h' }
|
||||
);
|
||||
}
|
||||
|
||||
export function authRequired(req, res, next) {
|
||||
const header = req.headers.authorization;
|
||||
if (!header?.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'No autenticado' });
|
||||
}
|
||||
try {
|
||||
req.user = jwt.verify(header.slice(7), JWT_SECRET);
|
||||
next();
|
||||
} catch {
|
||||
return res.status(401).json({ error: 'Token inválido o expirado' });
|
||||
}
|
||||
}
|
||||
|
||||
export function adminRequired(req, res, next) {
|
||||
if (!req.user?.isAdmin) {
|
||||
return res.status(403).json({ error: 'Solo administrador' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
Reference in New Issue
Block a user