Spencer FengSpencer Feng

Authentication in React Apps with JWT: Part 3

This is the third part of our ‘Authentication and Authorisation in React Apps with JSON Web Tokens’ series. In this part, we will do some work on our server side:

  • Setup the database connection
  • Create the User model
  • Install the Passport package and the jsonwebtoken package

Setup the database connection

I have created a sandbox database in mLab. mLab is a Database-as-a-Service for MongoDB and it offers a sandbox plan which is ideal for learning, developing and prototyping. Then, I will use Mongoose, a MongoDB object modeling tool, to establish the connection between our server and the MongoDB database.

Let’s run the command below to install the mongoose package:

$ npm install mongoose --save

When we set up the database connection, we need to provide the standard MongoDB URI which contains the sensitive information such as the username and password of our database, so it’s better to save the information in a .env file which is not committed to version control. Luckily, the dotenv package allows us just to do that.

Let’s install it by running the following command:

$ npm install dotenv --save

Then, create a .env file in the root directory and then open that file to add the MONGODB_URI variable and its value to it:

MONGODB_URI='your-standard-mongodb-uri'

The standard MongoDB URI can be grabbed from there:

Great, we have completed the preparation for connecting to the database. Then, let’s add the following code to the ‘bin/www’ file:

require('dotenv').config();
var mongoose =  require('mongoose');
// connect to the database
mongoose.connect(process.env.MONGODB_URI, { useMongoClient: true });
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => {
  console.error('mongoodb error: ' + err.message);
});

The first block of code requires and configures dotenv, so that process.env now has the key and value we defined in the .env file.

The second block of code requires mongoose.

The third block of code connects to our database, asks mongoose to use ES6 native promises for its async operations, like .save() and queries and display an error message if connections fails.

Create the User model

Next, we need to create the User model which is used to store the logged-in user. Models are defined by passing a Schema instance to mongoose.model. Let’s create a folder called ‘models’ in the root directory and then create a file called ‘User.js’ with the code below.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');

// create a schema
const userSchema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true 
    },
    email: {
        type: String,
        required: true 
    },
    password: {
        type: String,
        required: true
    }
});

// generating a hash
userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is correct
userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
};

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

As you can see, in the above code, we create a model with 4 required properties and they are ‘firstName’, ‘lastName’, ’email’ and ‘password’. We also a method to hash the password and a method to validate the password which utilise the ‘bcrypt-nodejs’ package, so we need to install this package as well by running the command below:

$ npm install bcrypt-nodejs --save

And then, we are going to import the User model in our app.js, since we will use it later.

// import models
let User = require('./models/User');

Install the Passport package and the jsonwebtoken package

In the last section, we will install 3 packages which we will use later in this series.

The first one is passport.js which is a very popular authentication middleware for Node.js and it is very flexible and does the heavy-lifting for us when implementing an authentication system in a Node.js application. Let’s run the command below to install passport.js:

$ npm install passport --save

passport.js has a comprehensive set of strategies which support authentication using a username and password, Facebook, Twitter, and more.

In our application, we will use a username and password to authenticate and it is called ‘passport-local’ strategy. So the second package need to install is ‘passport-local’:

$ npm install passport-local --save

The third package we need to install is the ‘jsonwebtoken’ package which does a lot of weight-lifting work for us when using JSON Web Tokens in our application, such as sign a token and verify a token.

$ npm install jsonwebtoken --save

Ok, that is all for today. In the next tutorial in this series, we will work on the signup process.

View the source code for this tutorial on GitHub.

Please sign up to our Newsletter if you want to get notified when new tutorials are available.

×