Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing current user on ExpressJs - Passport

I'm creating a backend app using expressJs and passportjs (local strategy) to secure some of the routes. I need to add the information for the current user on every Database query so we only expose the relevant information to each user. I know you can access the information for current user checking req.user, but that will involve passing the user information (or even the request) as a parameter through all my call-stack, and I found it a bit inconvenient.

Is there to get the user information on the last layer (the one preparing the sql statement) without adding it on the parameters?.

Thanks.

like image 864
Sole Avatar asked Dec 28 '25 09:12

Sole


1 Answers

Why not get the user information on the last layer by id ? Since you are using passport-local, you can query a user by id in the last database query by accessing req.user.id . No parameter is needed.

 router.post('/your/route', function(req, res) {
   User.findOne({
     where: {id: req.user.id}
   }).then(function(user) {
   // do something
    });
 //send response
 });
like image 101
govgo Avatar answered Dec 30 '25 22:12

govgo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!