简体   繁体   English

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

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

I'm using a bcrypt-node and mongoose to hash a users password and save that user to a mongo database.我正在使用 bcrypt-node 和 mongoose 来散列用户密码并将该用户保存到 mongo 数据库。 When I debug the code below it appears to be working correctly, when you log the password in the code it shows it hashed, but when you check the database it's still plain text.当我调试下面的代码时,它似乎工作正常,当您在代码中记录密码时,它显示它是散列的,但是当您检查数据库时,它仍然是纯文本。 I'm relatively new to node and mongoose/mongodb so I'm not sure how to troubleshoot.我对 node 和 mongoose/mongodb 比较陌生,所以我不确定如何进行故障排除。 I've tried changing calling next();我试过改变调用next(); to be return next(user); return next(user); as suggested in another post but that didn't help.正如另一篇文章中所建议的那样,但这没有帮助。 Any help would be greatly appreciated.任何帮助将不胜感激。

I'm using node version 6.9.5, mongoose 4.7.0, bcrypt-nodejs 0.0.3 and mongo 3.2.10我正在使用节点版本 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();
});

You placed the hash function outside the genSalt() function.您将哈希函数放在 genSalt() 函数之外。 Also, you used some nesting and conditionals that made it hard to follow.此外,您使用了一些难以遵循的嵌套和条件。 Try the following and see how it works.尝试以下操作,看看它是如何工作的。

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

A lot more readable, right?更具可读性,对吧?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM