【问题标题】:Setting up bcrypt to work with Passport and async-await Node.js library设置 bcrypt 以使用 Passport 和 async-await Node.js 库
【发布时间】:2016-11-04 12:05:47
【问题描述】:

我正在使用 yortus 的 async/await node.js 库来设置基于 Passport 的登录/注册系统,密码使用 bcrypt-nodejs 散列。

虽然系统的其余部分已设置并正常运行,但我无法让 bcrypt-nodejs 与 yortus 的 async/await 很好地工作,因为 bcrypt 散列函数签名需要两个回调,并且不清楚如何使用它async/await...

hash(data, salt, progress, cb)
    data - [REQUIRED] - the data to be encrypted.
    salt - [REQUIRED] - the salt to be used to hash the password.
    progress - a callback to be called during the hash calculation to signify progress
    callback - [REQUIRED] - a callback to be fired once the data has been encrypted.
        error - First parameter to the callback detailing any errors.
        result - Second parameter to the callback providing the encrypted form.

async/await 电话...

let generateHash = async((password) => {
    let salt = await(bcrypt.genSaltAsync(10)) // this works
    let result = await(bcrypt.hash(password, salt, null)
    return result // returns NULL
})

输出:

Unhandled rejection No callback function was given.

我尝试使用系统注册时的数据库条目(MongoDB):

{
    "_id" : ObjectId("581bf7031386f167a09851b9"),
    "username" : "vjk2005",
    "password" : ""
}

用户名通过但密码为NULL。我已经尝试了许多排列和组合但没有成功,感谢任何帮助。

【问题讨论】:

    标签: javascript node.js asynchronous passport.js bcrypt


    【解决方案1】:

    我建议只使用babel 和常规async/await 关键字或Node 7 上的--harmony-async-await 标志。这会使代码更简洁,而且我认为很少有人使用该库。他们接受了这个想法并将其变成了语言的一部分。

    即使你使用那个库,它也需要promisified 函数而不是那些使用回调的函数。您可以使用 pify 模块或找到一个承诺的 bcrypt。始终在 npmjs.com 或 npms.io 上搜索。搜索类似“bcrypt promise”。

    import {hash} from 'bcrypt-as-promised';
    
    const generateHash = async password => await hash(password, 10);
    
    generateHash('abc1234').then(console.log).catch(console.error);
    

    或者由于您可以像这样自动生成盐,您可以将其简化为:

    import {hash} from 'bcrypt-as-promised';
    
    hash('abc123',10).then(console.log).catch(console.error);
    

    【讨论】:

    • 我实际上是在使用 Bluebird 来承诺 bcrypt 库。我将保留和谐和通天作为我最后的手段。
    猜你喜欢
    • 2019-01-29
    • 2018-11-27
    • 2015-09-29
    • 1970-01-01
    • 2019-09-22
    • 2013-10-31
    • 2017-10-15
    • 2017-05-29
    • 2019-05-30
    相关资源
    最近更新 更多