From 463ed6473b7e949666acfb4b42a474daf409c1a0 Mon Sep 17 00:00:00 2001 From: Juan Cruz Viotti Date: Fri, 31 Oct 2014 14:47:18 -0400 Subject: [PATCH] Implement basic Auth module that fetches a token --- lib/cli-modules/auth/auth.coffee | 8 +++++ lib/cli-modules/auth/auth.spec.coffee | 38 ++++++++++++++++++++++ lib/cli-modules/auth/fixtures/johndoe.json | 7 ++++ 3 files changed, 53 insertions(+) create mode 100644 lib/cli-modules/auth/auth.coffee create mode 100644 lib/cli-modules/auth/auth.spec.coffee create mode 100644 lib/cli-modules/auth/fixtures/johndoe.json diff --git a/lib/cli-modules/auth/auth.coffee b/lib/cli-modules/auth/auth.coffee new file mode 100644 index 00000000..116700f6 --- /dev/null +++ b/lib/cli-modules/auth/auth.coffee @@ -0,0 +1,8 @@ +server = require('../../server/server') + +exports.getToken = (credentials, callback) -> + server.post '/login_', credentials, (error, response) -> + return callback(error, response?.body) + +exports.login = (credentials, callback) -> + exports.getToken(credentials, callback) diff --git a/lib/cli-modules/auth/auth.spec.coffee b/lib/cli-modules/auth/auth.spec.coffee new file mode 100644 index 00000000..eb94fbe1 --- /dev/null +++ b/lib/cli-modules/auth/auth.spec.coffee @@ -0,0 +1,38 @@ +expect = require('chai').expect +nock = require('nock') +auth = require('./auth') +config = require('../../config') +johnDoeFixture = require('./fixtures/johndoe') + +describe 'Auth', -> + + describe 'given valid credentials', -> + + beforeEach -> + nock(config.baseUrl) + .post('/login_', johnDoeFixture.credentials) + .reply(200, johnDoeFixture.token) + + describe '#getToken()', -> + + it 'should return a token string', (done) -> + auth.getToken johnDoeFixture.credentials, (error, token) -> + return done(error) if error? + expect(token).to.be.a('string') + expect(token).to.equal(johnDoeFixture.token) + done() + + describe 'given invalid credentials', -> + + beforeEach -> + nock(config.baseUrl) + .post('/login_') + .reply(401) + + describe '#getToken()', -> + + it 'should return an error', (done) -> + auth.getToken johnDoeFixture.credentials, (error, token) -> + expect(error).to.exist + expect(error).to.be.an.instanceof(Error) + done() diff --git a/lib/cli-modules/auth/fixtures/johndoe.json b/lib/cli-modules/auth/fixtures/johndoe.json new file mode 100644 index 00000000..334fc39d --- /dev/null +++ b/lib/cli-modules/auth/fixtures/johndoe.json @@ -0,0 +1,7 @@ +{ + "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imp2aW90dGkiLCJlbWFpbCI6Imp1YW5jaGl2aW90dGlAZ21haWwuY29tIiwiZ2l0bGFiX2lkIjoxNjUsImhhc1Bhc3N3b3JkU2V0Ijp0cnVlLCJwdWJsaWNfa2V5Ijp0cnVlLCJmZWF0dXJlcyI6W10sImlkIjoxNzUsInBlcm1pc3Npb25zIjpbImV3YS5kZXZpY2UuZ2V0IiwiYWRtaW4uY3JlYXRlX2ludml0ZXMiLCJhZG1pbi5ob21lIiwiYWRtaW4ubG9naW5fYXNfdXNlciJdLCJpYXQiOjE0MTQ3NzMyMTN9.j4gMqZlnVohJt8jLpzpJWZS6rFUpNCWDwa13woo58aY", + "credentials": { + "username": "johndoe", + "password": "mysecret" + } +}