Building a JavaScript Auth system using TDD (part 1)
Tags: javascript, node, authentication, tdd
Published: 2018-10-22 13:38:57

---
title: Building a JavaScript Auth system using TDD (part 1)
published: true
description: A step by step guide to build an authentication system for your Node.js apps following a TDD approach
tags: javascript, node.js, authentication, tdd
---

<p>Every time I want to learn a new programming language or framework I try do a couple of basic apps, like a to do list and then move to something I can reuse in future projects, like a user registration and authentication system. In this article I'll explain how to create an authentication system in JavaScript with an API (built with Express) that uses Json Web Tokens (JWT). In addition, I'll be following a Test Driven Develoment approach using a Mocha as a test framework and Chai as the assertion library.&nbsp;</p><p>TDD has a lot of benefits when creating a new project as it help us identify errors faster (fail fast), which will help us with continuous integration/delivery and, in addition, the tests will serve as documentation of the application. You can read more about the benefits of TDD in the <a href="https://www.madetech.com/blog/9-benefits-of-test-driven-development" title="Benefits of Test Driven Development" target="_blank">following article</a>.</p><p>The basic steps to follow when using TDD are:</p><ul><li>Requirement is translated to a test</li><li>Run and fail the test</li><li>Write the code</li><li>Run and pass the test</li><li>Refactor the code / pass test again</li><li>Repeat</li></ul><p>You can find all the code of this article (tests included) in&nbsp;<a href="https://gitlab.com/uF4No/authsysjs/tree/article-part-1" title="Repository with the code" target="_blank" style="background-color: rgb(255, 255, 255);">the following repository in GitLab</a>.</p><p>Let's go!</p><h3>Setup</h3><p>As usual, I started a node application with<strong> $npm init</strong> which creates the package.json for the app. Find below a list of all the modules our app will require in this first part:</p><ul><li><a href="https://www.npmjs.com/package/express" target="_blank">express</a>: framework for our app</li><li><a href="https://www.npmjs.com/package/body-parser" title="body parser in NPM" target="_blank">body-parser</a>: middleware to handle incoming requests as JSON.</li><li><a href="https://www.npmjs.com/package/mocha" title="Mocha in NPM" target="_blank" style="background-color: rgb(255, 255, 255); font-size: 1rem;">mocha</a>: test framework.<br></li><li><a href="https://www.npmjs.com/package/chai" title="chai in NPM" target="_blank">chai</a>: assertion library for mocha.</li><li><a href="https://www.npmjs.com/package/chai-http" title="chai-http in NPM" target="_blank">chai-http</a>: to send requests to our API from our tests.</li><li><a href="https://www.npmjs.com/package/jsonwebtoken" title="jwt in NPM" target="_blank" style="background-color: rgb(255, 255, 255); font-size: 1rem;">jsonwebtoken</a>: to generate the JWT.<br></li><li><em><a href="https://www.npmjs.com/package/morgan" title="morgan in NPM" target="_blank">morgan</a>: to debug (optional)</em></li><li><em><a href="https://www.npmjs.com/package/nodemon" title="nodemon in NPM" target="_blank">nodemon</a>: to auto restart server automatically when files change (optional)</em></li></ul><p>You can install them all them using<strong> $npm install <em>module_name</em></strong></p><p>As we'll follow a TDD approach, first thing to do is to make sure our test framework (mocha) is working as expected. As detailed in the <a href="https://mochajs.org/#getting-started" target="_blank">official documentation,</a> let's create a <em>'test'</em> folder with a file named <em>test.js</em> inside which will contain a simple test like this:</p><pre><code class="language-javascript">
var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1,2,3].indexOf(4), -1);
    });
  });
});<br>
</code></pre><p>Configure the test script in the package.json to launch mocha.&nbsp;</p><pre><code class="language-json">
/**
 * package.json
 * node app properties
 */

"scripts": {

  "test": "mocha", 

  "start": "nodemon server.js"

},</code></pre><p>*Note: You can configure the test script to target a specific folder, recursive ones or specific file types (like spec.js) by passing mocha different parameters. You can find more info in <a href="https://mochajs.org/#the-test-directory" target="_blank">this section</a>&nbsp;of the docs.</p><p>Once we have the test and mocha configured, we just have to run <strong>$npm test</strong> and we'll get the following output:</p><p style="text-align: center;"><img src="http://www.antonioufano.com/image_uploads/test_0.png" alt="first test result" style="font-size: 1rem;"></p><br><p>We're ready to roll :)</p><h3>Creating the express app</h3><p>The base of this small project is going to be an express based API that handles requests to store new users (/register), authenticate them (/login) and return valid tokens (JWT) that are used to access protected routes of the app. Our API will have the following endpoints:</p><ul><li>GET / - Returns a simple message. Public.</li><li>POST /register - Stores new users in the database</li><li>POST /login - Validates user/pass and return a token</li><li>GET /protected - Requires a valid token, returns user info.</li></ul><p>Following a TDD approach, let's create our first test which will just verify that our app exists:</p><pre><code class="language-javascript">/**
 * test/test.js
 * Basic tests for Auth system API
 */
const chai = require('chai');
const expect = chai.expect;

//start app
const app = require('../app');

describe('App', () =&gt; {
  it('Should exists', () =&gt; {
    expect(app).to.be.a('function');})
})<br></code></pre><p>Notice that I'm using the expect assertions from the chai module. In mocha, <em>describe()</em> is used to group tests, for example, from the same functionality or resource/domain and each test is defined with the <em>it() </em>function, which receives a description and a function that contains all the assertions. If we run the test above we'll get a very descriptive error "Error: Cannot find module '../app'". So to fix that, let's go ahead and create a file named "app.js" in the root of our project. This file should export our express app which can be easily created with the following code:</p><pre><code class="language-javascript">/**
 * api/app.js
 * exports an express app.
 */

const express = require('express')
//initializes express app
const app = express();

module.exports = app;<br></code></pre><p>Now our test will pass.<br></p><p style="text-align: center;"><img src="http://www.antonioufano.com/image_uploads/firstTestOK.png" alt="successful mocha test" style="font-size: 1rem;"></p><p>Obviously our app is not doing anything so lets add more tests. We need our app to be listening for requests in all the endpoints defined previously so let's start with the easiest one, GET requests in / . In order to test HTTP requests we have to add the chai-http module. Then we can use the<em> chai.request() </em>method to launch the requests. This method is followed by the type of request we want to send (get, post, put, delete..) and it will resolve/reject a promise when it receives a response so we can use <em>.then()/.catch() </em>to handle the response from our app:</p><pre><code class="language-javascript">
 /**
 * test/test.js
 * Basic tests for Auth system API
 */

//import chai-http to send requests to the app
const http = require('chai-http');
chai.use(http);

describe('App basics', () =&gt; {
  it('Should exists', () =&gt; {
    expect(app).to.be.a('function');
  })

  it('GET / should return 200 and message', (done) =&gt; {
    //send request to the app
    chai.request(app).get('/')
      .then((res) =&gt; {
        //assertions
        //console.log(res.body);
        expect(res).to.have.status(200);
        expect(res.body.message).to.contain('Yabadabadooo');
        done();
    }).catch(err =&gt; {
      console.log(err.message);
    })
  });
})</code></pre><p>Note that as we're adding a param (<em>done</em>) to the arrow function that&nbsp;<em>it()</em>&nbsp;receives as a param. This indicates the test is asynchronous (<em>chai.request()&nbsp;</em>launch async requests) and will not be completed until we manually indicate it by calling <em>done()</em> at the end. You can find more info about asnyc tests with mocha in <a href="https://mochajs.org/#asynchronous-code" target="_blank">this section</a> of the docs. If we run this test, it will fail.</p><p style="text-align: center; "><img src="http://www.antonioufano.com/image_uploads/404.png" alt="Error 404 in test"><br></p><p>That's because our app is running but not listening for incoming requests in any endpoint as we've not defined any route yet, so it returns an error. In order to fix this we just have to add the body-parser middleware and define the endpoint route in our express app. It will look like this:</p><pre><code class="language-javascript">/**
 * api/app.js
 * exports an express app started.
 */

const express = require('express')
const app = express();

const bodyParser = require('body-parser');

//middleware to parse requests of extended urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
//middleware to parse requests of content-type - application/json
app.use(bodyParser.json())

//endpoints
app.get('/', (req, res) =&gt; {
  res.send({message:'Yabadabadooo'});
});

module.exports = app;<br></code></pre><p>Now our test should pass :) We've coded the first endpoint following TDD. First we create the test, failed it and add code until the test pass.</p><p>With one of the endpoints completed, let's create the rest.</p><h3>Registering new users<br></h3><p>As previously, first thing to do is to create a test. The target endpoint to register new users will be POST /register and it will receive the user details (name, email and password). Our app will validate then user details and once done it will return a 201 status code and a message "User created". The test for this functionality be like this:</p><pre><code class="language-javascript">  /**
 * test/test.js
 * Basic tests for Auth system API
 */

...........

describe('User registration', () =&gt; {

  it('Should return 201 and confirmation for valid input', (done) =&gt; {
    //mock valid user input
    const new_user = {
      "name"  : "John Wick",
      "email": "john@wick.com",
      "password": "secret"
    }
    //send request to the app
    chai.request(app).post('/register')
      .send(new_user)
        .then((res) =&gt; {
          //console.log(res.body);
          //assertions
          expect(res).to.have.status(201);
          expect(res.body.message).to.be.equal("User created!");
          expect(res.body.errors.length).to.be.equal(0);
          done();
        }).catch(err =&gt; {
          console.log(err.message);
        })
  });

})<br></code></pre><br><p>I've created a new <em>describe() </em>block to group different tests for this endpoint. First thing we do is to mock the user input in an object that contains the user's name, email and password. Then we send this information to our app using <em>chai.request() </em>and use the <em>send() </em>method to attach the user input to the request. Once the request is resolved (<em>.then()</em>) we validate that the body of the response (<em>res.body</em>) has the correct status code and message.&nbsp;</p><p>If we run this test we'll get a 404 error similar to the one we got when got previously as we have not defined the /register endpoint yet. Instead of adding it directly in our app.js file, let's create a routes.js file and include the following code in it:</p><pre><code class="language-javascript">/**
 * /api/routes.js
 * exports an express router.
 */ 

const express = require('express');
//create the express router that will have all endpoints
const router = express.Router();

router.post('/register', (req, res, next) =&gt; {
  let hasErrors = false ;
  let errors = [];
  
  if(!req.body.name){
  //validate name presence in the request
    errors.push({'name': 'Name not received'})
    hasErrors = true;
  }
  if(!req.body.email){
    //validate email presence in the request
    errors.push({'email': 'Email not received'})
    hasErrors = true;
  }
  if(!req.body.password){
    //validate password presence in the request
    errors.push({'password': 'Password not received'})
    hasErrors = true;
  }

  if(hasErrors){
    //if there is any missing field
    res.status(422).json({
      message: "Invalid input",
      errors: errors
    });

  }else{
    res.status(201).json({
        message: 'User created!',
        errors: errors
      });
  }

});

module.exports = router;</code></pre><p>As you can see, the endpoint receives 3 parameters, <em>req</em> (requests), <em>res</em> (response) and <em>next</em> (next action). The request will contain the data sent by the users, in our case a json with the name, email and password, and the response is what the application will send back, in our case a message ('User created' / 'Invalid input') and an array of errors. The first thing we do is validate if the body of the request contains each expected field and, if not, change the flag <em>hasErrors</em> to true and add the error to the errors array. Finally we modify the response status depending on the validations we've done and include the message and errors as a JSON object.&nbsp;</p><p>If we run the tests again it will still fail. That's because we've defined the new endpoint in the routes.js file but we've not imported it in our express app (app.js file). We can import it with <em>require</em> and attach as a middleware to our app with the <em>use()</em> method.&nbsp;</p><pre><code class="language-javascript">/**
 * api/app.js
 * exports an express app started.
 */
............
//import router with endpoints definitions
const routes = require('./api/routes');
//attach router as a middleware
app.use(routes);</code></pre><p>Now our test should pass.&nbsp;</p><p>Although test passes, our application is not doing too much, just returning a message and a JSON object but that's enough to demonstrate this example. Ideally I'd add more tests to validate that we're not allowing a user to register with an email that is already in the database, the email and name formats or that the password should contain numbers and letters.</p><p>I'll explain how to encrypt the password using bcrypt and how to save the user in a Mongo database in a continuation article. For now, let's move on to the login endpoint.</p><br><h3>Login users</h3><p>As with the previous endpoints, the first thing to do is to create a test. In this scenario we'll send a POST request to /login and we expect to receive a successful status code (200), a message "Auth OK" and a JWT token which will be used to access protected routes. Our test will be like this:</p><pre><code class="language-javascript">/**
 * test/test.js
 * Basic tests for Auth system API
 */
  ...........

  describe('User login', () =&gt; {
    it('should return 200 and token for valid credentials', (done) =&gt; {
      //mock invalid user input
      const valid_input = {
        "email": "john@wick.com",
        "password": "secret"
      }
      //send request to the app
      chai.request(app).post('/login')
        .send(valid_input)
          .then((res) =&gt; {
            //console.log(res.body);
            //assertions
            expect(res).to.have.status(200);
            expect(res.body.token).to.exist;
            expect(res.body.message).to.be.equal("Auth OK");
            expect(res.body.errors.length).to.be.equal(0);
            done();
          }).catch(err =&gt; {
            console.log(err.message);
          })
    });
  });</code></pre><p>We run our test suite again and it will fail as our app will return a 404 status code as we've not defined the /login endpoint. Let's work on that. We can add the endpoint with just a few lines:</p><pre><code class="language-javascript">/**
 * /api/routes.js
 * exports an express router.
 */ 

..............

router.post('/login', (req, res, next) =&gt; {
  res.status(200);
});</code></pre><p>If we run the tests again, we'll pass the status assertion but&nbsp; it will still fail because we're not returning the token nor the message. In order to generate the JWT token we first need to verify that we've received the user and password in the body of the request (<em>req.body</em>), then verify that they are valid and finally we'll generate the token. As we've not prepared our code to store the registered users in a database yet, we'll just check if the email and pass are "john@wick.com" and&nbsp; "secret" for now. If the email and password do not match we'll return a status code 401 with the message 'Auth error'. Our login route will look like this:</p><pre><code class="language-javascript">/**
 * /api/routes.js
 * exports an express router.
 */ 

..............

router.post('/login', (req, res, next) =&gt; {
  let hasErrors = false ;
  let errors = [];
  
  //validate presence of email and password
  if(!req.body.email){
    errors.push({'email': 'Email not received'})
    hasErrors = true;
  }
  if(!req.body.password){
    errors.push({'password': 'Password not received'})
    hasErrors = true;
  }

  if(hasErrors){
  //return error code an info
    res.status(422).json({
      message: "Invalid input",
      errors: errors
    });

  }else{
  //check if credentials are valid
    if(req.body.email == 'john@wick.com' &amp;&amp; req.body.password == 'secret'){
      //return 200 and message OK
      res.status(200).json({
        message: 'Auth OK',
        errors: errors

      });
    }else{
      //return 401 and message KO
      res.status(401).json({
        message: "Auth error"
      }) 
    }  
  }</code></pre><p>The only thing preventing our test to pass all assertions is to return a token. If you're not familiar with JWT tokens you can get some info in&nbsp;<a href="http://www.jwt.io" title="jwt.io webpage" target="_blank" style="background-color: rgb(255, 255, 255); font-size: 1rem;">jwt.io</a>&nbsp;.</p><p>To generate the JWT tokens we'll have to install and import the <strong>jsonwebtoken</strong> module. As detailed in <a href="https://github.com/auth0/node-jsonwebtoken" title="jsonwebtoken documentation github" target="_blank">its documentation</a>, we can use the<em> jwt.sign() </em>method to generate the tokens. This method receives 3 parameters: the payload (info to be stored in our token), a key to encode it and an object with options (like expiration time). The most important one is the key. As it will be used to encode our tokens, we have to store it in a secure location, like an environment variable which can be accessed from our code with <em>process.env.VARIABLE_NAME</em>. In our case let's just name our variable JWT_KEY and&nbsp;load it directly at the beginning of our <em>app.js</em> file with any value we want:</p><pre><code class="language-javascript">/**
 * api/app.js
 * exports an express app started.
 */
...............
process.env.JWT_KEY = "thisIsMyJwtKeyUsedToEncodeTheTokens";
...............
</code></pre><p>Now back to our <em>routes.js</em> file, once we've validated the email and password from the <em>request.body</em> we'll generate the token so we can include it in our response:</p><pre><code class="language-javascript">/**
 * /api/routes.js
 * exports an express router.
 */ 

..............

router.post('/login', (req, res, next) =&gt; {
  let hasErrors = false ;
  let errors = [];

  //validate presence of email and password
  if(!req.body.email){
    errors.push({'email': 'Email not received'})
    hasErrors = true;
  }
  if(!req.body.password){
    errors.push({'password': 'Password not received'})
    hasErrors = true;
  }

  if(hasErrors){
  //return error code an info
    res.status(422).json({
      message: "Invalid input",
      errors: errors
    });

  }else{
  //check if credentials are valid
    if(req.body.email == 'john@wick.com' &amp;&amp; req.body.password == 'secret'){
      //generate JWT token. jwt.sing() receives payload, key and opts.
      const token = jwt.sign(
        {
          email: req.body.email, 
        }, 
        process.env.JWT_KEY, 
        {
          expiresIn: "1h"
        }
      );
      //validation OK
      res.status(200).json({
        message: 'Auth OK',
        token: token,
        errors: errors
      })
    }else{
      //return 401 and message KO
      res.status(401).json({
        message: "Auth error"
      }) 
    }  
  }
});</code></pre><p>Now all our assertions should pass. We're sending back the status code 200, the message 'Auth OK', the JWT token and an empty errors array.</p><h2>Conclusion</h2><p>Although it still have a lot of things to polish, we've built a basic registration and authentication system using TDD.&nbsp;In the next article I'll include integration with a Mongo database and I'll use the bcrypt module to encrypt the user password before storing it in the database. Once we save the registered users in the database we'll be able to properly validate the credentials in the login method.</p><p>The entire code can be found in <a href="https://gitlab.com/uF4No/authsysjs/tree/master" title="Repository in gilab" target="_blank">GitLab</a>.</p><p>I hope this article helps you understand the benefits of TDD. Creating tests before writing a single line of code will help us whenever we have to add new features to our application as if there is any incompatibility with previous functionalities, our tests will fail. This will also be helpful when setting up continuous integration / continuous delivery pipelines. In addition, having a good set of tests will also help other developers understand what the application does without even looking at the&nbsp; code.</p>.<p>See you in the next one.</p>
<p>This article was originally posted in <a href="https://antonioufano.com/articles/building-a-javascript-jwt-auth-system-using-tdd-part-1-13" target="_blank">my website</a>. Feel free to pay me a visit and give me some feedback in the <a href="http://antonioufano.com/contact" target="_blank">contact</a> section.</p>
<p>Happy codding!</p>