From 39fea743653dd89d86ff72a24d2f3ba6cd847074 Mon Sep 17 00:00:00 2001 From: Francesco Esposito <33671357+frsposito@users.noreply.github.com> Date: Tue, 6 Aug 2019 18:49:02 +0200 Subject: [PATCH] add helper: authentication --- src/helpers/authentication.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/helpers/authentication.js diff --git a/src/helpers/authentication.js b/src/helpers/authentication.js new file mode 100644 index 0000000..5bc7350 --- /dev/null +++ b/src/helpers/authentication.js @@ -0,0 +1,28 @@ +import jwt from 'jsonwebtoken'; + +const validateUser = (req, res, next) => { + let token = req.headers['x-access-token'] || req.headers.authorization; + + if (token) { + token = token.slice(7, token.length); + + jwt.verify(token, req.app.get('secretKey'), (err, decoded) => { + if (err) { + res.json({ + success: false, + message: 'Token is not valid', + }); + } else { + req.decoded = decoded; + next(); + } + }); + } else { + return res.status(401).json({ + success: false, + message: 'Auth token is not supplied', + }); + } +}; + +export default validateUser;