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 beforeserver.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 getreq.userId
from token, and - then perform more actions (replace
req.params.userId = req.userId
- then call
next()
to continue.
- perform some condition (check if