簡體   English   中英

嘗試在異步函數中使用 bcrypt 散列密碼

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

這個問題開始

我覺得我快到了,但我對異步的不完整理解阻止了我解決這個問題。 我基本上只是嘗試使用 bcrypt 對密碼進行哈希處理,並決定將 hashPassword 函數分開,以便我可以在應用程序的其他部分使用它。

雖然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 等待bcrypt.hash因為bcrypt.hash不返回承諾。 使用以下方法,它將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
}

更新:-

該庫添加了代碼來返回一個 promise,這將使async/await的使用成為可能,這在之前是不可用的。 新的使用方式如下。

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

默認情況下, bcrypt.hash(password,10)將作為承諾返回。 請檢查這里

示例:運行代碼,

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

輸出:

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

當您在 async 函數中使用await ,它會一直等到它從 promise 中得到解決。

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

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

異步散列 bcrypt 應該是這樣的

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

如果您對同步和異步感到困惑。 你需要閱讀更多關於它們的信息。 那里有很多好文章。

您需要在文檔中查看此處

如果 Promise 支持可用,則接受回調的異步方法在未指定回調時返回 Promise。

因此,如果您的函數調用接受回調,則不能對其使用await ,因為此函數簽名不返回Promise 為了使用await您需要刪除回調函數。 您也可以將它包裝在Promiseawait它,但這有點矯枉過正,因為庫已經提供了一種機制來這樣做。

代碼重構:

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

有同樣的問題...通過從函數分配布爾值來解決:

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

這里的 2 個參數不會是未定義的,這是問題的原因。 並調用函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM