Introduction to Testing Basic Authentication

Today's project

  • Update the blog tests
  • Fix anything which has broken by adding authentication
  • Add new tests which cover your auth system

Tests for authentication

  • I provided a correct username/password - can I access the endpoint?
  • I provided an incorrect username/password - can I access the endpoint?
  • I didn't provide any credentials - can I access the endpoint?
  • I'm user X, what happens if I do thing Y?
    • Add a new blog post - is the author set to me?
    • Edit a blog post which isn't mine - am I allowed?

Users in tests

  • We need a user for authentication in the tests
  • Seed on in the database
  • Difficulty: we need both the hashed and unhashed password
    • Store the hashed password in the database
    • Use the unhashed password to authenticate with
  • Simplest and quickest solution: Hard-code a hashed password
  • Use a seed function which adds a user with that password hash

Generating a hash

// You can just run this in the Node REPL
const {User} = require('./models');

User.hashPassword('test-password')
    .then(hash => console.log(hash));

Creating a user with a hard-coded hash

User.create({
  username: faker.internet.userName(),
  // Substitute the hash you generated here
  password: '$2a$10$mjFeHXylKADWX8/HCsOQAu418D.VDL6.tjpgGUH82BrS8XMOecVuW',
  firstName: faker.name.firstName(),
  lastName: faker.name.lastName()
});

Basic auth with chai-http

chai.request(app)
  .get('/me')
  // .auth method sets the basic auth header
  .auth('username', 'password');

Structure of tests

describe('Method endpoint', function() {
    it('should add a new restaurant', function() {
        // Make an HTTP request and check the response
        let res;
        return chai.request(app)
            .get('/resource')
            .auth('username', 'password')
            .then(_res => {
              res = _res;

              res.should.have.status(200);             
              //...

              return Model.findSomehow();

            })
            .then(item => {

              item.property.should.equal(res.property);

            });
    });
});
Add Authentication
Test the details
Retrieve Data
Confirm database matches response

Auth: Testing authentication

By Thinkful

Auth: Testing authentication

  • 1,462