mongodb bcrypt.compareSync总是返回false

soat7uwm  于 2023-05-28  发布在  Go
关注(0)|答案(4)|浏览(405)

我验证了在我的数据库中我保存了用户名和密码的哈希值。我能够从数据库中检索名称,但是当我检查密码时,它总是返回false。不知道什么是错的。
这是我的HTML

<div ng-controller="userController"> 
    <div class=user>
        <form name="login_form">
            <h2 class>Login</h2>
            <h3 class = "login_page">UserName</h3>
            <input ng-model="user" type="text" ng-minlength="1" required>
            <h3 class = "login_page">Password</h3>
            <input ng-model="password" type="password" name="password" ng-minlength="4" required>
            <input type="submit" value="Login" ng-click="login()" >
            <div ng-if ="login_form.$submitted" ng-messages="login_form.password.$error" style="color:maroon" role="alert">
                <div ng-message="minlength">Your field is too short</div>
            </div>
            <p ng-if="error">Username or login is incorrect</p>
        </form>
    </div>
    <div class=user>
        <form name = "register_form">
            <h2 class>Register</h2>
            <h3 class = "login_page">UserName</h3>
            <input ng-model="reg.name" type="text" required>
            <h3 class = "login_page">Password</h3>
            <input ng-model="reg.password" type="password">
            <input type="submit" value="Register" ng-click="register()" required >
            <div ng-if ="login_form.$submitted" ng-messages="login_form.password.$error" style="color:maroon" role="alert">
                <div ng-message="minlength">Your field is too short</div>
            </div>
            <p ng-if="duplicate">That user name is taken, please choose another</p>
            <p ng-if="correct">Registration Succesfull</p>
        </form>
    </div>
</div>

这是我在服务器端的控制器

var mongoose = require('mongoose'),
Todo = mongoose.model('Todo');
Login = mongoose.model('Login');
var bcrypt = require('bcrypt');
var name = ""

module.exports = (function(){
  return {
    save_name:function(req, res){
        req.session.user = req.body.user
      Login.findOne({name: req.body.user},
      function(err, user) {
        if(user){
          console.log(user.password);
            console.log( bcrypt.compareSync(req.body.password, user.password));
           res.json({'error': false}); 
          }else {
            res.json({'error': true});
          }
      })
    }, //end of save name method
    register:function(req, res){
      bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(8));
      login = new Login({
        name:req.body.user,
        password: bcrypt.genSaltSync(8)
      })
      login.save(function(err){
        if(err){
          res.json({'error': true});
        } else {
          res.json({'sucess': true})
        }
      })
    } // end of register user function
  } 
})();
jchrr9hc

jchrr9hc1#

您将生成的salt保存为密码,而不是实际的哈希本身。另外,显式调用genSalt*()是不必要的。最后,你真的应该使用异步函数,以避免不必要地阻塞事件循环。考虑到所有这些,你可能会得到这样的结果:

module.exports = {
  save_name: function(req, res) {
    req.session.user = req.body.user;
    Login.findOne({ name: req.body.user },
                  function(err, user) {
      if (err)
        return res.json({ error: true });
      bcrypt.compare(req.body.password,
                     user.password,
                     function(err, valid) {
        res.json({ error: !!(err || !valid) }); 
      });
    });
  }, // end of save name method
  register: function(req, res) {
    bcrypt.hash(req.body.password, 8, function(err, hash) {
      if (err)
        return res.json({ error: true });
      login = new Login({
        name: req.body.user,
        password: hash
      })
      login.save(function(err) {
        res.json({ error: !!err });
      })
    });
  } // end of register user function
};
htzpubme

htzpubme2#

尽管有其他答案,如果它仍然没有解决你的问题。尝试在登录时传递密码时应用toString(),如下所示。

req.body.password.toString();

zlhcx6iw

zlhcx6iw3#

你的bug的直接原因是在register中,你应该使用bcrypt.hashSync(myPlaintextPassword, saltRounds)而不是genSaltSync。解决这个问题应该让事情“工作”。
但是,您需要重新编码所有这些才能使用异步bcrypt API,否则您的应用程序在负载下的响应将非常差(像瘫痪和不可用,而不仅仅是“慢”)。一般规则:node.js服务器中没有同步调用。

vd2z7a6w

vd2z7a6w4#

这个片段对我有用。

userSchema.pre("save", function (next) {
  const password = this.password;
  const hashedPassword = bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
  this.password = hashedPassword;
  this.confirmPassword = undefined;
  next();
});

userSchema.methods.comparePassword = function (password, hash) {
  let isPasswordValid;
  isPasswordValid = bcrypt.compare(password, hash);
  return isPasswordValid;
};

相关问题