簡體   English   中英

mongoose 和 bcrypt-nodejs 不散列和保存密碼

[英]mongoose and bcrypt-nodejs not hashing and saving password

我正在使用 bcrypt-node 和 mongoose 來散列用戶密碼並將該用戶保存到 mongo 數據庫。 當我調試下面的代碼時,它似乎工作正常,當您在代碼中記錄密碼時,它顯示它是散列的,但是當您檢查數據庫時,它仍然是純文本。 我對 node 和 mongoose/mongodb 比較陌生,所以我不確定如何進行故障排除。 我試過改變調用next(); return next(user); 正如另一篇文章中所建議的那樣,但這沒有幫助。 任何幫助將不勝感激。

我正在使用節點版本 6.9.5、貓鼬 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();
});

您將哈希函數放在 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();
    });
  });
});

更具可讀性,對吧?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM