【问题标题】:bcrypt.compare promise always returns falsebcrypt.compare 承诺总是返回 false
【发布时间】:2019-05-27 19:20:48
【问题描述】:

我在 GitHub 上查看了 bcrypt.compare 的其他问题,但没有一个解决方案对我有用。它总是在 bcrypt.compare() 内的 console.log("failed 3") 上失败

我已尝试切换 .then() 而不是按照另一篇帖子的建议使用带有 bcrypt.compare 的回调,但这没有帮助。任何帮助将不胜感激!

以下是我的代码副本和正在使用的版本摘要:

  • 节点 v8.12.0
  • Express 4.16.0
  • bcrypt 3.0.3
  • jsonwebtoken 8.4.0
  • 猫鼬 5.4.1

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 比较(验证用户)

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

【问题讨论】:

    标签: javascript node.js express jwt bcrypt


    【解决方案1】:

    通常,密码以哈希的形式保存在数据库中。此外,为将哈希值保存到数据库中提供足够的长度。(至少 60 个 varchars)。为此,

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

    然后,将普通密码与数据库中的哈希值进行比较。

    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】:

      result 将始终未定义,因为 Promise 返回单个值并且错误只是简单地抛出在流行语中。所以基本上,在您的代码中,err 将包含实际结果。
      您的代码应如下所示:

      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))
      

      【讨论】:

      • 很好 @omarwaleed ,更新了代码 b/c 这更干净,但我仍然有同样的问题。还有其他想法吗? bcrypt.compare(req.body.password, user[0].password).then((result) =&gt; { if (result) { console.log("failed 2") return res.status(200).json({ message: 'Authentication Successful', }) } else { console.log("failed 3") return res.status(401).json({ message: 'Authentication Failed' }) } }) }) .catch((err) =&gt; { console.log('err in login', err); res.status(500).json({ error: err, message: 'error logging in' }) })
      • 谢谢伙计。好的,请您编写用于创建哈希的代码。我开始考虑密码本身的散列可能包含一些错误。请将其添加到问题中,以免代码格式丢失
      • 我也是这么想的。我刚刚添加了用于散列的代码。我是节点新手,我也有快速验证器和会话正在运行。我也觉得这可能是个问题?
      • 您正在对电子邮件而不是密码进行哈希处理
      • 不用担心 :) 如果问题得到解决,请接受最能帮助您解决问题的答案 :)
      【解决方案3】:

      看起来你没有在里面返回你的 res.status else { console.log("failed 3") block 就像你在失败的 2 和失败的 1 块中所做的那样。

      【讨论】:

      • 好眼光,但我仍然遇到同样的错误:(
      猜你喜欢
      • 2019-12-08
      • 1970-01-01
      • 2019-05-05
      • 2021-09-29
      • 2014-05-30
      • 2022-10-23
      • 2021-11-27
      相关资源
      最近更新 更多