DEV Community

Cover image for Safely Storing Passwords in mongoDB Using  Bcrypt and a mongoose middleware.
Ajulibe
Ajulibe

Posted on

Safely Storing Passwords in mongoDB Using Bcrypt and a mongoose middleware.

Hey there.
Maybe you landed here mistakenly or you are interested in figuring out how to safely hash user passwords and store it in your database, you are definitely in the right place. I will try to make this as concise as possible because i know these things can get out of hand real quick.

AIM:

The aim here is to make use of the document middleware from mongoose's library to perform a hashing operation on our password field, before it is stored in our mongoDB database. In mongoose there are 4 middlewares and here, we will be making use of the document "save" middleware.

I am running with the assumption that you have a basic mongoDB/mongoose and express server already setup.

If not, you can check out mdn's basic express setup here
https://developer.mozilla.org/enUS/docs/Learn/Serverside/Express_Nodejs/development_environment

And here for a mongoDb mongoose setup
https://developer.mozilla.org/enUS/docs/Learn/Serverside/Express_Nodejs/mongoose

Okay, Enough with the boring theory lets do some work...

First, we will install bcrypt using npm install bcryptjs

Require it like we do with all our modules
var bcrypt = require('bcryptjs');

In your schema file, just before creating your model add.

Alt Text

Your complete schema file should look like this.

Alt Text

Finally, this is my registration route in my route file.

Alt Text

LOGIC:

What happens here is, whenever this schema is called through its model (by going to the users registration route) , lets say we are registering a user, the middleware scans the request body to see if there is a password in it. If a password is present, it hashes it using the bcrypt algorithm.

Also, whenever the password is modified, maybe during a password change or an update, the middleware performs the same hashing operation. In essence, the middleware serves as a middle man between an incoming request and the action to be performed on the request object.

For a more in-depth understanding of the backdoor operations of either bcrypt or mongoose you can check out their documentation.

Top comments (4)

Collapse
 
pixsaoj profile image
Pixsa

How would you add salt to this?

Collapse
 
jhdcruz profile image
Joshua Hero

I believe the Number 8 after user.password is the salt.

Collapse
 
waellomari profile image
Waell Omari

Number 8 is the cost

Collapse
 
saikat_chatterjee profile image
Saikat Chatterjee

Thank You