【问题标题】:Bcrypt compare always returning TRUE in NodeJSBcrypt比较在NodeJS中总是返回TRUE
【发布时间】:2021-11-25 03:33:43
【问题描述】:

我正在制作自己的小型 API,并且我已将以下 POST 请求编码到我的 MongoDB 数据库中:

api.post("/account/login", async (req, res) => {

    const user = {
        username: req.body.username,
        password: req.body.password
    };

    const username = JSON.stringify(user.username);

    const hashedPassword = await logincollection.find(user.username).toArray();
    const hardCodedPassword = "$2b$10$q0iOBFTqqZ3vnp5oqDQUqejdS7UD/ayw4Q4qgi5hs1pfFI.xfipDS"
    console.log(hashedPassword)

    // Search for matching login credentials
    logincollection.find(user, (err, result) => {

        try {

            if (bcrypt.compare(req.body.password, hardCodedPassword)) {
            
                // Return credentials back to the client
                const sendObject = {
                    username: result.username,
                    password: result.password
                };

                console.log(sendObject);
                    
                // Return code 200 (success) to the client
                res.status(200).send(sendObject);

                // Log to console when user logs in
                console.log("User " + username + " logged in");

            }

        } catch(error) {

            // If matching credentials were not found, return code 404 (wrong credentials) to the client
            res.status(404).send()

        }

    })

})

我设置了一个有效的硬编码密码,用于纯粹的测试目的。处理此请求时,console.log(sendObject) 将未定义的结果打印到控制台,bcrypt 返回true,无论我输入什么密码。这里有什么问题?

【问题讨论】:

  • 比较不返回布尔值。它返回一个 promise,这是真的。

标签: node.js bcrypt


【解决方案1】:

正如@jonrsharpe 所说,bcrypt.compare 返回一个 Promise 而不是一个值。您必须使用回调函数 Promise.then() 或 async/await 来处理异步结果。

// Search for matching login credentials
logincollection.find(user, (err, result) => {

  bcrypt.compare(req.body.password, hardCodedPassword)
  .then(match => {      
    if (match) {
      // Return credentials back to the client
      const sendObject = {
          username: result.username,
          password: result.password
      };

      console.log(sendObject);
          
      // Return code 200 (success) to the client
      res.status(200).send(sendObject);

      // Log to console when user logs in
      console.log("User " + username + " logged in");          
    } else {
      // If matching credentials were not found, return code 404 (wrong credentials) to the client
      res.status(404).send()          
    }
  })
  .catch(error => {
    res.status(500).send()
  })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多