Initial commit
This commit is contained in:
41
middleware/verifyToken.js
Executable file
41
middleware/verifyToken.js
Executable file
@@ -0,0 +1,41 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user