简体   繁体   English

Bcrypt.compare()仅返回false,在承诺下使用

[英]Bcrypt.compare() returning only false, Used Under Promises

I am using Bcrypt for hashing passwords and storing it in the database, 我正在使用Bcrypt哈希密码并将其存储在数据库中,

Bcrypt is returning false, when I retrieve the hashed password from the database, and compare with the typed user password. 当我从数据库中检索散列密码并将其与键入的用户密码进行比较时,Bcrypt返回false。

I am using it under Promise, but bcrypt is returning false on the correct password 我在Promise下使用它,但是bcrypt使用正确的密码返回false

Here is the code: 这是代码:

userSchema.statics.findByCredentials = function(email, password) {
const User = this;

return User.findOne({email}).then((user) => {
    if(!user) {
        return Promise.reject();
    }
    // console.log(user.password);

    return new Promise((resolve, reject) => {
        bcrypt.compare(password, user.password, (err,res) => {
             if(res) {
                 resolve(user);
             }
             else {
                 reject("Problem here");
             }
            console.log(res);

        });            
    });
});

}; };

I am trying promise chain to the main file ie server.js and return the details to the user, but it's not working. 我正在尝试将诺言链链接到主文件(即server.js),并将详细信息返回给用户,但是它不起作用。

Here is the route code of express: 这是快递的路线代码:

app.post('/users/login', (req, res) => {
const body = _.pick(req.body, ['email', 'password']);
// res.send(body);

User.findByCredentials(body.email, body.password)
    .then((user) => {
        res.send(user);
    }).catch((e) => res.send(e));

}); });

Thanks 谢谢

Have you tried using the promise api for bcrypt ? 您是否尝试过将诺言API用于bcrypt

It might look like this: 它可能看起来像这样:

userSchema.statics.findByCredentials = function(email, password) {
  const User = this;

  return User.findOne({email}).then((user) => {
      if(!user) {
          return Promise.reject();
      }
      // console.log(user.password);

      return bcrypt.compare(password, user.password)
        .then(res => {
          if (res) {
            return user;
          }
          throw new Error('Problem here');
        });
  });
}

If not, you might be getting an error, so you could check the err argument to see if something came back from there. 如果不是,则可能会出现错误,因此可以检查err参数以查看是否从那里回来。 Other than that, as long as user.password is the hashed version of the original password, then it should be working. 除此之外,只要user.password是原始密码的哈希版本,那么它应该可以正常工作。

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

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