Tony Drummond
Tony Drummond

Reputation: 375

bcrypt / Mongoose change user password

I'm trying to add a change password option to a dashboard I built. My form has three inputs, currentPassword, newPassword, confirmNewPassword. This is your standard check current password against database, if it matches, then update it with the new password.

No matter what I do, I cannot get the code to run where a match is successful (the code after bcrypt.compare). I know I am using the correct password. I can't figure out what I'm doing wrong. Appreciate the help.

router.post("/changepassword", ensureAuthenticated, (req, res) => {
    const { currentPassword, newPassword, confirmNewPassword } = req.body;
    const userID = req.user.userID;
    let errors = [];

    //Check required fields
    if (!currentPassword || !newPassword || !confirmNewPassword) {
        errors.push({ msg: "Please fill in all fields." });
    }

    //Check passwords match
    if (newPassword !== confirmNewPassword) {
        errors.push({ msg: "New passwords do not match." });
    }

    //Check password length
    if (newPassword.length < 6 || confirmNewPassword.length < 6) {
        errors.push({ msg: "Password should be at least six characters." });
    }

    if (errors.length > 0) {
        res.render("changepassword", {
            errors,
            name: req.user.name,
        });
    } else {
        //VALIDATION PASSED
        //Ensure current password submitted matches
        User.findOne({ userID: userID }).then(user => {
            //encrypt newly submitted password
            bcrypt.compare(currentPassword, user.password, (err, isMatch) => {
                if (err) throw err;
                if (isMatch) {
                    console.log(user.password);
                    //Update password for user with new password
                    bcrypt.genSalt(10, (err, salt) =>
                        bcrypt.hash(newPassword, salt, (err, hash) => {
                            if (err) throw err;
                            user.password = hash;
                            user.save();
                        })
                    );
                    req.flash("success_msg", "Password successfully updated!");
                    res.redirect("/dashboard");
                } else {
                    //Password does not match
                    errors.push({ msg: "Current password is not a match." });
                    res.render("changepassword", {
                        errors,
                        name: req.user.name,
                    });
                }
            });
        });
    }
});

Upvotes: 1

Views: 2932

Answers (2)

Tony Drummond
Tony Drummond

Reputation: 375

I figured out what it was. const userID should have been set to equal to req.user.id. Then, in my Mongoose find I should have been using _id as the query.

router.post("/changepassword", ensureAuthenticated, (req, res) => {
const { currentPassword, newPassword, confirmNewPassword } = req.body;
const userID = req.user.id;
let errors = [];
//Check required fields
if (!currentPassword || !newPassword || !confirmNewPassword) {
    errors.push({ msg: "Please fill in all fields." });
}

//Check passwords match
if (newPassword !== confirmNewPassword) {
    errors.push({ msg: "New passwords do not match." });
}

//Check password length
if (newPassword.length < 6 || confirmNewPassword.length < 6) {
    errors.push({ msg: "Password should be at least six characters." });
}

if (errors.length > 0) {
    res.render("changepassword", {
        errors,
        name: req.user.name,
    });
} else {
    //VALIDATION PASSED
    //Ensure current password submitted matches
    User.findOne({ _id: userID }).then(user => {
        //encrypt newly submitted password
        bcrypt.compare(currentPassword, user.password, (err, isMatch) => {
            if (err) throw err;
            if (isMatch) {
                //Update password for user with new password
                bcrypt.genSalt(10, (err, salt) =>
                    bcrypt.hash(newPassword, salt, (err, hash) => {
                        if (err) throw err;
                        user.password = hash;
                        user.save();
                    })
                );
                req.flash("success_msg", "Password successfully updated!");
                res.redirect("/dashboard");
            } else {
                //Password does not match
                errors.push({ msg: "Current password is not a match." });
                res.render("changepassword", {
                    errors,
                    name: req.user.name,
                });
            }
        });
    });
}

});

Upvotes: 1

Jithin Zachariah
Jithin Zachariah

Reputation: 332

Try using async await syntax

router.post("/changepassword", ensureAuthenticated, async (req, res) => {
  const { currentPassword, newPassword, confirmNewPassword } = req.body;
  const userID = req.user.userID;
  let errors = [];

  //Check required fields
  if (!currentPassword || !newPassword || !confirmNewPassword) {
    errors.push({ msg: "Please fill in all fields." });
  }

  //Check passwords match
  if (newPassword !== confirmNewPassword) {
    errors.push({ msg: "New passwords do not match." });
  }

  //Check password length
  if (newPassword.length < 6 || confirmNewPassword.length < 6) {
    errors.push({ msg: "Password should be at least six characters." });
  }

  if (errors.length > 0) {
    res.render("changepassword", {
      errors,
      name: req.user.name,
    });
  } else {
    //VALIDATION PASSED
    //Ensure current password submitted matches

    User.findOne({ userID: userID }).then(async (user) => {
      //encrypt newly submitted password
      // async-await syntax
      const isMatch = await bcrypt.compare(currentPassword, user.password);

      if (isMatch) {
        console.log(user.password);
        //Update password for user with new password
        bcrypt.genSalt(10, (err, salt) =>
          bcrypt.hash(newPassword, salt, (err, hash) => {
            if (err) throw err;
            user.password = hash;
            user.save();
          })
        );
        req.flash("success_msg", "Password successfully updated!");
        res.redirect("/dashboard");
      } else {
        //Password does not match
        errors.push({ msg: "Current password is not a match." });
        res.render("changepassword", {
          errors,
          name: req.user.name,
        });
      }
    });
  }
});

Upvotes: 0

Related Questions