Node.js with bcrypt
As we saw in the previous article about how to register a user with mongodb, in this lesson we will see how to to use Bcrypt
for secure password by hashing it
What is BCrypt
bcrypt is a password-hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher and presented at USENIX in 1999
Let’s head back to our server and register router, but first of all let’s importing bcrypt And the User model:
before our register route was like this
as you notice password was been saved plain in Database and isn’t the best practice to do so, we will modify our route to hash our password before save it in to Database
Let’s use bcrypt to salt and hash our new user’s password before storing it in the database and saving the user (make sure to put this in the ‘else’ statement in the previous code block):
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err));
})
})
will looks like this
Let’s try our new changes to check bcrypt with postman…
if you you followed all the instructions above you will get response back like this…
as you see our password been hashed and secured also checking your Atlas cluster, you should see that is has automatically created a users collection. When you click on this you should see that the user you just created now exists in the database.