How to get current user using jsonwebtoken in Sails.js?

I worked with Sails a couple of years ago, I came from Rails, and I have no experience with Node.js.

Now I'm trying to do strong token authentication using jsonwebtoken. https://github.com/auth0/node-jsonwebtoken

I followed this guide http://thesabbir.com/how-to-use-json-web-token-authentication-with-sails-js/ and everything worked fine. I can do registration, log in, and then use the token correctly for different actions.

Now there are some actions in which I would like to use a login user, something like devise current_user helper. For example, when creating a comment, this comment must belong to the current user.

Using the Sabbir Ahmed manual, on line 33 of the isAuthorized.js policy, the token receives the decryption, so I can get the current user ID from it.

So my question is: what should be the best way to get the current user and be able to use it later in some kind of controller? For example, I tried something like:

 # isAuthorized.js line 34, after getting decrypted token User.findOne({id: token.id}).exec(function findOneCB(err, found){ currentUser = found; }); 

But, therefore, since this is an asynchronous action, I cannot use this currentUser in the controller.

I want to save the current user in order to be able to use it later in some controller without repeating the same code in each controller, something like an assistant or, possibly, a service.

+5
source share
2 answers

The trick is where you put next() . Since you are making an asynchronous call, the control should only be passed to the next policy / controller when the database action will compete.

You must change the policy:

 User.findOne({id: token.id}).exec(function findOneCB(err, found){ if(err) next(err); req.currentUser = found; next(); }); 

And you should have access to user details in controllers that use the isAuthorized policy through req.currentUser

+4
source

If

For example, when creating a comment, this comment must belong to the current user.

what you mean is certain attributes like username and country etc. and not a database query after checking what you can do is send these extra attributes to jwToken.issue in api/controllers/UsersController.js

eg.

 jwToken.issue({ id: user.id, username: user.name, country: user.country }) 

As much as it helps, you can save api/policies/isAuthorized.js as it is, and in all the controllers that you use in the future, you can access the payload values ​​with

 token.username or token.country 

Instead of querying the database again, thereby saving valuable response time.

Beware, however, of the data you choose to send to the token (you can also send {user: user} if you want), since a secret key or hashing is not required to decrypt the payload, as you can see @ jwt.io , you can exercise restraint.

0
source

Source: https://habr.com/ru/post/1241891/


All Articles