1

I am new Passport.js. I was using passport-local-mongoose making forget password API. for that I was using setPassword method as define by https://github.com/saintedlama/passport-local-mongoose.

Now this whole code is working fine. No error rises and mail is sended after the setPassword Execution. But password doesn't resets. It work only with the old password.

router.patch("/forget-password", async (req, res, next) => {
  var user = await User.findOne({ username: req.body.email });

  if (!user) {
    return res.status(400).json({ msg: "There is no such user registered." });
  } else {
    console.log(user);
    if (String(req.body.otp) != String(genOTP)) {
      return res
        .status(400)
        .json({ msg: "OTP does not match. Please check again." });
    } else {
      user.setPassword(req.body.password, (err, user) => {
        if (err) {
          res.statusCode = 500;
          res.send(err);
        } else {
          readHTMLFile(__dirname + "/mail/reseted.html", function (err, html) {
            if (err) {
              res.statusCode = 500;
              res.send(err);
            } else {
              try {
                sendEmail(
                  user.username,
                  "Security alert",
                  html
                );
                return res
                  .status(400)
                  .json({ msg: "Password Reset Successfully." });
              } catch (err) {
                console.error(err.message);
                return res.status(500).json({ msg: "Server Error" });
              }
            }
          });
        }
      });
    }
  }
});

Please suggest a solution to the same.

1 Answers1

0

According to documentation setPassword method doesn't save the document.

Using setPassword() will only update the document's password fields, but will not save the document. To commit the changed document, remember to use Mongoose's document.save() after using setPassword().

else {
    try {
        user.save() // here
        sendEmail(
            user.username,
            "Security alert",
            html
        );
        return res
            .status(400)
            .json({ msg: "Password Reset Successfully." });
    } catch (err) {
        console.error(err.message);
        return res.status(500).json({ msg: "Server Error" });
    }
}