Step 20
Let's fix a huge security risk in our application!
You should never store users' password in a database! You must encode the password and store the encoded version.
We are going to follow the recommendation made in How To Safely Store A Password which essentially recommends using the bcrypt password-hashing function.
Stop the application and install the bcrypt package:
npm install bcrypt
Import the package in index.js
:
const bcrypt = require("bcrypt");
Update where you create and save user:
- const user = await users.create({ username, password });
+ const hash = await bcrypt.hash(password, 10);
+ const user = await users.create({ username, password: hash });
Notice the 10
is the value for "salt round" which is the cost factor in BCrypt algorithm. The cost factor controls how much time is needed to calculate a single BCrypt hash. The higher the cost factor, the more hashing rounds are done. Increasing the cost factor by 1 doubles the necessary time. The more time is necessary, the more difficult is brute-forcing.
Save index.js
and run the application again. Go to registration page and create a new user account. I created a user with username ali
and password 1234
and this is what is now stored in the database:
{
_id: '5facb6581128743f8c9f7a8c',
username: 'ali',
password: '$2b$10$FGpyplYOqntwbNJNvfKy1efZA1LGSTOn3H9gemDVOVlwf3KqWnIle',
__v: 0
}
When you authenticate user, you need to use the bcrypt
package:
- const user = await users.findOne({ username, password });
+ const user = await users.findOne({ username });
if (!user) throw Error("No user found with this username!");
+ const authorized = bcrypt.compare(password, user.password);
+ if (!authorized) throw Error("Invalid password!");
Save index.js
and ensure you can login with the credential you have created after adding bcrypt to this application.
Another potential addition to our Users App is a process to validate password complexity to enforce users provide strong passwords. There are node packages that help you with this, for example joi-password-complexity, which I encourage you to explore on your own.
The complete application is here: https://github.com/cs280fall20/users-app.