42 lines
994 B
JavaScript
Executable File
42 lines
994 B
JavaScript
Executable File
const jwt = require('jsonwebtoken');
|
|
|
|
if (!process.env.JWT_SECRET) {
|
|
throw new Error('JWT_SECRET não definido no .env');
|
|
}
|
|
|
|
function verifyToken(req, res, next) {
|
|
const authHeader =
|
|
req.headers['authorization'] || req.headers['Authorization'];
|
|
|
|
if (!authHeader) {
|
|
return res.status(403).json({ error: 'Token não fornecido' });
|
|
}
|
|
|
|
const match = authHeader.match(/^Bearer\s+(.+)$/i);
|
|
if (!match) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: 'Token malformado. Use "Bearer <token>"' });
|
|
}
|
|
|
|
const token = match[1];
|
|
|
|
jwt.verify(token, process.env.JWT_SECRET, (err, payload) => {
|
|
if (err) {
|
|
if (err.name === 'TokenExpiredError') {
|
|
return res.status(403).json({ error: 'Sessão expirada' });
|
|
}
|
|
return res.status(403).json({ error: 'Token inválido' });
|
|
}
|
|
|
|
if (!payload?.id) {
|
|
return res.status(403).json({ error: 'Token inválido' });
|
|
}
|
|
|
|
req.user = payload;
|
|
next();
|
|
});
|
|
}
|
|
|
|
module.exports = verifyToken;
|