• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 2/21/22

Prepare the Database for Authentication Info

Understand Safe Password Storage

Over the following few chapters, we will be implementing email and password-based authentication to the API. This means storing user passwords in the database. Never keep them as plain text: anyone with access to the database could get a complete list of everyone's login information. So instead, let's store each user's password as a hash or encrypted string.

We will use the  bcrypt  encryption package. It uses a one-way algorithm to encrypt and create a hash of user passwords, which you can store in that user's database document. When a user tries to sign in, use  bcrypt  to create a new hash with the entered password and then compare it to the hash stored in the database. These two hashes will not be the same — that would be insecure, and hackers could guess passwords until the hashes matched. Thankfully,  bcrypt  can tell if both hashes were generated using the same initial password, allowing you to implement safe and secure storage and verification.

The first step in implementing authentication is to create a database model for user information.

Create a User Model

Let see in this next video how to create a user model!

Use the  unique  keyword to make sure that two users cannot use the same email address.  However, the default errors thrown by MongoDB can be tricky, so to make your life easier, install a validation package to pre-validate information before saving:

npm install mongoose-unique-validator

With that package installed, you can now build your user model:

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

userSchema.plugin(uniqueValidator);

module.exports = mongoose.model('User', userSchema);

The  unique  value in the schema and the  mongoose-unique-validator  passed as a plugin will ensure that no two users can share the same email address.

Let's Recap!

  • bcrypt  is a secure encryption package you can install with  npm  .

  • mongoose-unique-validator  is a package that improves error messages when validating unique data .

Now that your model is ready, we will start using it to save new users to the database, and to enforce password encryption.

Example of certificate of achievement
Example of certificate of achievement