Async or Sync bcrypt function to use in node.js in order to generate hashes?

こ雲淡風輕ζ 提交于 2019-12-19 00:19:19

问题


I'm currently trying to make authentication module for my project in node.js?

I've already seen some examples of using bcrypt to generate hashes, i.e.

https://github.com/bnoguchi/mongoose-auth/blob/master/lib/modules/password/plugin.js https://github.com/Turbo87/locomotive-passport-boilerplate/blob/master/app/models/account.js

However, for some reason they are using bcrypt.hashSync() function. Since bcrypt is good because it's time-consuming, wouldn't it be wiser to use asynchronous function instead in order to not block the code, i.e:

User.virtual('password')
.get( function () {
    return this.hash;
})
.set( function (password) {
    bcrypt.hash('password', 10, function(err, hash) {
        this.hash = hash;
    });
});

Could you please explain me which way is better and why? Thank you!


回答1:


Yes, you'd want to use the async version if possible so you're not tying up your node processing during the password hash. In both source code cases you reference, the code is using the synchronous version because the method it's used within is synchronous so the author had no choice but to use the synchronous version.




回答2:


You can't make an async call inside of a synchronous method. Try making a separate method to use when setting the password.

I just submitted a pull request so someone's project that does exactly this. Check it out here: https://github.com/nickpoorman/CrowdNotes/commit/e268c80a9cacddbc0215bf0e2b7aa31c0a4c785f



来源:https://stackoverflow.com/questions/11605943/async-or-sync-bcrypt-function-to-use-in-node-js-in-order-to-generate-hashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!