Middleware: Verify token.
Margaret W.N
Posted on August 19, 2020
Today was all about separation of concerns. I had to refactor the get users function to simply get users and not verify any tokens. Hence i created middleware that would handle token verification on a request made to get users.
I moved the middleware code to auth.js.
Code in auth.js
const verifyToken = (req, res, next) => {
let token = req.headers['x-access-token']
if(!token){
return res.status(401).send('no token provided')
}
jwt.verify(token, secret, (err, userData) => {
if(err) {
return res.status(403).send('Failed to authenticate token.')
}
if(userData){
return next()
}
return res.sendStatus(500)
})
}
module.exports = {
verifyToken
}
I passed the middleware to the route handler.
router.route('/users')
.get(auth.verifyToken, userController.getUsers);
And called it a day!
_ Day 34._
π πͺ π
π©
Margaret W.N
Posted on August 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.