Middleware: Verify token.

mtee

Margaret W.N

Posted on August 19, 2020

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._

πŸ’– πŸ’ͺ πŸ™… 🚩
mtee
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.

Related

Day 23 of 100DaysOfCode
javascript Day 23 of 100DaysOfCode

October 3, 2024

Day21 of 100DaysOfCode
javascript Day21 of 100DaysOfCode

August 22, 2024

Day22 of 100DaysOfCode
javascript Day22 of 100DaysOfCode

September 7, 2024

Day 2 of #100daysofMiva Coding Challenge
100daysofmiva Day 2 of #100daysofMiva Coding Challenge

August 22, 2024