8

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!

Andrey Elenskiy
  • 129
  • 1
  • 6

3 Answers3

8

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 3
    +1, async is definitely the right choice; one thing to keep in mind when using an ODM like Mongoose is that getters and setters can't be asynchronous, so some authors will use synchronous methods inside them instead. This is generally the wrong move; in the past, I've used a custom method on the model like `setPassword` to do the async password set. – Michelle Tilley Jul 23 '12 at 05:35
  • @BrandonTilley can you give an example of your custom method? – Steve Lorimer Dec 16 '13 at 06:56
  • 3
    @lori Oh man, it's been a while since I posted this, but something like this seems close: https://gist.github.com/BinaryMuse/7983335 – Michelle Tilley Dec 16 '13 at 07:05
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

poorman
  • 120
  • 7
0

Here's a benchmark that shows async hash() is 2.3x faster than synchronous hashSync(): https://jinoantony.com/blog/async-vs-sync-nodejs-a-simple-benchmark

I don't really know what's the reason for this speed-up given that the function is strictly CPU-bound, no I/O. Maybe the async version is able to utilize multiple cores under the hood? This could be a likely explanation. I ran this benchmark myself and got a consistent 4x speed-up on a machine with 8 cores.

Marcin Wojnarski
  • 2,362
  • 24
  • 17