Home > database >  Calling middleware inside another middleware
Calling middleware inside another middleware

Time:11-09

So i was following a web development project tutorial on youtube.

They had created two middlewares, verifyToken and verifyUser.

`verifyToken`
const verifyToken = (req, res, next) => {
  const token = req.cookies.access_token;
  if (!token) {
    return next(createError(401, "You are not authenticated!"));
  }
  jwt.verify(token, process.env.JWT, (err, user) => {
    if (err) return next(createError(403, "invalid token!"));
    req.user = user;
    next();
  });
};

`verifyUser`
const verifyUser = (req, res, next) => {
  verifyToken(req, res, () => {
    if (req.user.id === req.params.id || req.user.isAdmin) {
      next();
    } else {
      return next(createError(403, "invalid user!"));
    }
  });
};

VerifyToken checks if the access_token is valid or not and verifyUser verifies if the user logged in has the correct access_token attached. Now i get the fact that to verify the user, you need to first check if the token is valid. And that's why we have called verifyToken inside verifyUser. But can someone please explain to me how the callback function is invoked? Don't we need to invoke the callback function at the end of the verifyUser function?

CodePudding user response:

The next function that you invoke inside the callback that you pass to verifyToken is actually belong to the verifyUser method. So verifyUser() => verifyToken() => next() // of verifyToken => next() // of verifyUser.

I assume that you use some nodejs server framework like Expressjs or alike. In general you should just pipe them in a row and let the framework execute them in order and pass next callback for you, like

app.get('/protected-api', verifyToken, verifyUser)
  • Related