48 lines
929 B
JavaScript
48 lines
929 B
JavaScript
const jwt = require('jsonwebtoken');
|
|
|
|
function authMiddleware(req, res, next) {
|
|
const authHeader = req.headers.authorization;
|
|
|
|
if (!authHeader) {
|
|
return res.status(401).json({
|
|
ok: false,
|
|
message: 'Token não informado.',
|
|
});
|
|
}
|
|
|
|
const parts = authHeader.split(' ');
|
|
|
|
if (parts.length !== 2) {
|
|
return res.status(401).json({
|
|
ok: false,
|
|
message: 'Token inválido.',
|
|
});
|
|
}
|
|
|
|
const [scheme, token] = parts;
|
|
|
|
if (!/^Bearer$/i.test(scheme)) {
|
|
return res.status(401).json({
|
|
ok: false,
|
|
message: 'Formato de token inválido.',
|
|
});
|
|
}
|
|
|
|
try {
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
|
|
req.user = {
|
|
id: decoded.id,
|
|
nome: decoded.nome,
|
|
};
|
|
|
|
return next();
|
|
} catch (error) {
|
|
return res.status(401).json({
|
|
ok: false,
|
|
message: 'Token expirado ou inválido.',
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = authMiddleware; |