Server initialization

Add the following line to your package.json file.

package.json

"scripts": {
"dev": "NODE_ENV=development nodemon index.js"
},

We’ll now start our server with the npm run dev command.

Every time we do this, development is automatically set as a value for the NODE_ENV key in our process object. The command nodemon index.js will allow nodemon to restart our server every time we make changes in our folder structure.

Let’s define the port we’ll have our server listen to in the config file.

In the above code, we connect to our mongodb database then access the name and password provided in the request by destructuring those properties from the request.body object. Remember, we can do this because of our bodyparser middleware.

Next we create a new user document by calling new on our model then in the same step add the name and password we got from the request to the new document.

We exploited mongoose’s pre hook and hashed our password in our users model but we could just as well have hashed it in our controller before we called user.save

Finally, we pass a callback function into user.save that will handle our errors and pass the user back to us in our server response. We attach a handy status property in our response to let us know if the result was successful or not.

Testing with Postman

I’m using Postman to test out my API functionality but you can use any request library or application you like. Heck, you can even use curl if you’re a console purist. Cue the XBox and Playstation fan boys and fan girls. Tada!

As you can see below, we can now create users by making POST requests to the /api/v1/users endpoint.

What’s that strange string as the value under the password key? Well, that’s our password in hash form. We store it this way because it’s safer. Hashes are ridiculously difficult to reverse.

Edit out the pre save hashing hook and see what happens. Don’t forget to put it back though. Perish the thought!

We’ll see how to verify that a user is who they say they are, using the password they give us later when we work on the /login route.

Here’s what happens when we try to create a user without specifying a password.

Above, we query our collection to find the user by their name. If we find them, we use bcrypt to compare the hash generated using the password they’ve given us and the hash that we’d previously stored. If we don’t find them, we send ourselves an error.

As you can see above, we can now log in our users. As an experiment, try logging in a user without a password or with an incorrect password and see what happens.

Adding Tokens to our authentication process

Let’s add the following import statement to our users controller then work on modifying our login controller to create tokens.

As mentioned before, we’ll use these to protect one of our routes from unauthorized access.

Once we verify that a user is who they say they are, we create a token and pass it to our server response. If something goes wrong, we pass back an error as the response.

Now, we get a token every time we successfully log in a user. Yaaay!

Express middleware

An express middleware function is a function that gets triggered when a route pattern is matched in our request uri. All middleware have access to the request and response objects and can call the next()function to pass execution onto the subsequent middleware function.

Believe it or not, we’ve written out several already. Don’t believe me? I’ll show you.

Bodyparser and morgan are both middleware that act on all our routes. When we call the app.use function without the specifying the first parameter, we’re esentially doing this:

app.use(bodyParser.json());
// This is equivalent to
app.use('/', bodyParser.json());
if (environment !== 'production') {
app.use(logger('dev'));
// and this
app.use('/', logger('dev'));
}
// Here, we've specified the pattern we'd like to be matched from our request's uri
app.use('/api/v1', (req, res, next) => {
res.send('Hello');
// We call next to hand execution over to the next middleware
next();
});

Hold that thought and for now, let’s create a controller function that will get all users from our users collection.

Have you noticed that our controllers are esentially middleware functions passed to our other routing middleware? Above we’ve just added middleware our controller that will handle GET requests made to /users. However, we haven’t protected our route yet.

If we make a GET request to /users, here’s what happens.

But we wouldn’t want just any user to access a list of all our users. So, let’s create an admin user then check if they have a token before we allow access to this functionality.

Now, finally, let’s write out middleware to validate that a user has a valid token (issued by us and not expired) before we allow access to certain routes on our application.

Let’s add our function to our router so that it’s called before our getAll controller. If validateToken throws an error, controller.getAll won’t be called. Also, if it sends a response with an error, since we haven’t called next in our else block, getAll won’t be called either.