Bhakti Thakkar
Bhakti Thakkar

Reputation: 373

How to update token when the user logs in in express js?

I want to update token in user collection when the user logs in. So far, I have tried this.

router.post("/login", (req, res, next) => {
  User.find({ email: req.body.email })
    .exec()
    .then(user => {
      if (user.length < 1) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        if (result) {
          const token2 = jwt.sign(
            {
              email: user[0].email,iat: Math.floor(Date.now() / 1000) - 30
            },
            "123",
            {
                expiresIn: "1h"
            }
          );
          User.update({token : token2 })
            .exec()

          return res.status(200).json({
            message: "Auth successful",
            token: token2
          });
        }
        res.status(401).json({
          message: "Auth failed"
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

here new token is getting generated but it is not being saved in the user collection. I want to update new token in the collection.

Can anyone know where I am missing?

Upvotes: 0

Views: 358

Answers (3)

dasunse
dasunse

Reputation: 3089

Firstly understand why do you need to refresh the token. Once you create the token you can store that token as a session variable in a web, internal storage of your mobile etc...

Instead of refresh of token you can create another token. In another way you can set timeout for the token. Token will be invalid after that time period.

Upvotes: 0

Rahul kumar
Rahul kumar

Reputation: 44

Try Something like:

router.post("/login", async (req, res) => {
  try{
    const user = await User.find({ email: req.body.email });
    if (user.length < 1) {
      return res.status(401).json({
        message: "Auth failed"
      });
    }
    bcrypt.compare(req.body.password, user[0].password, (err, result) => {
      if (err) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      if (result) {
        const token2 = jwt.sign(
          {
            email: user[0].email,iat: Math.floor(Date.now() / 1000) - 30
          },
          "123",
          {
            expiresIn: "1h"
          }
        );
        User.update({_id:user[0]._id},{$set:{token : token2 }},{new: true});

        return res.status(200).json({
          message: "Auth successful",
          token: token2
        });
      }
      res.status(401).json({
        message: "Auth failed"
      });
    });
  }
  catch(err){
    res.status(500).json({
      error: err
    });
  }
});

Upvotes: 2

Shrabanee
Shrabanee

Reputation: 2766

Try below code:

      jwt.sign(
        {
          email: user[0].email,iat: Math.floor(Date.now() / 1000) - 30
        },
        "123",
        {
            expiresIn: "1h"
        }, function(err, token2) {
           User.update({token : token2 }).exec() //Change the query to update

         return res.status(200).json({
            message: "Auth successful",
            token: token2
         });
       }
      );

Let me know if it helps.

Upvotes: 1

Related Questions