【问题标题】:mongoose and bcrypt-nodejs not hashing and saving password猫鼬和 bcrypt-nodejs 不散列和保存密码
【发布时间】:2017-06-26 18:44:43
【问题描述】:

我正在使用 bcrypt-node 和 mongoose 来散列用户密码并将该用户保存到 mongo 数据库。当我调试下面的代码时,它似乎工作正常,当您在代码中记录密码时,它显示它是散列的,但是当您检查数据库时,它仍然是纯文本。我对 node 和 mongoose/mongodb 比较陌生,所以我不确定如何排除故障。我已经尝试按照另一篇文章中的建议将呼叫next(); 更改为return next(user);,但这并没有帮助。任何帮助将不胜感激。

我正在使用节点版本 6.9.5、mongoose 4.7.0、bcrypt-nodejs 0.0.3 和 mongo 3.2.10

 UserSchema.pre('save', function (next) {  
      var user = this;
      if (user.password != "") {
        if (this.isModified('password') || this.isNew) {
          bcrypt.genSalt(10, function (err, salt) {
            if (err) {
          return next(err);
        }
        bcrypt.hash(user.password, salt, null, function(err, hash) {
          if (err) {
            return next(err);
          }
          console.log(hash);
          user.password = hash;
          console.log(user.password);
          next();
        });
      });
    } else {
      return next();
    }
  }
  return next();
});

【问题讨论】:

  • 请使用一致且有意义的缩进。
  • 抱歉,在我的屏幕上,缩进看起来很正常。
  • 对比答案中的代码。
  • @zaph,我理解这种情绪,但也许这不是最有建设性的评论。它给人的印象是相当居高临下的。干杯。
  • OP 没有看到缩进问题,并且答案是正确缩进的,这就是我的观点。几乎不可能在评论中说明缩进。

标签: node.js mongodb


【解决方案1】:

您将散列函数置于 genSalt() 函数之外。此外,您使用了一些难以理解的嵌套和条件。尝试以下操作,看看它是如何工作的。

UserSchema.pre('save', function(next) {
  const user = this;
  if (!user.isModified('password')) {
    return next();
  }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, null, (error, hash) => {
      if (error) {
        return next(error);
      }
      console.log('HASH: ', hash);
      user.password = hash;
      console.log('USER.PASSWORD: ', user.password);
      next();
    });
  });
});

更具可读性,对吧?

【讨论】:

  • 谢谢你,成功了。当看到你的代码时,我能够看到我的代码看起来有多糟糕。长时间盯着我的代码看,很难看出它的格式不正确。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2017-08-19
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 2016-03-23
  • 1970-01-01
  • 2019-09-21
相关资源
最近更新 更多