4

In my User controller, I create a token in which I save this user's id when he login to my application.

exports.findOne = (req, res) => {
  User.findOne({
    where: {
      login: req.body.login,
    },
  })
    .then(user => {
      if (user) {
        if (bcrypt.compareSync(req.body.password, user.password)) {
          const token = jwt.sign(
            {
              id: user.id, // this is the id I need.
            },
            env.SECRET_KEY,
            {
              expiresIn: 129600,
            },
          );
          return res.status(200).json({
            message: 'Auth successful',
            token,
          });
        }
       ...
      }
    })
    .catch(err => {
      res.status(400).json({ error: err });
    });
};

Now in another controller I would like to read this id and use it for my purpose. How can I get to it?

       const loginId = '?'; // here I want to give it to id
            Bill.update(
              {
                available_funds: available_funds - amountMoney,
              },
              { where: { id_owner: loginId } },
            ).then(() => {
              res.status(200).send(`ok`);
            });
  • Possible duplicate of [NodeJs - Retrieve user infor from JWT token?](https://stackoverflow.com/questions/33451298/nodejs-retrieve-user-infor-from-jwt-token) – sadrzadehsina Dec 22 '18 at 16:49

2 Answers2

6

Make a middleware which checks the incoming token before forwarding to your update route. This middleware should be responsible for validating the incoming token which you pass from the client side code after logging in (storing token in cookies is commonly practiced).

Now in your middleware, you can do something similar to this:

app.use(function(req,res,next) {
 JWT.verify(req.cookies['token'], 'YOUR_SECRET', function(err, decodedToken) {
   if(err) { /* handle token err */ }
   else {
    req.userId = decodedToken.id;   // Add to req object
    next();
   }
 });
});

Then, finally in your upcoming controller, you can access the id from the request object:

   const loginId = req.userId;

    Bill.update(
      {
        available_funds: available_funds - amountMoney,
      },
      { where: { id_owner: loginId } },
    ).then(() => {
      res.status(200).send(`ok`);
    });
0

You don't need to add extra codes. To access the userId use this:

req.payload.id
Behnam Eskandari
  • 1,011
  • 12
  • 27