【问题标题】:bcrypt / Mongoose change user passwordbcrypt / Mongoose 更改用户密码
【发布时间】:2020-09-18 21:50:13
【问题描述】:

我正在尝试向我构建的仪表板添加更改密码选项。我的表单有三个输入,currentPassword、newPassword、confirmNewPassword。这是您对数据库的标准检查当前密码,如果匹配,则使用新密码更新它。

无论我做什么,我都无法让代码在匹配成功的地方运行(bcrypt.compare 之后的代码)。我知道我使用了正确的密码。我无法弄清楚我做错了什么。感谢您的帮助。

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,
                    });
                }
            });
        });
    }
});

【问题讨论】:

  • 你应该在bcrypt.hash回调中重定向

标签: javascript node.js mongodb mongoose bcrypt


【解决方案1】:

我知道它是什么。 const userID 应该设置为等于 req.user.id。然后,在我的 Mongoose 查找中,我应该使用 _id 作为查询。

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,
                });
            }
        });
    });
}

});

【讨论】:

    【解决方案2】:

    尝试使用异步等待语法

    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,
            });
          }
        });
      }
    });
    

    【讨论】:

    • 谢谢,但结果是一样的。无论我尝试什么,它总是以“密码不匹配”作为响应。
    猜你喜欢
    • 2021-08-27
    • 2019-06-28
    • 2013-07-23
    • 2017-01-03
    • 2021-06-15
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多