DEV Community

Margaret W.N
Margaret W.N

Posted on

Middleware: Verify token.

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
}
Enter fullscreen mode Exit fullscreen mode

I passed the middleware to the route handler.

router.route('/users')
  .get(auth.verifyToken, userController.getUsers);
Enter fullscreen mode Exit fullscreen mode

And called it a day!

_ Day 34._

Discussion (0)