From 88074fc6363ac86a80b82d619191ec7b54918b5a Mon Sep 17 00:00:00 2001 From: canove Date: Fri, 14 Aug 2020 05:48:24 -0300 Subject: [PATCH] impromente: better jwt errors handler --- backend/src/middleware/is-auth.js | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/backend/src/middleware/is-auth.js b/backend/src/middleware/is-auth.js index b9fc728..633de47 100644 --- a/backend/src/middleware/is-auth.js +++ b/backend/src/middleware/is-auth.js @@ -1,17 +1,22 @@ const jwt = require("jsonwebtoken"); + const authConfig = require("../config/auth"); -module.exports = (req, res, next) => { - let decodedToken; +module.exports = async (req, res, next) => { + const authHeader = req.headers.authorization; - const [, token] = req.get("Authorization").split(" "); - decodedToken = jwt.verify(token, authConfig.secret); - // todo >> find user in DB and store in req.user to use latter, or throw an error if user not exists anymore - req.userId = decodedToken.userId; - - if (!decodedToken) { - return res.status(401).json({ message: "Unauthorized" }); + if (!authHeader) { + return res.status(401).json({ error: "Token not provided" }); } - next(); + const [, token] = authHeader.split(" "); + + jwt.verify(token, authConfig.secret, (error, result) => { + if (error) { + return res.status(401).json({ error: "Invalid token" }); + } + req.userId = token.userId; + // todo >> find user in DB and store in req.user to use latter, or throw an error if user not exists anymore + next(); + }); };