【问题标题】:Bcrypt compare returns false randomly for correct passwords对于正确的密码,Bcrypt 比较随机返回 false
【发布时间】:2018-11-28 01:35:18
【问题描述】:

我在 MERN 项目(节点 v8.10.0)中使用 bcrypt (v2.0.1) 使用 Mongoose 在 MongoDB 中存储用户密码。哈希函数:

SellerSchema.pre('save', function (next) {
    var user = this;
    bcrypt.hash(user.password, 10, function (err, hash) {
      if (err) {
        return next(err);
      }
      user.password = hash;
      next();
    });
});

认证部分:

SellerSchema.statics.authenticate = function (email, password, callback) {
    Seller.findOne({ email: email })
      .exec(function (error, user) {
        if (error) return callback(error);
        else if (!user) {
          var err = new Error('User not found.');
          err.status = 401;
          return callback(err);
        }
        bcrypt.compare(password, user.password).then(function (result){
          if (result == true) {
            return callback(null, user);
          } else {
            return callback();
          }
        });
      });
}; 

登录路径:

router.post('/login', function(req, res, next) {
    if (req.body.email && req.body.password){ 
Seller.authenticate(req.body.email,req.body.password,function(error,user) {
    if (error || !user) {
        console.log("this "+error);
    var err = new Error('Wrong email or password.');  // logged everytime the compare result was false 
    err.status = 401;
    return next(err);
    }  else {
    res.json(user);
    }
});
} else {
var err = new Error('Email and password are required.');
err.status = 401;
return next(err);
}
});

在注册新用户时,哈希会被很好地存储,并且使用纯文本登录确实会通过 compare() 几次,但之后返回 false。

如果我注册一个新用户并登录,它会再次工作一段时间,然后开始返回 false。 例如:我仍然可以登录几小时前注册的用户(10-15 次比较),但无法登录几分钟前创建的用户(1-2 次比较后)

使用节点:8.10.0,操作系统:Ubuntu 18.04

【问题讨论】:

  • 你会用pre('save')钩子覆盖每个用户更新的密码,不是吗?
  • 等等,这个钩子会在每次查询更改文档后调用吗?我以为只有在我实际保存新用户时才会调用它。
  • 显然你必须检查if (this.isNew)

标签: node.js mongoose bcrypt


【解决方案1】:

您的pre('save') 中间件每次保存对象时都会更新密码。要停止这种情况,请使用猫鼬的isModified 函数,如下所示:

SellerSchema.pre('save', function(next) {
  if (this.isModified('password')) { // check if password is modified then has it
    var user = this;
    bcrypt.hash(user.password, 10, function(err, hash) {
      if (err) {
        return next(err);
      }
      user.password = hash;
      next();
    });
  } else {
    next();
  }
});

【讨论】:

    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2017-09-16
    相关资源
    最近更新 更多