简体   繁体   English

尝试在异步函数中使用 bcrypt 散列密码

[英]Trying to hash a password using bcrypt inside an async function

Following on from this question .这个问题开始

I feel like I'm almost there, but my incomplete understanding of async is preventing me from solving this.我觉得我快到了,但我对异步的不完整理解阻止了我解决这个问题。 I'm basically trying to just hash a password using bcrypt and have decided to seperate out the hashPassword function so that I can potentially use it in other parts of the app.我基本上只是尝试使用 bcrypt 对密码进行哈希处理,并决定将 hashPassword 函数分开,以便我可以在应用程序的其他部分使用它。

hashedPassword keeps returning undefined though...虽然hashedPassword一直返回未定义...

userSchema.pre('save', async function (next) {

  let user = this
  const password = user.password;

  const hashedPassword = await hashPassword(user);
  user.password = hashedPassword

  next()

})

async function hashPassword (user) {

  const password = user.password
  const saltRounds = 10;

  const hashedPassword = await bcrypt.hash(password, saltRounds, function(err, hash) {

    if (err) {
      return err;
    }

    return hash

  });

  return hashedPassword

}

await dosent wait for bcrypt.hash because bcrypt.hash does not return a promise. await dosent 等待bcrypt.hash因为bcrypt.hash不返回承诺。 Use the following method, which wraps bcrypt in a promise in order to use await .使用以下方法,它将bcrypt包装在一个 promise 中以便使用await

async function hashPassword (user) {

  const password = user.password
  const saltRounds = 10;

  const hashedPassword = await new Promise((resolve, reject) => {
    bcrypt.hash(password, saltRounds, function(err, hash) {
      if (err) reject(err)
      resolve(hash)
    });
  })

  return hashedPassword
}

Update:-更新:-

The library has added code to return a promise which will make the use of async/await possible, which was not available earlier.该库添加了代码来返回一个 promise,这将使async/await的使用成为可能,这在之前是不可用的。 the new way of usage would be as follows.新的使用方式如下。

const hashedPassword = await bcrypt.hash(password, saltRounds)

By default, bcrypt.hash(password,10) will return as promise.默认情况下, bcrypt.hash(password,10)将作为承诺返回。 please check here请检查这里

Example: Run the code,示例:运行代码,

var bcrypt= require('bcrypt');

let password = "12345";


var hashPassword = async function(){
    console.log(bcrypt.hash(password,10));
    var hashPwd = await bcrypt.hash(password,10);
    console.log(hashPwd);
}

hashPassword();

Output:输出:

Promise { <pending> }
$2b$10$8Y5Oj329TeEh8weYpJA6EOE39AA/BXVFOEUn1YOFC.sf1chUi4H8i

When you use await inside the async function, it will wait untill it get resolved from the promise.当您在 async 函数中使用await ,它会一直等到它从 promise 中得到解决。

使用方法 bcrypt.hashSync(),它是同步开箱即用的。

const hashedPassword = bcrypt.hashSync(password,saltRounds);

Hashing bcrypt asynchronously should be like this异步散列 bcrypt 应该是这样的

bcrypt.hash(password, saltRounds, function(err, hash) {
  if (err) {
     throw err;
  }
  // Do whatever you like with the hash
});

If you are confused with sync and async.如果您对同步和异步感到困惑。 You need to read more about them.你需要阅读更多关于它们的信息。 There are a lot of good articles out there.那里有很多好文章。

You need to look here in the documentation.您需要在文档中查看此处

Async methods that accept a callback, return a Promise when callback is not specified if Promise support is available.如果 Promise 支持可用,则接受回调的异步方法在未指定回调时返回 Promise。

So, if your function call takes in a callback then you can't use await on it since this function signature doesn't return a Promise .因此,如果您的函数调用接受回调,则不能对其使用await ,因为此函数签名不返回Promise In order to use await you need to remove the callback function.为了使用await您需要删除回调函数。 You can also wrap it in a Promise and await on it but that's a bit overkill since the library already provides a mechanism to do so.您也可以将它包装在Promiseawait它,但这有点矫枉过正,因为库已经提供了一种机制来这样做。

Code refactor:代码重构:

try {
   // I removed the callbackFn argument
   const hashedPassword = await bcrypt.hash(password, saltRounds)
} catch (e) {
   console.log(e)
}
const hashedPassword = (password, salt) => {
    return new Promise((resolve, reject) => {
        bcrpyt.hash(password, salt, (err, hash) => {
            if (err) reject();
            resolve(hash);
        });
    });
};
hashedPassword('password', 10).then((passwordHash) => {
    console.log(passwordHash);
});

Had same issue... solved by assigning the Boolean value from a function:有同样的问题...通过从函数分配布尔值来解决:

compareHash = (password, hashedPassword) => {
if (!password || !hashedPassword) {
  return Promise.resolve(false);
}
return bcrypt.compare(password, hashedPassword);
 };

Here the 2 arguments will not be undefined, which is the cause of issue.这里的 2 个参数不会是未定义的,这是问题的原因。 And calling the function:并调用函数:

let hashCompare = this.compareHash(model.password, entity.password);

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

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