简体   繁体   English

bcrypt.compare承诺始终返回false

[英]bcrypt.compare promise always returns false

I've looked through the other issues with bcrypt.compare on GitHub and none of the solutions have worked for me. 我在GitHub上浏览了bcrypt.compare的其他问题,但没有一个解决方案对我有用。 It always fails on console.log("failed 3") inside bcrypt.compare() 它总是在bcrypt.compare()中的console.log(“ failed 3”)上失败

I've tried switching the .then() instead of using a callback with bcrypt.compare as suggested by another post but that hasn't help. 我试图切换.then(),而不是像另一篇文章所建议的那样使用带有bcrypt.compare的回调,但这无济于事。 Any help would be greatly appreciated! 任何帮助将不胜感激!

Below is a copy of my code and summary of versions being used: 以下是我的代码副本和使用的版本摘要:

  • Node v8.12.0 节点v8.12.0
  • Express 4.16.0 快递4.16.0
  • bcrypt 3.0.3 bcrypt 3.0.3
  • jsonwebtoken 8.4.0 jsonwebtoken 8.4.0
  • mongoose 5.4.1 猫鼬5.4.1

Bcrypt Hash (Password Hashing) Bcrypt哈希(密码哈希)

function saveUserData(req, res, next, userSignUpInfo, info){
bcrypt.hash(req.body.email, 10, (err, hash) =>{ 
if (err){   
  return res.status(500).json({
    error: err
  })
} else {
  console.log('inside test route')
  console.log('req.body.fnUserName', userSignUpInfo.fnUserName)
  const userData = new UserData({
    fnUserName : userSignUpInfo.fnUserName,
    password : hash,
    email : req.body.email,
    verify: userSignUpInfo.verify,
    createAccountDate: userSignUpInfo.createAccountDate,
    userId : userSignUpInfo.userId,
    friends: null,
    online: null
    })
  userData.save()
    .then(result => {
      console.log('result from MongoDB Cloud', result);
      saveApiData(info, userSignUpInfo, res);
  })
  .catch(err => console.log('error from MongoDB Cloud', err));
}
})
}

Bcrypt Compare (Auth User) Bcrypt比较(身份验证用户)

    router.post('/login', (req, res, next) => {
    UserData.find({email: req.body.email})
    .exec()
    .then(user => {
      if(user.length < 1) {
        console.log("failed 1")
     return res.status(401).json({
      message: 'Authentication Failed'
    });
    }
    console.log('user[0].password', user[0].password)
    console.log(' user[0].password',  user[0].password)
    console.log(' req.body.password',  req.body.password)

    bcrypt.compare(req.body.password,user[0].password).then(function(err, result) {
    if (err) {
      console.log("failed 1")
      return res.status(401).json({
        message: 'Authentication Failed'

      });
    }
    if (result) {
      const token = jwt.sign(
        {
        email: user[0].email,
        userId: user[0].userId
        },
        process.env.JWT_KEY,
        {
          expiresIn: "1h"  // he suggested one hour
        }
      );
      console.log("failed 2")
      return res.status(200).json({
        message: 'Authentication Successful',
        token: token
      })
    } else {
      console.log("failed 3")
      res.status(401).json({
        message: 'Authentication Failed'
      })
    }
    })
    })
     .catch(err => {
     console.log('err in login', err);
     res.status(500).json({
      error: err,
      message: 'error logging in'
    })
     })
    });

Usually, password is saved as hash in the database. 通常,密码以哈希形式保存在数据库中。 Also, provide adequate length for saving hashes into database.(atleast 60 varchars). 另外,请提供足够的长度以将哈希值保存到数据库中(至少60个varchars)。 To do so, 为此,

schema.pre("save", function (next) {
    bcrypt.hash(this.password, 10, (err, hash) => {
        this.password = hash;
        next();
    });
});

Then, plain password is compared against the hash from database. 然后,将普通密码与数据库中的哈希进行比较。

bcrypt.hash('mypassword', 10, function(err, hash) {
    if (err) { throw (err); }
    bcrypt.compare('mypassword', hash, function(err, result) {
        if (err) { throw (err); }
        console.log(result);
    });
});

看起来您没有像在失败2块和失败1块中那样在else { console.log("failed 3")块中返回res.status。

result will always be undefined since promises return a single value and errors are simply thrown in the catch phrase. result永远是不确定的,因为promise返回单个值,并且错误只是在catch短语中抛出。 So basically, in your code, err will contain the actual result. 因此,基本上,在您的代码中,err将包含实际结果。
What your code should look like is the following: 您的代码应如下所示:

bcrypt.compare(req.body.password,user[0].password).then((result)=>{
  if(result){
    console.log("authentication successful")
    // do stuff
  } else {
    console.log("authentication failed. Password doesn't match")
    // do other stuff
  }
})
.catch((err)=>console.error(err))

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

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