0

I have a middleware for authentication which decrypts the token in the header and put the userId from the token to req.userId. Otherwise it throws an error if token doesn't exists or is invalid.

I call it like this in routes where I need authentication:

server.get('/api/somecall', authMiddleware, callService.somecall);

Now I will also have some routes which will carry a user ID in its params, like this:

server.get('/api/somecall/:userId', callService.somecall);

Here :userId can be a Mongoose Object ID or just me.

So I want to write another middleware which will be called for all routes that looks for particular params like userId and/or adminId. And if their value equals me, I want to make sure that authMiddleware automatically comes to action, PLUS replace me with the logged in user's ID so the callService.somecall handles the logic inside as it received a Mongoose Object ID.

There are two problems I'm facing:

  • How do I get req.params.userId in a middleware which is called before server.get(...)?
  • Suppose if I get req.params.userId somehow, how do I make the middleware to:
    • perform some condition (check if req.params.userId === 'me'),
    • then call authMiddleware so that I get req.userId from token, and
    • then perform more actions (replace req.params.userId = req.userId
    • then call next() to continue.
Ali Yousuf
  • 692
  • 8
  • 23

1 Answers1

-1

Your question is a little confusing so I don't know if this will help, but why not do something like this:

server.get('/api/somecall/:userId', otherMiddleware, callService.somecall);

function otherMiddleware(req, res, next){
    if(req.params.userId === 'me'){
        authMiddleware(req, res, next);
    }

    // Do other stuff here.

    next();
}
HeadCode
  • 2,770
  • 1
  • 14
  • 26
  • Thanks, I actually modified the `authMiddleware` and did the `params` thing inside it. – Ali Yousuf Jan 26 '16 at 18:13
  • This will cause error: `next shouldn't be called more than once`. Assuming `authMiddleware` is written correctly, it would have already called `next()` already and the one in `otherMiddleware` will cause error – Jason Yu Jun 07 '23 at 02:18