diff --git a/middlewares/auth.js b/middlewares/auth.js index 345b869..a45c305 100644 --- a/middlewares/auth.js +++ b/middlewares/auth.js @@ -2,13 +2,25 @@ const jwt = require('jsonwebtoken'); const config = require('config'); module.exports = (req, res, next) => { - const token = req.header('Authorization'); - if (!token) { + const authHeader = req.header('Authorization'); + if (!authHeader) { const err = new Error('Access denied. No token provided.'); err.status = 401; return next(err); } + const parts = authHeader.split(' '); + + if (!parts.length === 2) { + return res.status(401).send({ error: 'Token error' }); + } + + const [scheme, token] = parts; + + if (!/^Bearer$/i.test(scheme)) { + return res.status(401).send({ error: 'Token Malformatted' }); + } + try { const decoded = jwt.verify(token, config.get('jwtPrivateKey')); req.user = decoded; diff --git a/modules/tokenGenerator.js b/modules/tokenGenerator.js index 61f87fa..56076da 100644 --- a/modules/tokenGenerator.js +++ b/modules/tokenGenerator.js @@ -2,7 +2,8 @@ const jwt = require('jsonwebtoken'); const config = require('config'); function sendToken (req) { - const token = jwt.sign({ username: req.body.username }, config.get('jwtPrivateKey'), { expiresIn: '7 days' }); + // Validade do Token: 7 dias + const token = jwt.sign({ username: req.body.username }, config.get('jwtPrivateKey'), { expiresIn: 604800 }); // 7 dias em segundos return token; }