From fa7c3c2cd46b73c5e75b5bd54f85a6916ffe8a55 Mon Sep 17 00:00:00 2001 From: guumaster Date: Sat, 27 Feb 2016 15:02:11 +0100 Subject: [PATCH 1/7] simplified tests structures. package.json cleanup --- gulpfile.js | 21 - main.js | 8 +- package.json | 32 +- tests-unit/auth.js | 42 -- tests-unit/auth/admin_login.js | 77 +++ tests-unit/auth/facebook_token.js | 189 +++-- tests-unit/auth/google.js | 58 +- tests-unit/auth/in.js | 62 +- tests-unit/auth/login.js | 260 +++---- tests-unit/auth/logout.js | 280 ++++---- tests-unit/auth/renew.js | 216 +++--- tests-unit/auth/sf.js | 319 +++++---- tests-unit/auth/user.js | 646 +++++++++--------- tests-unit/dao.js | 32 +- tests-unit/email.js | 124 ++-- tests-unit/emailAvailable.js | 12 +- tests-unit/fileStore.js | 13 +- tests-unit/heartbeat.js | 9 - tests-unit/jsonValidator.js | 2 +- tests-unit/managerUser.js | 2 +- tests-unit/managers/crypto.js | 8 +- tests-unit/middlewares/decodeToken.js | 4 +- tests-unit/phone.js | 33 +- tests-unit/pinValidation.js | 4 +- tests-unit/platforms/salesforce.js | 8 - tests-unit/proxy.js | 80 +-- tests-unit/proxy/protectedCallsPassThrough.js | 462 ++++++------- .../protectedCallsStandard-platformSF.js | 140 ++-- tests-unit/proxy/protectedCallsStandard.js | 216 +++--- .../public_routes/auth/loginRefreshToken.js | 2 +- tests-unit/redirect.js | 15 +- tests-unit/redis.js | 63 +- tests-unit/routesRealms.js | 37 +- tests-unit/routesUser.js | 33 +- tests-unit/server.js | 2 +- tests-unit/start_stop_cipherlayer.js | 12 + tests-unit/token_settings.js | 16 + tests-unit/verifyPhone.js | 32 +- 38 files changed, 1683 insertions(+), 1888 deletions(-) delete mode 100644 gulpfile.js delete mode 100644 tests-unit/auth.js create mode 100644 tests-unit/auth/admin_login.js create mode 100644 tests-unit/start_stop_cipherlayer.js create mode 100644 tests-unit/token_settings.js diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100644 index 0d50603..0000000 --- a/gulpfile.js +++ /dev/null @@ -1,21 +0,0 @@ -var gulp = require('gulp'); -var jshint = require('gulp-jshint'); - -var SOURCE_FOLDERS = ['./src/**/*.js', './features/**/*.js', 'gulpfile.js']; - -// -// Check code style and lint -// -gulp.task('jshint', function () { - return gulp.src(SOURCE_FOLDERS) - .pipe(jshint()) - .pipe(jshint.reporter('default')) - .pipe(jshint.reporter('fail')); -}); - -gulp.task('jshint-go', function () { - return gulp.src(SOURCE_FOLDERS) - .pipe(jshint()) - .pipe(jshint.reporter('jshint-junit-reporter', {outputFile: 'lint-tests-reports.xml'})) - .pipe(jshint.reporter('fail')); -}); diff --git a/main.js b/main.js index bc2e8ad..62699e5 100644 --- a/main.js +++ b/main.js @@ -2,12 +2,16 @@ var cipherLayer = require('./src/cipherlayer'); var fs = require('fs'); var config = require(process.cwd() + '/config.json'); +var PUBLIC_PORT = process.env.PORT || config.public_port; +var INTERNAL_PORT = process.env.INTERNAL_PORT || config.internal_port; + console.log('starting cipherlayer proxy'); -cipherLayer.start(config.public_port, config.internal_port, function (err) { + +cipherLayer.start(PUBLIC_PORT, INTERNAL_PORT, function (err) { if (err) { console.error('error on launch: ' + err); } else { - console.log('listening on port ' + config.public_port); + console.log('listening on port ' + PUBLIC_PORT); } fs.watchFile('config.json', function () { diff --git a/package.json b/package.json index 191e5d4..66e7513 100644 --- a/package.json +++ b/package.json @@ -4,11 +4,11 @@ "description": "cipherlayer", "main": "src/cipherlayer.js", "scripts": { - "test": "npm run-script jshint && npm run-script mocha && npm run-script features", - "mocha": "mocha tests-unit --recursive", - "features": "cucumber.js tests-acceptance -f pretty --tags ~@ignore", - "features-only": "cucumber.js tests-acceptance -f pretty --tags @only", - "jshint": "jshint ./src ./tests-unit ./tests-acceptance main.js", + "test": "npm run lint && npm run test-unit && npm run test-acceptance", + "test-unit": "mocha tests-unit --recursive", + "test-acceptance": "cucumber.js tests-acceptance -f pretty --tags ~@ignore", + "test-acceptance-only": "cucumber.js tests-acceptance -f pretty --tags @only", + "lint": "jshint ./src ./tests-unit ./tests-acceptance main.js", "coverage-unit": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/unit _mocha -- tests-unit --recursive --reporter mocha-lcov-reporter", "coverage-acceptance": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/acceptance cucumber.js -- tests-acceptance --tags ~@ignore --format json", "coverage-merge": "istanbul-combine coverage/**/coverage.json", @@ -26,7 +26,7 @@ "http-proxy": "^1.8.1", "jsonschema": "^1.0.0", "lodash": "^4.3.0", - "mongodb": "^1.4.22", + "mongodb": "^1.4.40", "passport": "^0.2.1", "passport-forcedotcom": "^0.1.1", "passport-google-oauth2": "^0.1.6", @@ -39,7 +39,6 @@ }, "devDependencies": { "assert": "^1.1.2", - "blanket": "^1.1.7", "chai": "^3.5.0", "codeclimate-test-reporter": "^0.3.1", "coveralls": "^2.11.4", @@ -48,11 +47,10 @@ "istanbul-combine": "^0.3.0", "istanbul-coveralls": "^1.0.3", "jshint": "^2.8.0", - "lcov-result-merger": "^1.0.2", "mocha": "^2.0.1", - "mocha-lcov-reporter": "0.0.2", + "mocha-lcov-reporter": "^1.2.0", "mockery": "^1.4.0", - "nock": "^0.51.0", + "nock": "^7.3.0", "pre-commit": "^1.0.7", "sinon": "^1.12.2", "which": "^1.0.8" @@ -68,24 +66,12 @@ }, "homepage": "https://github.com/thegameofcode/cipherlayer", "pre-commit": [ - "jshint" + "lint" ], "jshintConfig": { "esnext": true, "node": true, "unused": true, "mocha": true - }, - "config": { - "blanket": { - "pattern": [ - "src", - "tests" - ], - "data-cover-never": [ - "node_modules", - "tests" - ] - } } } diff --git a/tests-unit/auth.js b/tests-unit/auth.js deleted file mode 100644 index bdd2cb3..0000000 --- a/tests-unit/auth.js +++ /dev/null @@ -1,42 +0,0 @@ -var cipherlayer = require('../src/cipherlayer.js'); -var config = require('../config.json'); - -var describeLogin = require('./auth/login.js'); -var describeLogout = require('./auth/logout.js'); -var describeUser = require('./auth/user.js'); -var describeSf = require('./auth/sf.js'); -var describeFbToken = require('./auth/facebook_token.js'); -var describeIn = require('./auth/in.js'); -var describeGoogle = require('./auth/google.js'); -var describeRenew = require('./auth/renew.js'); - -var accessTokenSettings = { - cipherKey: config.accessToken.cipherKey, - firmKey: config.accessToken.signKey, - tokenExpirationMinutes: config.accessToken.expiration -}; - -var refreshTokenSettings = { - cipherKey: config.refreshToken.cipherKey, - firmKey: config.refreshToken.signKey, - tokenExpirationMinutes: config.refreshToken.expiration -}; - -describe('/auth', function () { - beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, done); - }); - - afterEach(function (done) { - cipherlayer.stop(done); - }); - - describeLogin.describe(accessTokenSettings, refreshTokenSettings); - describeLogout.describe(accessTokenSettings); - describeUser.describe(); - describeSf.describe(accessTokenSettings, refreshTokenSettings); - describeIn.describe(); - describeFbToken.describe(); - describeGoogle.describe(); - describeRenew.describe(); -}); diff --git a/tests-unit/auth/admin_login.js b/tests-unit/auth/admin_login.js new file mode 100644 index 0000000..b737239 --- /dev/null +++ b/tests-unit/auth/admin_login.js @@ -0,0 +1,77 @@ +var assert = require('assert'); +var request = require('request'); +var ciphertoken = require('ciphertoken'); +var config = require('../../config.json'); +var dao = require('../../src/managers/dao.js'); +var nock = require('nock'); +var _ = require('lodash'); +var crypto = require('../../src/managers/crypto'); +var cryptoMng = crypto(config.password); + +var versionHeader = 'test/1'; + +var accessTokenSettings = require('../token_settings').accessTokenSettings; +var refreshTokenSettings = require('../token_settings').refreshTokenSettings; + + +describe('Admin /login', function () { + var baseUser = { + id: 'a1b2c3d4e5f6', + username: 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), + password: 'validpassword', + roles: ["admin"], + deviceId: "0987654321" + }; + + beforeEach(function (done) { + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + var userToCreate = _.clone(baseUser); + cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { + userToCreate.password = encryptedPwd; + dao.addUser()(userToCreate, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, undefined); + done(); + }); + }); + }); + }); + it('POST 200', function (done) { + var user = _.clone(baseUser); + var options = { + url: 'http://localhost:' + config.public_port + '/auth/login', + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify(user) + }; + options.headers[config.version.header] = versionHeader; + + nock('http://localhost:' + config.private_port) + .post('/api/me/session') + .reply(204); + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + body = JSON.parse(body); + assert.notEqual(body.accessToken, undefined); + assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); + ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { + assert.equal(err, null); + assert.equal(accessTokenInfo.userId, user.id); + assert.deepEqual(accessTokenInfo.data.roles, user.roles); + assert.equal(accessTokenInfo.data.deviceId, user.deviceId); + assert.notEqual(body.refreshToken, undefined); + ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { + assert.equal(err, null); + assert.equal(refreshTokenInfo.userId, user.id); + assert.equal(accessTokenInfo.data.deviceId, user.deviceId); + done(); + }); + }); + }); + }); +}); diff --git a/tests-unit/auth/facebook_token.js b/tests-unit/auth/facebook_token.js index 99a3f27..04f3053 100644 --- a/tests-unit/auth/facebook_token.js +++ b/tests-unit/auth/facebook_token.js @@ -33,125 +33,120 @@ var FB_PROFILE = { var versionHeader = 'test/1'; -module.exports = { - describe: function () { - describe('/facebook_token', function () { - - beforeEach(function (done) { - userDao.deleteAllUsers(function (err) { - assert.equal(err, null); - done(); - }); - }); +describe('/facebook_token', function () { - it('exchanges facebook token for an existing cipherlayer user', function (done) { - nockFBGraphCall(FB_PROFILE, OPTIONS.body.accessToken, config.facebook.requestFields); - - var options = _.cloneDeep(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/login/facebook'; - options.headers[config.version.header] = versionHeader; - - var existingUser = _.cloneDeep(baseUser); - existingUser.username = existingUser.email; - delete existingUser.email; - - userDao.addUser()(existingUser, function (error) { - assert.equal(error, null); - - request(options, function (err, res, body) { - assert.ok(body.accessToken); - assert.ok(body.refreshToken); - assert.ok(body.expiresIn); - - userDao.getFromUsername(baseUser.email, function (error, user) { - assert.ok(user); - assert.equal(user.username, existingUser.username); - assert.ok(user.platforms); - var fbPlatform = user.platforms[0]; - assert.equal(fbPlatform.platform, 'fb'); - assert.equal(fbPlatform.accessToken, OPTIONS.body.accessToken); - return done(); - }); - }); + beforeEach(function (done) { + userDao.deleteAllUsers(function (err) { + assert.equal(err, null); + done(); + }); + }); + + it('exchanges facebook token for an existing cipherlayer user', function (done) { + nockFBGraphCall(FB_PROFILE, OPTIONS.body.accessToken, config.facebook.requestFields); + + var options = _.cloneDeep(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/login/facebook'; + options.headers[config.version.header] = versionHeader; + + var existingUser = _.cloneDeep(baseUser); + existingUser.username = existingUser.email; + delete existingUser.email; + + userDao.addUser()(existingUser, function (error) { + assert.equal(error, null); + + request(options, function (err, res, body) { + assert.ok(body.accessToken); + assert.ok(body.refreshToken); + assert.ok(body.expiresIn); + + userDao.getFromUsername(baseUser.email, function (error, user) { + assert.ok(user); + assert.equal(user.username, existingUser.username); + assert.ok(user.platforms); + var fbPlatform = user.platforms[0]; + assert.equal(fbPlatform.platform, 'fb'); + assert.equal(fbPlatform.accessToken, OPTIONS.body.accessToken); + return done(); }); }); - - it('exchanges facebook token for new user', function (done) { - nockFBGraphCall(FB_PROFILE, OPTIONS.body.accessToken, config.facebook.requestFields); - nockPrivateCall(config, baseUser.id); - - var options = _.cloneDeep(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/login/facebook'; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.ok(body.accessToken); - assert.ok(body.refreshToken); - assert.ok(body.expiresIn); - - userDao.getFromUsername(baseUser.email, function (err, foundUser) { - assert.equal(err, null); - assert.ok(foundUser); - assert.equal(foundUser.username, baseUser.email); - assert.ok(foundUser.platforms); - var fbPlatform = foundUser.platforms[0]; - assert.equal(fbPlatform.platform, 'fb'); - assert.equal(fbPlatform.accessToken, OPTIONS.body.accessToken); - done(); - }); - }); + }); + }); + + it('exchanges facebook token for new user', function (done) { + nockFBGraphCall(FB_PROFILE, OPTIONS.body.accessToken, config.facebook.requestFields); + nockPrivateCall(config, baseUser.id); + + var options = _.cloneDeep(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/login/facebook'; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.ok(body.accessToken); + assert.ok(body.refreshToken); + assert.ok(body.expiresIn); + + userDao.getFromUsername(baseUser.email, function (err, foundUser) { + assert.equal(err, null); + assert.ok(foundUser); + assert.equal(foundUser.username, baseUser.email); + assert.ok(foundUser.platforms); + var fbPlatform = foundUser.platforms[0]; + assert.equal(fbPlatform.platform, 'fb'); + assert.equal(fbPlatform.accessToken, OPTIONS.body.accessToken); + done(); }); + }); + }); - it('creates a user with a facebook domain email when username field is missing', function (done) { + it('creates a user with a facebook domain email when username field is missing', function (done) { - var noEmailUser = _.cloneDeep(baseUser); - delete noEmailUser.email; + var noEmailUser = _.cloneDeep(baseUser); + delete noEmailUser.email; - var madeUpEmailFbProfile = _.cloneDeep(FB_PROFILE); - delete madeUpEmailFbProfile.email; + var madeUpEmailFbProfile = _.cloneDeep(FB_PROFILE); + delete madeUpEmailFbProfile.email; - var userEmail = 'fb' + noEmailUser.id + '@facebook.com'; + var userEmail = 'fb' + noEmailUser.id + '@facebook.com'; - nockFBGraphCall(madeUpEmailFbProfile, OPTIONS.body.accessToken, config.facebook.requestFields); - nockPrivateCall(config, noEmailUser.id); + nockFBGraphCall(madeUpEmailFbProfile, OPTIONS.body.accessToken, config.facebook.requestFields); + nockPrivateCall(config, noEmailUser.id); - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/login/facebook'; - options.headers[config.version.header] = versionHeader; + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/login/facebook'; + options.headers[config.version.header] = versionHeader; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.ok(body.accessToken); - assert.ok(body.refreshToken); - assert.ok(body.expiresIn); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.ok(body.accessToken); + assert.ok(body.refreshToken); + assert.ok(body.expiresIn); - userDao.getFromUsername(userEmail, function (err, foundUser) { - assert.equal(err, null); - assert.ok(foundUser); - assert.equal(foundUser.username, userEmail); - assert.ok(foundUser.platforms); - var fbPlatform = foundUser.platforms[0]; - assert.equal(fbPlatform.platform, 'fb'); - assert.equal(fbPlatform.accessToken, OPTIONS.body.accessToken); - done(); - }); - }); + userDao.getFromUsername(userEmail, function (err, foundUser) { + assert.equal(err, null); + assert.ok(foundUser); + assert.equal(foundUser.username, userEmail); + assert.ok(foundUser.platforms); + var fbPlatform = foundUser.platforms[0]; + assert.equal(fbPlatform.platform, 'fb'); + assert.equal(fbPlatform.accessToken, OPTIONS.body.accessToken); + done(); }); }); - } -}; + }); +}); -function nockFBGraphCall(profile, access_token, fields) { +function nockFBGraphCall (profile, access_token, fields) { fields = encodeURIComponent(fields); nock('https://graph.facebook.com') .get('/v2.5/me?fields=' + fields + '&format=json&method=get&pretty=0&suppress_http_code=1' + '&access_token=' + access_token) .reply(200, profile); } -function nockPrivateCall(config, userId) { +function nockPrivateCall (config, userId) { nock('http://' + config.private_host + ':' + config.private_port) .post(config.passThroughEndpoint.path) .reply(201, {id: userId}); } - diff --git a/tests-unit/auth/google.js b/tests-unit/auth/google.js index ab999af..ee48d2f 100644 --- a/tests-unit/auth/google.js +++ b/tests-unit/auth/google.js @@ -6,43 +6,39 @@ var _ = require('lodash'); var versionHeader = 'test/1'; -module.exports = { - describe: function () { - describe('/google', function () { - beforeEach(function (done) { - OPTIONS.headers[config.version.header] = versionHeader; - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - done(); - }); - }); +describe('/google', function () { + beforeEach(function (done) { + OPTIONS.headers[config.version.header] = versionHeader; + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + done(); + }); + }); - it('GET 302', function (done) { - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/google'; + it('GET 302', function (done) { + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/google'; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - done(); - }); - }); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 302, body); + done(); + }); + }); - describe('/callback', function () { - it('302 invalid data', function (done) { - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/google/callback'; + describe('/callback', function () { + it('302 invalid data', function (done) { + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/google/callback'; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - done(); - }); - }); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 302, body); + done(); }); }); - } -}; + }); +}); var OPTIONS = { headers: { diff --git a/tests-unit/auth/in.js b/tests-unit/auth/in.js index 2ed7776..c851b45 100644 --- a/tests-unit/auth/in.js +++ b/tests-unit/auth/in.js @@ -6,44 +6,40 @@ var _ = require('lodash'); var versionHeader = 'test/1'; -module.exports = { - describe: function () { - describe('/in', function () { - beforeEach(function (done) { - OPTIONS.headers[config.version.header] = versionHeader; - - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - done(); - }); - }); +describe('/in', function () { + beforeEach(function (done) { + OPTIONS.headers[config.version.header] = versionHeader; - it('GET 302', function (done) { - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/in'; + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + done(); + }); + }); - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - done(); - }); - }); + it('GET 302', function (done) { + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/in'; - describe('/callback', function () { - it('302 invalid data', function (done) { - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/in/callback'; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - done(); - }); - }); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 302, body); + done(); + }); + }); + + describe('/callback', function () { + it('302 invalid data', function (done) { + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/in/callback'; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 302, body); + done(); }); }); - } -}; + }); +}); var OPTIONS = { headers: { diff --git a/tests-unit/auth/login.js b/tests-unit/auth/login.js index b1fa92c..c30441a 100644 --- a/tests-unit/auth/login.js +++ b/tests-unit/auth/login.js @@ -5,178 +5,116 @@ var config = require('../../config.json'); var dao = require('../../src/managers/dao.js'); var nock = require('nock'); var _ = require('lodash'); - var crypto = require('../../src/managers/crypto'); var cryptoMng = crypto(config.password); var versionHeader = 'test/1'; -module.exports = { - describe: function(accessTokenSettings, refreshTokenSettings){ - describe('/login', function () { - var baseUser = { - id: 'a1b2c3d4e5f6', - username: 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*','') : ''), - password: 'validpassword', - deviceId: '1234567890' - }; - - beforeEach(function (done) { - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - var userToCreate = _.clone(baseUser); - cryptoMng.encrypt(userToCreate.password, function(encryptedPwd) { - userToCreate.password = encryptedPwd; - dao.addUser()(userToCreate, function (err, createdUser) { - assert.equal(err, null); - assert.notEqual(createdUser, undefined); - done(); - }); - }); - }); - }); - it('POST 200', function (done) { - var user = _.clone(baseUser); - var options = { - url: 'http://localhost:' + config.public_port + '/auth/login', - headers: { - 'Content-Type': 'application/json; charset=utf-8' - }, - method: 'POST', - body: JSON.stringify(user) - }; - options.headers[config.version.header] = versionHeader; +var accessTokenSettings = require('../token_settings').accessTokenSettings; +var refreshTokenSettings = require('../token_settings').refreshTokenSettings; - nock('http://localhost:'+ config.private_port) - .post('/api/me/session') - .reply(204); +describe('/login', function () { + var baseUser = { + id: 'a1b2c3d4e5f6', + username: 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), + password: 'validpassword', + deviceId: '1234567890' + }; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - body = JSON.parse(body); - assert.notEqual(body.accessToken, undefined); - assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); - ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { - assert.equal(err, null); - assert.equal(accessTokenInfo.userId, user.id); - assert.equal(accessTokenInfo.data.deviceId, user.deviceId); - assert.notEqual(body.refreshToken, undefined); - ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { - assert.equal(err, null); - assert.equal(refreshTokenInfo.userId, user.id); - assert.equal(accessTokenInfo.data.deviceId, user.deviceId); - done(); - }); - }); - }); - }); - it('POST 409 invalid credentials', function (done) { - var user = _.clone(baseUser); - user.password = 'invalidpassword'; - var options = { - url: 'http://localhost:' + config.public_port + '/auth/login', - headers: { - 'Content-Type': 'application/json; charset=utf-8' - }, - method: 'POST', - body: JSON.stringify(user) - }; - options.headers[config.version.header] = versionHeader; + beforeEach(function (done) { + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + var userToCreate = _.clone(baseUser); + cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { + userToCreate.password = encryptedPwd; + dao.addUser()(userToCreate, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, undefined); + done(); + }); + }); + }); + }); + it('POST 200', function (done) { + var user = _.clone(baseUser); + var options = { + url: 'http://localhost:' + config.public_port + '/auth/login', + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify(user) + }; + options.headers[config.version.header] = versionHeader; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 409); - body = JSON.parse(body); - assert.notEqual(body.err, 'invalid_credentials'); - done(); - }); - }); + nock('http://localhost:' + config.private_port) + .post('/api/me/session') + .reply(204); - it('POST 409 username substring', function (done) { - var user = _.clone(baseUser); - var username = user.username; - user.username = username.slice(0, username.length / 2); - var options = { - url: 'http://localhost:' + config.public_port + '/auth/login', - headers: { - 'Content-Type': 'application/json; charset=utf-8' - }, - method: 'POST', - body: JSON.stringify(user) - }; - options.headers[config.version.header] = versionHeader; + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + body = JSON.parse(body); + assert.notEqual(body.accessToken, undefined); + assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); + ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { + assert.equal(err, null); + assert.equal(accessTokenInfo.userId, user.id); + assert.equal(accessTokenInfo.data.deviceId, user.deviceId); + assert.notEqual(body.refreshToken, undefined); + ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { + assert.equal(err, null); + assert.equal(refreshTokenInfo.userId, user.id); + assert.equal(accessTokenInfo.data.deviceId, user.deviceId); + done(); + }); + }); + }); + }); + it('POST 409 invalid credentials', function (done) { + var user = _.clone(baseUser); + user.password = 'invalidpassword'; + var options = { + url: 'http://localhost:' + config.public_port + '/auth/login', + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify(user) + }; + options.headers[config.version.header] = versionHeader; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 409); - body = JSON.parse(body); - assert.notEqual(body.err, 'invalid_credentials'); - done(); - }); - }); - }); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 409); + body = JSON.parse(body); + assert.notEqual(body.err, 'invalid_credentials'); + done(); + }); + }); - describe('Admin /login', function () { - var baseUser = { - id: 'a1b2c3d4e5f6', - username: 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*','') : ''), - password: 'validpassword', - roles : ["admin"], - deviceId: "0987654321" - }; + it('POST 409 username substring', function (done) { + var user = _.clone(baseUser); + var username = user.username; + user.username = username.slice(0, username.length / 2); + var options = { + url: 'http://localhost:' + config.public_port + '/auth/login', + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify(user) + }; + options.headers[config.version.header] = versionHeader; - beforeEach(function (done) { - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - var userToCreate = _.clone(baseUser); - cryptoMng.encrypt(userToCreate.password, function(encryptedPwd) { - userToCreate.password = encryptedPwd; - dao.addUser()(userToCreate, function (err, createdUser) { - assert.equal(err, null); - assert.notEqual(createdUser, undefined); - done(); - }); - }); - }); - }); - it('POST 200', function (done) { - var user = _.clone(baseUser); - var options = { - url: 'http://localhost:' + config.public_port + '/auth/login', - headers: { - 'Content-Type': 'application/json; charset=utf-8' - }, - method: 'POST', - body: JSON.stringify(user) - }; - options.headers[config.version.header] = versionHeader; + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 409); + body = JSON.parse(body); + assert.notEqual(body.err, 'invalid_credentials'); + done(); + }); + }); +}); - nock('http://localhost:'+ config.private_port) - .post('/api/me/session') - .reply(204); - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - body = JSON.parse(body); - assert.notEqual(body.accessToken, undefined); - assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); - ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { - assert.equal(err, null); - assert.equal(accessTokenInfo.userId, user.id); - assert.deepEqual(accessTokenInfo.data.roles, user.roles); - assert.equal(accessTokenInfo.data.deviceId, user.deviceId); - assert.notEqual(body.refreshToken, undefined); - ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { - assert.equal(err, null); - assert.equal(refreshTokenInfo.userId, user.id); - assert.equal(accessTokenInfo.data.deviceId, user.deviceId); - done(); - }); - }); - }); - }); - }); - } -}; diff --git a/tests-unit/auth/logout.js b/tests-unit/auth/logout.js index 37e64bc..a6627db 100644 --- a/tests-unit/auth/logout.js +++ b/tests-unit/auth/logout.js @@ -13,154 +13,152 @@ var cryptoMng = crypto(config.password); var versionHeader = 'test/1'; -module.exports = { - describe: function (accessTokenSettings) { - describe('/logout', function () { - var baseUser = { - id: 'a1b2c3d4e5f6', - username: 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), - password: 'validpassword', - deviceId: '1234567890' - }; - - beforeEach(function (done) { - dao.deleteAllUsers(function (err) { +var accessTokenSettings = require('../token_settings').accessTokenSettings; + +describe('/logout', function () { + var baseUser = { + id: 'a1b2c3d4e5f6', + username: 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), + password: 'validpassword', + deviceId: '1234567890' + }; + + beforeEach(function (done) { + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + var userToCreate = _.clone(baseUser); + cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { + userToCreate.password = encryptedPwd; + dao.addUser()(userToCreate, function (err, createdUser) { assert.equal(err, null); - var userToCreate = _.clone(baseUser); - cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { - userToCreate.password = encryptedPwd; - dao.addUser()(userToCreate, function (err, createdUser) { - assert.equal(err, null); - assert.notEqual(createdUser, undefined); - done(); - }); - }); + assert.notEqual(createdUser, undefined); + done(); }); }); - - function doLogin() { - return new Promise(function (ok) { - var user = _.clone(baseUser); - var options = { - url: 'http://localhost:' + config.public_port + '/auth/login', - headers: {}, - method: 'POST', - body: user, - json: true - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - should.not.exist(err); - res.statusCode.should.equal(200); - body.should.have.property('accessToken'); - body.expiresIn.should.equal(accessTokenSettings.tokenExpirationMinutes); - ok(body.accessToken); - }); - }); - } - - it('POST 204', function (done) { - doLogin().then(function (accessToken) { - var options = { - url: 'http://localhost:' + config.public_port + '/auth/logout', - method: 'POST', - headers: { - 'Authorization': 'bearer ' + accessToken - }, - json: true - }; - options.headers[config.version.header] = versionHeader; - - nock('http://' + config.private_host + ':' + config.private_port).delete('/api/me/session').reply(200); - - request(options, function (err, res, body) { - should.not.exist(err); - res.statusCode.should.equal(204, body); - done(); - }); - }); + }); + }); + + function doLogin () { + return new Promise(function (ok) { + var user = _.clone(baseUser); + var options = { + url: 'http://localhost:' + config.public_port + '/auth/login', + headers: {}, + method: 'POST', + body: user, + json: true + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + should.not.exist(err); + res.statusCode.should.equal(200); + body.should.have.property('accessToken'); + body.expiresIn.should.equal(accessTokenSettings.tokenExpirationMinutes); + ok(body.accessToken); }); + }); + } - it('POST 500 no sesion service', function (done) { - doLogin().then(function (accessToken) { - var options = { - url: 'http://localhost:' + config.public_port + '/auth/logout', - method: 'POST', - headers: { - 'Authorization': 'bearer ' + accessToken - }, - json: true - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - should.not.exist(err); - res.statusCode.should.equal(500); - body.should.have.property('err').to.be.equal('internal_session_error'); - body.should.have.property('des').to.be.equal('unable to close session'); - done(); - }); - }); - }); + it('POST 204', function (done) { + doLogin().then(function (accessToken) { + var options = { + url: 'http://localhost:' + config.public_port + '/auth/logout', + method: 'POST', + headers: { + 'Authorization': 'bearer ' + accessToken + }, + json: true + }; + options.headers[config.version.header] = versionHeader; - it('POST 401 invalid access token', function (done) { - var options = { - url: 'http://localhost:' + config.public_port + '/auth/logout', - method: 'POST', - headers: { - 'Authorization': 'bearer INVALID_TOKEN' - }, - json: true - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - should.not.exist(err); - res.statusCode.should.equal(401); - body.should.have.property('err').to.be.equal('invalid_access_token'); - body.should.have.property('des').to.be.equal('unable to read token info'); - done(); - }); - }); + nock('http://' + config.private_host + ':' + config.private_port).delete('/api/me/session').reply(200); - it('POST 401 no authorization header', function (done) { - var options = { - url: 'http://localhost:' + config.public_port + '/auth/logout', - method: 'POST', - headers: {}, - json: true - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - should.not.exist(err); - res.statusCode.should.equal(401); - body.should.have.property('err').to.be.equal('invalid_authorization'); - body.should.have.property('des').to.be.equal('required authorization header'); - done(); - }); + request(options, function (err, res, body) { + should.not.exist(err); + res.statusCode.should.equal(204, body); + done(); }); - - it('POST 401 invalid authorization header identifier', function (done) { - var options = { - url: 'http://localhost:' + config.public_port + '/auth/logout', - method: 'POST', - headers: { - 'Authorization': 'wrong bearer TOKEN' - }, - json: true - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - should.not.exist(err); - res.statusCode.should.equal(401); - body.should.have.property('err').to.be.equal('invalid_authorization'); - body.should.have.property('des').to.be.equal('invalid authorization type'); - done(); - }); + }); + }); + + it('POST 500 no sesion service', function (done) { + doLogin().then(function (accessToken) { + var options = { + url: 'http://localhost:' + config.public_port + '/auth/logout', + method: 'POST', + headers: { + 'Authorization': 'bearer ' + accessToken + }, + json: true + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + should.not.exist(err); + res.statusCode.should.equal(500); + body.should.have.property('err').to.be.equal('internal_session_error'); + body.should.have.property('des').to.be.equal('unable to close session'); + done(); }); }); - } -}; + }); + + it('POST 401 invalid access token', function (done) { + var options = { + url: 'http://localhost:' + config.public_port + '/auth/logout', + method: 'POST', + headers: { + 'Authorization': 'bearer INVALID_TOKEN' + }, + json: true + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + should.not.exist(err); + res.statusCode.should.equal(401); + body.should.have.property('err').to.be.equal('invalid_access_token'); + body.should.have.property('des').to.be.equal('unable to read token info'); + done(); + }); + }); + + it('POST 401 no authorization header', function (done) { + var options = { + url: 'http://localhost:' + config.public_port + '/auth/logout', + method: 'POST', + headers: {}, + json: true + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + should.not.exist(err); + res.statusCode.should.equal(401); + body.should.have.property('err').to.be.equal('invalid_authorization'); + body.should.have.property('des').to.be.equal('required authorization header'); + done(); + }); + }); + + it('POST 401 invalid authorization header identifier', function (done) { + var options = { + url: 'http://localhost:' + config.public_port + '/auth/logout', + method: 'POST', + headers: { + 'Authorization': 'wrong bearer TOKEN' + }, + json: true + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + should.not.exist(err); + res.statusCode.should.equal(401); + body.should.have.property('err').to.be.equal('invalid_authorization'); + body.should.have.property('des').to.be.equal('invalid authorization type'); + done(); + }); + }); +}); diff --git a/tests-unit/auth/renew.js b/tests-unit/auth/renew.js index e1661e5..f9d4f41 100644 --- a/tests-unit/auth/renew.js +++ b/tests-unit/auth/renew.js @@ -11,126 +11,122 @@ var cryptoMng = crypto(config.password); var versionHeader = 'test/1'; -module.exports = { - describe: function () { - describe('/renew', function () { - - beforeEach(function (done) { - dao.deleteAllUsers(function (err) { +describe('/renew', function () { + + beforeEach(function (done) { + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + var userToCreate = _.cloneDeep(USER); + cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { + userToCreate.password = encryptedPwd; + dao.addUser()(userToCreate, function (err, createdUser) { assert.equal(err, null); - var userToCreate = _.cloneDeep(USER); - cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { - userToCreate.password = encryptedPwd; - dao.addUser()(userToCreate, function (err, createdUser) { - assert.equal(err, null); - assert.notEqual(createdUser, undefined); - done(); - }); - }); - }); - }); - - it('POST - 200', function (done) { - var options = { - url: 'http://localhost:' + config.public_port + '/auth/login', - headers: {}, - method: 'POST', - json: true, - body: _.cloneDeep(USER) - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200); - assert.notEqual(body, null); - var refreshToken = body.refreshToken; - - var options = _.cloneDeep(OPTIONS_FOR_RENEW); - options.headers[config.version.header] = versionHeader; - options.body = {refreshToken: refreshToken}; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - assert.notEqual(body.accessToken, null); - done(); - }); - }); - }); - - it('POST - 401 invalid token', function (done) { - var invalidToken = 'not a valid token :( sorry'; - var options = _.cloneDeep(OPTIONS_FOR_RENEW); - options.headers[config.version.header] = versionHeader; - options.body = {refreshToken: invalidToken}; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 401); - - assert.equal(body.err, 'invalid_token'); - assert.equal(body.des, 'Invalid token'); + assert.notEqual(createdUser, undefined); done(); }); }); - - it('POST - 401 expired token', function (done) { - var refreshTokenSettings = { - cipherKey: config.refreshToken.cipherKey, - firmKey: config.refreshToken.signKey, - tokenExpirationMinutes: 0 - }; - ciphertoken.createToken(refreshTokenSettings, 'id123', null, {}, function (err, token) { - assert.equal(err, null); - - var options = _.cloneDeep(OPTIONS_FOR_RENEW); - options.headers[config.version.header] = versionHeader; - options.body = {refreshToken: token}; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 401, body); - - assert.equal(body.err, 'expired_token'); - assert.equal(body.des, 'Expired token'); - done(); - }); - }); + }); + }); + + it('POST - 200', function (done) { + var options = { + url: 'http://localhost:' + config.public_port + '/auth/login', + headers: {}, + method: 'POST', + json: true, + body: _.cloneDeep(USER) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200); + assert.notEqual(body, null); + var refreshToken = body.refreshToken; + + var options = _.cloneDeep(OPTIONS_FOR_RENEW); + options.headers[config.version.header] = versionHeader; + options.body = {refreshToken: refreshToken}; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + assert.notEqual(body.accessToken, null); + done(); }); + }); + }); - it('Complete process', function (done) { - var options = { - url: 'http://localhost:' + config.public_port + '/auth/login', - headers: { - 'Content-Type': 'application/json; charset=utf-8' - }, - method: 'POST', - body: {username: USER.username, password: USER.password, deviceId: USER.deviceId}, - json: true - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - - var options = _.cloneDeep(OPTIONS_FOR_RENEW); - options.headers[config.version.header] = versionHeader; - options.body = {refreshToken: body.refreshToken}; + it('POST - 401 invalid token', function (done) { + var invalidToken = 'not a valid token :( sorry'; + var options = _.cloneDeep(OPTIONS_FOR_RENEW); + options.headers[config.version.header] = versionHeader; + options.body = {refreshToken: invalidToken}; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 401); - assert.notEqual(body.accessToken, null); - done(); - }); - }); + assert.equal(body.err, 'invalid_token'); + assert.equal(body.des, 'Invalid token'); + done(); + }); + }); + + it('POST - 401 expired token', function (done) { + var refreshTokenSettings = { + cipherKey: config.refreshToken.cipherKey, + firmKey: config.refreshToken.signKey, + tokenExpirationMinutes: 0 + }; + ciphertoken.createToken(refreshTokenSettings, 'id123', null, {}, function (err, token) { + assert.equal(err, null); + + var options = _.cloneDeep(OPTIONS_FOR_RENEW); + options.headers[config.version.header] = versionHeader; + options.body = {refreshToken: token}; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 401, body); + + assert.equal(body.err, 'expired_token'); + assert.equal(body.des, 'Expired token'); + done(); }); }); - } -}; + }); + + it('Complete process', function (done) { + var options = { + url: 'http://localhost:' + config.public_port + '/auth/login', + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: {username: USER.username, password: USER.password, deviceId: USER.deviceId}, + json: true + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + + var options = _.cloneDeep(OPTIONS_FOR_RENEW); + options.headers[config.version.header] = versionHeader; + options.body = {refreshToken: body.refreshToken}; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + + assert.notEqual(body.accessToken, null); + done(); + }); + }); + }); +}); var USER = { id: 'a1b2c3d4e5f6', diff --git a/tests-unit/auth/sf.js b/tests-unit/auth/sf.js index 3de5686..0934248 100644 --- a/tests-unit/auth/sf.js +++ b/tests-unit/auth/sf.js @@ -9,201 +9,200 @@ var dao = require('../../src/managers/dao.js'); var SF_PROFILE = require('../resources/sfProfileTemplate.js'); +var accessTokenSettings = require('../token_settings').accessTokenSettings; +var refreshTokenSettings = require('../token_settings').refreshTokenSettings; + var versionHeader = 'test/1'; -module.exports = { - describe: function (accessTokenSettings, refreshTokenSettings) { - describe('/sf', function () { - beforeEach(function (done) { - OPTIONS.headers[config.version.header] = versionHeader; +describe('/sf', function () { + beforeEach(function (done) { + OPTIONS.headers[config.version.header] = versionHeader; - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - done(); - }); - }); + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + done(); + }); + }); - it('GET 302', function (done) { - var options = _.clone(OPTIONS); + it('GET 302', function (done) { + var options = _.clone(OPTIONS); - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - done(); - }); - }); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 302, body); + done(); + }); + }); - describe('/callback', function () { - it('302 invalid data', function (done) { - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback'; + describe('/callback', function () { + it('302 invalid data', function (done) { + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback'; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - done(); - }); - }); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 302, body); + done(); }); + }); + }); - it('203 not exists (default avatar)', function (done) { - nockSFLoginCall(); - nockSFGetProfileCall(SF_PROFILE); - nockSFGetOptInfo(); + it('203 not exists (default avatar)', function (done) { + nockSFLoginCall(); + nockSFGetProfileCall(SF_PROFILE); + nockSFGetOptInfo(); - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?code=a1b2c3d4e5f6'; + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?code=a1b2c3d4e5f6'; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 203, body); - body = JSON.parse(body); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 203, body); + body = JSON.parse(body); - assert.equal(body.name, 'Name'); - assert.equal(body.lastname, 'Lastname'); - assert.equal(body.email, 'name.lastname' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : '')); + assert.equal(body.name, 'Name'); + assert.equal(body.lastname, 'Lastname'); + assert.equal(body.email, 'name.lastname' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : '')); - if (config.salesforce.replaceDefaultAvatar) { - assert.equal(body.avatar, config.salesforce.replaceDefaultAvatar.replacementAvatar); - } + if (config.salesforce.replaceDefaultAvatar) { + assert.equal(body.avatar, config.salesforce.replaceDefaultAvatar.replacementAvatar); + } - assert.equal(body.phone, '000000000'); - assert.equal(body.country, 'ES'); - assert.notEqual(body.sf, undefined); + assert.equal(body.phone, '000000000'); + assert.equal(body.country, 'ES'); + assert.notEqual(body.sf, undefined); - ciphertoken.getTokenSet(accessTokenSettings, body.sf, function (err, sfTokenInfo) { - assert.equal(err, null); - assert.equal(sfTokenInfo.userId, '00De00000004cdeEAA/005e0000001uNIyAAM'); - assert.notEqual(sfTokenInfo.data.accessToken, undefined); - assert.notEqual(sfTokenInfo.data.refreshToken, undefined); - done(); - }); - }); + ciphertoken.getTokenSet(accessTokenSettings, body.sf, function (err, sfTokenInfo) { + assert.equal(err, null); + assert.equal(sfTokenInfo.userId, '00De00000004cdeEAA/005e0000001uNIyAAM'); + assert.notEqual(sfTokenInfo.data.accessToken, undefined); + assert.notEqual(sfTokenInfo.data.refreshToken, undefined); + done(); }); + }); + }); - describe('Valid avatar', function () { - var configAWSParam = false; - - it('Get AWS configuration', function (done) { - var msg = 'You must configure your AWS service in the config file, ' + - '\r\notherwise you must skip the next test, which use AWS'; - - assert.notEqual(config.aws, null, msg); - assert.notEqual(config.aws, 'undefined', msg); - - assert.notEqual(config.aws.accessKeyId, null, msg); - assert.notEqual(config.aws.accessKeyId, 'undefined', msg); + describe('Valid avatar', function () { + var configAWSParam = false; - assert.notEqual(config.aws.secretAccessKey, null, msg); - assert.notEqual(config.aws.secretAccessKey, 'undefined', msg); + it('Get AWS configuration', function (done) { + var msg = 'You must configure your AWS service in the config file, ' + + '\r\notherwise you must skip the next test, which use AWS'; - assert.notEqual(config.aws.region, null, msg); - assert.notEqual(config.aws.region, 'undefined', msg); + assert.notEqual(config.aws, null, msg); + assert.notEqual(config.aws, 'undefined', msg); - assert.notEqual(config.aws.buckets, null, msg); - assert.notEqual(config.aws.buckets, 'undefined', msg); + assert.notEqual(config.aws.accessKeyId, null, msg); + assert.notEqual(config.aws.accessKeyId, 'undefined', msg); - assert.notEqual(config.aws.buckets.avatars, null, msg); - assert.notEqual(config.aws.buckets.avatars, 'undefined', msg); + assert.notEqual(config.aws.secretAccessKey, null, msg); + assert.notEqual(config.aws.secretAccessKey, 'undefined', msg); - configAWSParam = true; - done(); - }); + assert.notEqual(config.aws.region, null, msg); + assert.notEqual(config.aws.region, 'undefined', msg); - it.skip('203 not exists (valid avatar)', function (done) { - if (!configAWSParam) return done(); + assert.notEqual(config.aws.buckets, null, msg); + assert.notEqual(config.aws.buckets, 'undefined', msg); - var sfProfile = _.clone(SF_PROFILE); - sfProfile.photos.picture = "https://es.gravatar.com/userimage/75402146/7781b7690113cedf43ba98c75b08cea0.jpeg"; - sfProfile.photos.thumbnail = "https://es.gravatar.com/userimage/75402146/7781b7690113cedf43ba98c75b08cea0.jpeg"; + assert.notEqual(config.aws.buckets.avatars, null, msg); + assert.notEqual(config.aws.buckets.avatars, 'undefined', msg); - nockSFLoginCall(); - nockSFGetProfileCall(sfProfile); - nockSFGetOptInfo(); - - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?code=a1b2c3d4e5f6'; + configAWSParam = true; + done(); + }); - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 203, body); - body = JSON.parse(body); - - assert.equal(body.name, 'Name'); - assert.equal(body.lastname, 'Lastname'); - assert.equal(body.email, sfProfile.email); - assert.notEqual(body.avatar, undefined); - assert.notEqual(body.avatar, null); - assert.equal(body.phone, '000000000'); - assert.equal(body.country, 'ES'); - assert.notEqual(body.sf, undefined); - done(); - }); - }); + it.skip('203 not exists (valid avatar)', function (done) { + if (!configAWSParam) return done(); + + var sfProfile = _.clone(SF_PROFILE); + sfProfile.photos.picture = "https://es.gravatar.com/userimage/75402146/7781b7690113cedf43ba98c75b08cea0.jpeg"; + sfProfile.photos.thumbnail = "https://es.gravatar.com/userimage/75402146/7781b7690113cedf43ba98c75b08cea0.jpeg"; + + nockSFLoginCall(); + nockSFGetProfileCall(sfProfile); + nockSFGetOptInfo(); + + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?code=a1b2c3d4e5f6'; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 203, body); + body = JSON.parse(body); + + assert.equal(body.name, 'Name'); + assert.equal(body.lastname, 'Lastname'); + assert.equal(body.email, sfProfile.email); + assert.notEqual(body.avatar, undefined); + assert.notEqual(body.avatar, null); + assert.equal(body.phone, '000000000'); + assert.equal(body.country, 'ES'); + assert.notEqual(body.sf, undefined); + done(); }); - - it('200 OK', function (done) { - var user = { - id: 'a1b2c3d4e5f6', - username: 'name.lastname' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), - password: '12345678' - }; - - dao.addUser()(user, function (err, createdUser) { + }); + }); + + it('200 OK', function (done) { + var user = { + id: 'a1b2c3d4e5f6', + username: 'name.lastname' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), + password: '12345678' + }; + + dao.addUser()(user, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, undefined); + + nockSFLoginCall(); + nockSFGetProfileCall(SF_PROFILE); + + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?code=a1b2c3d4e5f6'; + options.followAllRedirects = true; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + body = JSON.parse(body); + assert.notEqual(body.refreshToken, undefined); + assert.notEqual(body.expiresIn, undefined); + + dao.getFromId(createdUser._id, function (err, foundUser) { assert.equal(err, null); - assert.notEqual(createdUser, undefined); - - nockSFLoginCall(); - nockSFGetProfileCall(SF_PROFILE); - - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?code=a1b2c3d4e5f6'; - options.followAllRedirects = true; + assert.notEqual(foundUser.platforms, undefined, 'stored user must contain a platforms array'); + assert.equal(foundUser.platforms.length, 1, 'stored user must contain 1 platform'); + assert.equal(foundUser.platforms[0].accessToken.params.access_token, 'a1b2c3d4e5f6', 'invalid access token stored'); - request(options, function (err, res, body) { + ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, tokenInfo) { assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - body = JSON.parse(body); - assert.notEqual(body.refreshToken, undefined); - assert.notEqual(body.expiresIn, undefined); + assert.equal(tokenInfo.userId, createdUser._id, 'bad accessToken userId'); - dao.getFromId(createdUser._id, function (err, foundUser) { + ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, tokenInfo) { assert.equal(err, null); - assert.notEqual(foundUser.platforms, undefined, 'stored user must contain a platforms array'); - assert.equal(foundUser.platforms.length, 1, 'stored user must contain 1 platform'); - assert.equal(foundUser.platforms[0].accessToken.params.access_token, 'a1b2c3d4e5f6', 'invalid access token stored'); - - ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, tokenInfo) { - assert.equal(err, null); - assert.equal(tokenInfo.userId, createdUser._id, 'bad accessToken userId'); - - ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, tokenInfo) { - assert.equal(err, null); - assert.equal(tokenInfo.userId, createdUser._id, 'bad refreshToken userId'); - done(); - }); - }); + assert.equal(tokenInfo.userId, createdUser._id, 'bad refreshToken userId'); + done(); }); - }); }); - }); - it('401 deny permissions to SF', function (done) { - var options = _.clone(OPTIONS); - options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?error=access_denied&error_description=end-user+denied+authorization'; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 401, body); - body = JSON.parse(body); - assert.deepEqual(body, {"err": "access_denied", "des": "end-user denied authorization"}); - done(); - }); }); }); - } -}; + }); + + it('401 deny permissions to SF', function (done) { + var options = _.clone(OPTIONS); + options.url = 'http://localhost:' + config.public_port + '/auth/sf/callback?error=access_denied&error_description=end-user+denied+authorization'; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 401, body); + body = JSON.parse(body); + assert.deepEqual(body, {"err": "access_denied", "des": "end-user denied authorization"}); + done(); + }); + }); +}); var OPTIONS = { url: 'http://localhost:' + config.public_port + '/auth/sf', @@ -214,7 +213,7 @@ var OPTIONS = { followRedirect: false }; -function nockSFLoginCall() { +function nockSFLoginCall () { nock('https://login.salesforce.com') .filteringPath(function (path) { if (path.indexOf('/services/oauth2/authorize') > -1) { @@ -234,13 +233,13 @@ function nockSFLoginCall() { }); } -function nockSFGetProfileCall(profile) { +function nockSFGetProfileCall (profile) { nock('https://cs15.salesforce.com') .get('/id/00De00000004cdeEAA/005e0000001uNIyAAM') .reply(200, profile); } -function nockSFGetOptInfo() { +function nockSFGetOptInfo () { nock('https://cs15.salesforce.com') .get('/services/data/v26.0/chatter/users/005e0000001uNIyAAM') .reply(200, { diff --git a/tests-unit/auth/user.js b/tests-unit/auth/user.js index f60a011..a24583d 100644 --- a/tests-unit/auth/user.js +++ b/tests-unit/auth/user.js @@ -13,406 +13,402 @@ var redisMng = require('../../src/managers/redis'); var versionHeader = 'test/1'; -module.exports = { - describe: function () { - describe('/user', function () { +// TODO: if config.management does not exist or is incorrect POST and DELETE to /auth/user must return 404 +// for this test config should be edited, doing so a white box unit test or either change way of loading config file - beforeEach(function (done) { - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - done(); - }); - }); +var username = 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); +var password = 'validpassword'; +var phone = '111111111'; - it('POST 201 created', function (done) { - var options = { - url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', - headers: HEADERS_WITH_AUTHORIZATION_BASIC, - method: 'POST', - body: JSON.stringify({username: username, password: password, phone: phone}) - }; - options.headers[config.version.header] = versionHeader; +var USER = { + id: 'a1b2c3d4e5f6', + username: username, + password: password, + phone: phone +}; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 201, body); - body = JSON.parse(body); - assert.equal(body.username, username); - assert.equal(body.password, undefined); - done(); - }); +var HEADERS_WITHOUT_AUTHORIZATION_BASIC = { + 'Content-Type': 'application/json; charset=utf-8' +}; + +var HEADERS_WITH_AUTHORIZATION_BASIC = { + 'Content-Type': 'application/json; charset=utf-8', + 'Authorization': 'basic ' + new Buffer(config.management.clientId + ':' + config.management.clientSecret).toString('base64') +}; + +describe('Auth /user', function () { + + beforeEach(function (done) { + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + done(); + }); + }); + + it('POST 201 created', function (done) { + var options = { + url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', + headers: HEADERS_WITH_AUTHORIZATION_BASIC, + method: 'POST', + body: JSON.stringify({username: username, password: password, phone: phone}) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 201, body); + body = JSON.parse(body); + assert.equal(body.username, username); + assert.equal(body.password, undefined); + done(); + }); + }); + + it('401 Not authorized when trying to POST to /auth/user without basic authorization', function (done) { + var options = { + url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', + headers: HEADERS_WITHOUT_AUTHORIZATION_BASIC, + method: 'POST', + body: JSON.stringify({username: username, password: password}) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res) { + assert.equal(err, null); + assert.equal(res.statusCode, 401); + done(); + }); + }); + + it('POST 409 already exists', function (done) { + dao.addUser()(USER, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, null); + + var options = { + url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', + headers: HEADERS_WITH_AUTHORIZATION_BASIC, + method: 'POST', + body: JSON.stringify({username: USER.username, password: USER.password}) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 409); + body = JSON.parse(body); + assert.equal(body.err, 'username_already_exists'); + done(); + }); + }); + }); + + it('401 Not authorized when trying to POST an existing user without basic auth', function (done) { + dao.addUser()(USER, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, null); + + var options = { + url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', + headers: HEADERS_WITHOUT_AUTHORIZATION_BASIC, + method: 'POST', + body: JSON.stringify({username: USER.username, password: USER.password}) + }; + + request(options, function (err, res) { + assert.equal(err, null); + assert.equal(res.statusCode, 401); + done(); }); + }); + }); + + it('DELETE 204', function (done) { + dao.addUser()(USER, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, null); - it('401 Not authorized when trying to POST to /auth/user without basic authorization', function (done) { - var options = { - url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', - headers: HEADERS_WITHOUT_AUTHORIZATION_BASIC, - method: 'POST', - body: JSON.stringify({username: username, password: password}) - }; - options.headers[config.version.header] = versionHeader; + var options = { + url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', + headers: HEADERS_WITH_AUTHORIZATION_BASIC, + method: 'DELETE' + }; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 204); + assert.equal(body, ''); - request(options, function (err, res) { + dao.countUsers(function (err, count) { assert.equal(err, null); - assert.equal(res.statusCode, 401); + assert.equal(count, 0); done(); }); }); + }); + }); - it('POST 409 already exists', function (done) { - dao.addUser()(USER, function (err, createdUser) { - assert.equal(err, null); - assert.notEqual(createdUser, null); + it('401 Not authorized when trying to delete without basic authorization', function (done) { + dao.addUser()(USER, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, null); - var options = { - url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', - headers: HEADERS_WITH_AUTHORIZATION_BASIC, - method: 'POST', - body: JSON.stringify({username: USER.username, password: USER.password}) - }; - options.headers[config.version.header] = versionHeader; + var options = { + url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', + headers: HEADERS_WITHOUT_AUTHORIZATION_BASIC, + method: 'DELETE' + }; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 409); - body = JSON.parse(body); - assert.equal(body.err, 'username_already_exists'); - done(); - }); - }); - }); + request(options, function (err, res) { + assert.equal(err, null); + assert.equal(res.statusCode, 401); - it('401 Not authorized when trying to POST an existing user without basic auth', function (done) { - dao.addUser()(USER, function (err, createdUser) { + dao.countUsers(function (err, count) { assert.equal(err, null); - assert.notEqual(createdUser, null); - - var options = { - url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', - headers: HEADERS_WITHOUT_AUTHORIZATION_BASIC, - method: 'POST', - body: JSON.stringify({username: USER.username, password: USER.password}) - }; + assert.equal(count, 1); + }); - request(options, function (err, res) { + options.headers = HEADERS_WITH_AUTHORIZATION_BASIC; + request(options, function (err) { + assert.equal(err, null); + dao.countUsers(function (err, count) { assert.equal(err, null); - assert.equal(res.statusCode, 401); + assert.equal(count, 0); done(); }); }); }); + }); + }); + + var tokenSettings = { + cipherKey: config.accessToken.cipherKey, + firmKey: config.accessToken.signKey, + tokenExpirationMinutes: config.accessToken.expiration * 60 + }; + + describe('/user/activate', function () { + + beforeEach(function (done) { + async.series([ + function (done) { + redisMng.connect(done); + }, + function (done) { + redisMng.deleteAllKeys(done); + } + ], done); + }); - it('DELETE 204', function (done) { - dao.addUser()(USER, function (err, createdUser) { - assert.equal(err, null); - assert.notEqual(createdUser, null); + it('Create OK (iOS device) ', function (done) { + var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); + + var bodyData = { + firstName: 'Firstname', + lastName: 'Lastname', + password: password, + country: 'US', + phone: phone, + email: username, + transactionId: transactionId + }; - var options = { - url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', - headers: HEADERS_WITH_AUTHORIZATION_BASIC, - method: 'DELETE' - }; + var redisKey = config.emailVerification.redis.key; + redisKey = redisKey.replace('{username}', bodyData.email); + var redisExp = config.emailVerification.redis.expireInSec; - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 204); - assert.equal(body, ''); - - dao.countUsers(function (err, count) { - assert.equal(err, null); - assert.equal(count, 0); - done(); - }); - }); - }); - }); + redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { + assert.equal(err, null); - it('401 Not authorized when trying to delete without basic authorization', function (done) { - dao.addUser()(USER, function (err, createdUser) { + ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { assert.equal(err, null); - assert.notEqual(createdUser, null); var options = { - url: 'http://' + config.private_host + ':' + config.internal_port + '/auth/user', - headers: HEADERS_WITHOUT_AUTHORIZATION_BASIC, - method: 'DELETE' + url: 'http://' + config.private_host + ':' + config.public_port + '/user/activate?verifyToken=' + token, + method: 'GET', + headers: {}, + followRedirect: false }; + options.headers['user-agent'] = "Apple-iPhone5C2/1001.525"; - request(options, function (err, res) { + nock('http://' + config.private_host + ':' + config.private_port) + .post(config.passThroughEndpoint.path) + .reply(201, {id: USER.id}); + + request(options, function (err, res, body) { assert.equal(err, null); - assert.equal(res.statusCode, 401); - - dao.countUsers(function (err, count) { - assert.equal(err, null); - assert.equal(count, 1); - }); - - options.headers = HEADERS_WITH_AUTHORIZATION_BASIC; - request(options, function (err) { - assert.equal(err, null); - dao.countUsers(function (err, count) { - assert.equal(err, null); - assert.equal(count, 0); - done(); - }); - }); + assert.equal(res.statusCode, 302, body); + assert.notEqual(res.headers.location.indexOf(config.emailVerification.scheme + '://user/refreshToken/'), -1); + done(); }); }); + }); + }); - var tokenSettings = { - cipherKey: config.accessToken.cipherKey, - firmKey: config.accessToken.signKey, - tokenExpirationMinutes: config.accessToken.expiration * 60 + it('Create OK (Android device) ', function (done) { + var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); + + var bodyData = { + firstName: 'Firstname', + lastName: 'Lastname', + password: password, + country: 'US', + phone: phone, + email: username, + transactionId: transactionId }; - describe('/user/activate', function () { - - beforeEach(function (done) { - async.series([ - function (done) { - redisMng.connect(done); - }, - function (done) { - redisMng.deleteAllKeys(done); - } - ], done); - }); + var redisKey = config.emailVerification.redis.key; + redisKey = redisKey.replace('{username}', bodyData.email); + var redisExp = config.emailVerification.redis.expireInSec; - it('Create OK (iOS device) ', function (done) { - var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); - - var bodyData = { - firstName: 'Firstname', - lastName: 'Lastname', - password: password, - country: 'US', - phone: phone, - email: username, - transactionId: transactionId - }; + redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { + assert.equal(err, null); - var redisKey = config.emailVerification.redis.key; - redisKey = redisKey.replace('{username}', bodyData.email); - var redisExp = config.emailVerification.redis.expireInSec; + ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { + assert.equal(err, null); - redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { - assert.equal(err, null); + var options = { + url: 'http://' + config.private_host + ':' + config.public_port + '/user/activate?verifyToken=' + token, + method: 'GET', + headers: {}, + followRedirect: false + }; + options.headers['user-agent'] = "Mozilla/5.0 (Linux; U; Android 2.2; nb-no; HTC Desire Build/FRF91)"; - ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { - assert.equal(err, null); - - var options = { - url: 'http://' + config.private_host + ':' + config.public_port + '/user/activate?verifyToken=' + token, - method: 'GET', - headers: {}, - followRedirect: false - }; - options.headers['user-agent'] = "Apple-iPhone5C2/1001.525"; - - nock('http://' + config.private_host + ':' + config.private_port) - .post(config.passThroughEndpoint.path) - .reply(201, {id: USER.id}); - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - assert.notEqual(res.headers.location.indexOf(config.emailVerification.scheme + '://user/refreshToken/'), -1); - done(); - }); - }); + nock('http://' + config.private_host + ':' + config.private_port) + .post(config.passThroughEndpoint.path) + .reply(201, {id: USER.id}); + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 302, body); + assert.notEqual(res.headers.location.indexOf('intent://user/refreshToken/'), -1); + done(); }); }); - it('Create OK (Android device) ', function (done) { - var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); - - var bodyData = { - firstName: 'Firstname', - lastName: 'Lastname', - password: password, - country: 'US', - phone: phone, - email: username, - transactionId: transactionId - }; + }); + }); - var redisKey = config.emailVerification.redis.key; - redisKey = redisKey.replace('{username}', bodyData.email); - var redisExp = config.emailVerification.redis.expireInSec; + it('Create OK (not an iOS or Android device) without redirect option ', function (done) { + var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); + var thisConfig = _.clone(config); + thisConfig.emailVerification.redirectUrl = null; + + var bodyData = { + firstName: 'Firstname', + lastName: 'Lastname', + password: password, + country: 'US', + phone: phone, + email: username, + transactionId: transactionId + }; - redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { - assert.equal(err, null); + var redisKey = thisConfig.emailVerification.redis.key; + redisKey = redisKey.replace('{username}', bodyData.email); + var redisExp = thisConfig.emailVerification.redis.expireInSec; - ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { - assert.equal(err, null); - - var options = { - url: 'http://' + config.private_host + ':' + config.public_port + '/user/activate?verifyToken=' + token, - method: 'GET', - headers: {}, - followRedirect: false - }; - options.headers['user-agent'] = "Mozilla/5.0 (Linux; U; Android 2.2; nb-no; HTC Desire Build/FRF91)"; - - nock('http://' + config.private_host + ':' + config.private_port) - .post(config.passThroughEndpoint.path) - .reply(201, {id: USER.id}); - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 302, body); - assert.notEqual(res.headers.location.indexOf('intent://user/refreshToken/'), -1); - done(); - }); - }); + redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { + assert.equal(err, null); - }); - }); + ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { + assert.equal(err, null); - it('Create OK (not an iOS or Android device) without redirect option ', function (done) { - var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); - var thisConfig = _.clone(config); - thisConfig.emailVerification.redirectUrl = null; - - var bodyData = { - firstName: 'Firstname', - lastName: 'Lastname', - password: password, - country: 'US', - phone: phone, - email: username, - transactionId: transactionId + var options = { + url: 'http://' + thisConfig.private_host + ':' + thisConfig.public_port + '/user/activate?verifyToken=' + token, + method: 'GET', + headers: {}, + followRedirect: false }; + options.headers['user-agent'] = "Mozilla/5.0"; - var redisKey = thisConfig.emailVerification.redis.key; - redisKey = redisKey.replace('{username}', bodyData.email); - var redisExp = thisConfig.emailVerification.redis.expireInSec; + nock('http://' + thisConfig.private_host + ':' + thisConfig.private_port) + .post(thisConfig.passThroughEndpoint.path) + .reply(201, {id: USER.id}); - redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { + request(options, function (err, res, body) { assert.equal(err, null); - - ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { - assert.equal(err, null); - - var options = { - url: 'http://' + thisConfig.private_host + ':' + thisConfig.public_port + '/user/activate?verifyToken=' + token, - method: 'GET', - headers: {}, - followRedirect: false - }; - options.headers['user-agent'] = "Mozilla/5.0"; - - nock('http://' + thisConfig.private_host + ':' + thisConfig.private_port) - .post(thisConfig.passThroughEndpoint.path) - .reply(201, {id: USER.id}); - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - body = JSON.parse(body); - assert.deepEqual(body, {msg: thisConfig.emailVerification.nonCompatibleEmailMsg}); - done(); - }); - }); - + assert.equal(res.statusCode, 200, body); + body = JSON.parse(body); + assert.deepEqual(body, {msg: thisConfig.emailVerification.nonCompatibleEmailMsg}); + done(); }); }); - it('Create OK (not an iOS or Android device) with redirect option', function (done) { - var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); - var thisConfig = _.clone(config); - thisConfig.emailVerification.redirectUrl = 'http://www.google.com'; - - var bodyData = { - firstName: 'Firstname', - lastName: 'Lastname', - password: password, - country: 'US', - phone: phone, - email: username, - transactionId: transactionId - }; - - var redisKey = thisConfig.emailVerification.redis.key; - redisKey = redisKey.replace('{username}', bodyData.email); - var redisExp = thisConfig.emailVerification.redis.expireInSec; + }); + }); - redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { - assert.equal(err, null); + it('Create OK (not an iOS or Android device) with redirect option', function (done) { + var transactionId = crypto.pseudoRandomBytes(12).toString('hex'); + var thisConfig = _.clone(config); + thisConfig.emailVerification.redirectUrl = 'http://www.google.com'; + + var bodyData = { + firstName: 'Firstname', + lastName: 'Lastname', + password: password, + country: 'US', + phone: phone, + email: username, + transactionId: transactionId + }; - ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { - assert.equal(err, null); - - var options = { - url: 'http://' + thisConfig.private_host + ':' + thisConfig.public_port + '/user/activate?verifyToken=' + token, - method: 'GET', - headers: {}, - followRedirect: false - }; - options.headers['user-agent'] = "Mozilla/5.0"; - - nock('http://' + thisConfig.private_host + ':' + thisConfig.private_port) - .post(thisConfig.passThroughEndpoint.path) - .reply(201, {id: USER.id}); - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 301, body); - assert.equal(res.headers.location, thisConfig.emailVerification.redirectUrl); - done(); - }); - }); + var redisKey = thisConfig.emailVerification.redis.key; + redisKey = redisKey.replace('{username}', bodyData.email); + var redisExp = thisConfig.emailVerification.redis.expireInSec; - }); - }); + redisMng.insertKeyValue(redisKey, transactionId, redisExp, function (err) { + assert.equal(err, null); - it('No verify token param', function (done) { - var expectedResponseBody = { - err: 'auth_proxy_error', - des: 'empty param verifyToken' - }; + ciphertoken.createToken(tokenSettings, username, null, bodyData, function (err, token) { + assert.equal(err, null); var options = { - url: 'http://' + config.private_host + ':' + config.public_port + '/user/activate', - method: 'GET' + url: 'http://' + thisConfig.private_host + ':' + thisConfig.public_port + '/user/activate?verifyToken=' + token, + method: 'GET', + headers: {}, + followRedirect: false }; + options.headers['user-agent'] = "Mozilla/5.0"; + + nock('http://' + thisConfig.private_host + ':' + thisConfig.private_port) + .post(thisConfig.passThroughEndpoint.path) + .reply(201, {id: USER.id}); request(options, function (err, res, body) { assert.equal(err, null); - assert.equal(res.statusCode, 400, body); - body = JSON.parse(body); - assert.deepEqual(body, expectedResponseBody); + assert.equal(res.statusCode, 301, body); + assert.equal(res.headers.location, thisConfig.emailVerification.redirectUrl); done(); }); }); }); - }); - } - // TODO: if config.management does not exist or is incorrect POST and DELETE to /auth/user must return 404 - // for this test config should be edited, doing so a white box unit test or either change way of loading config file -}; + it('No verify token param', function (done) { + var expectedResponseBody = { + err: 'auth_proxy_error', + des: 'empty param verifyToken' + }; -var username = 'validuser' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); -var password = 'validpassword'; -var phone = '111111111'; + var options = { + url: 'http://' + config.private_host + ':' + config.public_port + '/user/activate', + method: 'GET' + }; -var USER = { - id: 'a1b2c3d4e5f6', - username: username, - password: password, - phone: phone -}; + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 400, body); + body = JSON.parse(body); + assert.deepEqual(body, expectedResponseBody); + done(); + }); + }); -var HEADERS_WITHOUT_AUTHORIZATION_BASIC = { - 'Content-Type': 'application/json; charset=utf-8' -}; + }); -var HEADERS_WITH_AUTHORIZATION_BASIC = { - 'Content-Type': 'application/json; charset=utf-8', - 'Authorization': 'basic ' + new Buffer(config.management.clientId + ':' + config.management.clientSecret).toString('base64') -}; +}); diff --git a/tests-unit/dao.js b/tests-unit/dao.js index 9291c47..3f45485 100644 --- a/tests-unit/dao.js +++ b/tests-unit/dao.js @@ -17,36 +17,26 @@ describe('user dao', function () { var fakeCollection = {}; var fakeDb = {}; var fakeFind = {}; + var noop = () => {}; beforeEach(function (done) { fakeCollection = { - remove: function () { - }, - count: function () { - }, - find: function () { - }, - insert: function () { - }, - update: function () { - }, - ensureIndex: function () { - }, - toArray: function () { - - } + remove: noop, + count: noop, + find: noop, + insert: noop, + update: noop, + ensureIndex: noop, + toArray: noop }; fakeDb = { - collection: function () { - }, - close: function () { - } + collection: noop, + close: noop }; fakeFind = { - nextObject: function () { - } + nextObject: noop }; sinon.stub(fakeCollection, 'remove').yields(); diff --git a/tests-unit/email.js b/tests-unit/email.js index 2d6cf5e..4c83b9f 100644 --- a/tests-unit/email.js +++ b/tests-unit/email.js @@ -8,77 +8,77 @@ var config = require('../config.json'); var notifServiceURL = config.externalServices.notifications.base; var notifServicePath = config.externalServices.notifications.pathEmail; -describe('email', function() { +describe('email', function () { - beforeEach(function(done){ - async.series([ - function(done){ - redisMng.connect(done); - }, - function(done){ - redisMng.deleteAllKeys(done); - } - ],done); - }); + beforeEach(function (done) { + async.series([ + function (done) { + redisMng.connect(done); + }, + function (done) { + redisMng.deleteAllKeys(done); + } + ], done); + }); - it('verifyEmail', function (done) { - var emailMng = require('../src/managers/email')({ - "useEmailVerification": true - }); + it('verifyEmail', function (done) { + var emailMng = require('../src/managers/email')({ + "useEmailVerification": true + }); - nock(notifServiceURL) - .post(notifServicePath) - .reply(204); + nock(notifServiceURL) + .post(notifServicePath) + .reply(204); - var email = "test@test.com"; - var bodyData = { - key : "value", - key2: "value2" - }; - emailMng.emailVerification(email, bodyData, function(err, returnedEmail){ - assert.equal(err, null); - assert.equal(returnedEmail, email); - done(); - }); - }); + var email = "test@test.com"; + var bodyData = { + key: "value", + key2: "value2" + }; + emailMng.emailVerification(email, bodyData, function (err, returnedEmail) { + assert.equal(err, null); + assert.equal(returnedEmail, email); + done(); + }); + }); - it('verifyEmail (not email)', function (done) { - var emailMng = require('../src/managers/email')({ - "useEmailVerification": true - }); + it('verifyEmail (not email)', function (done) { + var emailMng = require('../src/managers/email')({ + "useEmailVerification": true + }); - var expected_error = {"err":"auth_proxy_error","des":"empty email"}; + var expected_error = {"err": "auth_proxy_error", "des": "empty email"}; - nock(notifServiceURL) - .post('/notification/email') - .reply(204); + nock(notifServiceURL) + .post('/notification/email') + .reply(204); - var email = null; - var bodyData = { - key : "value", - key2: "value2" - }; - emailMng.emailVerification(email, bodyData, function(err, returnedEmail){ - assert.deepEqual(err, expected_error); + var email = null; + var bodyData = { + key: "value", + key2: "value2" + }; + emailMng.emailVerification(email, bodyData, function (err, returnedEmail) { + assert.deepEqual(err, expected_error); assert.equal(returnedEmail, null); - done(); - }); - }); + done(); + }); + }); - it('verifyEmail (useEmailVerification = false)', function (done) { - var emailMng = require('../src/managers/email')({ - "emailVerification": false - }); + it('verifyEmail (useEmailVerification = false)', function (done) { + var emailMng = require('../src/managers/email')({ + "emailVerification": false + }); - var email = "test@test.com"; - var bodyData = { - key : "value", - key2: "value2" - }; - emailMng.emailVerification(email, bodyData, function(err, returnedEmail){ - assert.equal(err, null); - assert.equal(returnedEmail, null); - done(); - }); - }); + var email = "test@test.com"; + var bodyData = { + key: "value", + key2: "value2" + }; + emailMng.emailVerification(email, bodyData, function (err, returnedEmail) { + assert.equal(err, null); + assert.equal(returnedEmail, null); + done(); + }); + }); }); diff --git a/tests-unit/emailAvailable.js b/tests-unit/emailAvailable.js index 6336ec2..2d77cb3 100644 --- a/tests-unit/emailAvailable.js +++ b/tests-unit/emailAvailable.js @@ -1,7 +1,6 @@ var assert = require('assert'); var request = require('request'); -var cipherlayer = require('../src/cipherlayer'); var config = require('../config.json'); var userDao = require('../src/managers/dao'); @@ -14,19 +13,12 @@ var baseUser = { describe('Check Email Available endpoint', function () { beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, function (error) { + userDao.deleteAllUsers(function (error) { assert.equal(error, null); - userDao.deleteAllUsers(function (error) { - assert.equal(error, null); - return done(); - }); + return done(); }); }); - afterEach(function (done) { - cipherlayer.stop(done); - }); - it('should indicate that requested email is available', function (done) { var requestOptions = { diff --git a/tests-unit/fileStore.js b/tests-unit/fileStore.js index 75b0657..af1f218 100644 --- a/tests-unit/fileStore.js +++ b/tests-unit/fileStore.js @@ -4,13 +4,8 @@ var fs = require('fs'); var config = require('../config.json'); describe('AWS', function () { - beforeEach(function (done) { - done(); - }); - afterEach(function (done) { - done(); - }); + this.timeout(10000); var configAWSParam = false; var validBucket; @@ -61,8 +56,6 @@ describe('AWS', function () { it('upload invalid bucket', function (done) { if (!configAWSParam) return done(); - this.timeout(5000); - fs.readFile(uploadImage.path, function (err, data) { assert.equal(err, null); var file = new Buffer(data, 'binary'); @@ -102,8 +95,6 @@ describe('AWS', function () { it.skip('upload valid image', function (done) { if (!configAWSParam) return done(); - this.timeout(10000); - fs.readFile(uploadImage.path, function (err, data) { assert.equal(err, null); var file = new Buffer(data, 'binary'); @@ -118,8 +109,6 @@ describe('AWS', function () { it.skip('upload valid zip', function (done) { if (!configAWSParam) return done(); - this.timeout(10000); - fs.readFile(uploadZip.path, function (err, data) { assert.equal(err, null); var file = new Buffer(data, 'binary'); diff --git a/tests-unit/heartbeat.js b/tests-unit/heartbeat.js index ae1e50f..05446f7 100644 --- a/tests-unit/heartbeat.js +++ b/tests-unit/heartbeat.js @@ -1,21 +1,12 @@ var assert = require('assert'); var request = require('request'); var config = require('../config.json'); -var cipherlayer = require('../src/cipherlayer'); var userDao = require('../src/managers/dao'); var redisMng = require('../src/managers/redis'); describe('Heartbeat (Server status)', function () { - beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, done); - }); - - afterEach(function (done) { - cipherlayer.stop(done); - }); - it('OK', function (done) { var options = { url: 'http://localhost:' + config.public_port + '/heartbeat', diff --git a/tests-unit/jsonValidator.js b/tests-unit/jsonValidator.js index 17af7a8..90b3153 100644 --- a/tests-unit/jsonValidator.js +++ b/tests-unit/jsonValidator.js @@ -29,4 +29,4 @@ describe('jsonValidator', function () { assert.equal(result, true); done(); }); -}); \ No newline at end of file +}); diff --git a/tests-unit/managerUser.js b/tests-unit/managerUser.js index aefcb2b..04141d1 100644 --- a/tests-unit/managerUser.js +++ b/tests-unit/managerUser.js @@ -54,7 +54,7 @@ var configSettings = { describe('user Manager', function () { - function validatePwd(clear, crypted, cbk) { + function validatePwd (clear, crypted, cbk) { var cryptoMng = crypto(config.password); cryptoMng.verify(clear, crypted, function (err) { assert.equal(err, null); diff --git a/tests-unit/managers/crypto.js b/tests-unit/managers/crypto.js index da1f6de..f5319cd 100644 --- a/tests-unit/managers/crypto.js +++ b/tests-unit/managers/crypto.js @@ -4,10 +4,10 @@ var should = require('chai').should(); var config = require(process.cwd() + '/config.json'); var cryptoManager = require('../../src/managers/crypto')(); -describe('managers', function(){ - describe('crypto', function(){ - describe('random password generation', function(){ - it('OK', function(done){ +describe('managers', function () { + describe('crypto', function () { + describe('random password generation', function () { + it('OK', function (done) { var newPassword = cryptoManager.randomPassword(config.password.generatedRegex); var match = newPassword.match(config.password.regexValidation); should.exist(match); diff --git a/tests-unit/middlewares/decodeToken.js b/tests-unit/middlewares/decodeToken.js index b706ae3..ae2a8e6 100644 --- a/tests-unit/middlewares/decodeToken.js +++ b/tests-unit/middlewares/decodeToken.js @@ -13,7 +13,7 @@ var accessTokenSettings = { describe('middleware', function () { describe('decodeToken', function () { - it('OK - lowercase authorization header', function(done){ + it('OK - lowercase authorization header', function (done) { var userId = 'A1B2C3D4'; var data = {data: 'some data'}; ciphertoken.createToken(accessTokenSettings, userId, null, data, function (err, accessToken) { @@ -39,7 +39,7 @@ describe('middleware', function () { }); }); - it('OK - uppercase authorization header', function(done){ + it('OK - uppercase authorization header', function (done) { var userId = 'A1B2C3D4'; var data = {data: 'some data'}; ciphertoken.createToken(accessTokenSettings, userId, null, data, function (err, accessToken) { diff --git a/tests-unit/phone.js b/tests-unit/phone.js index d1db8bf..1d8f4e9 100644 --- a/tests-unit/phone.js +++ b/tests-unit/phone.js @@ -1,10 +1,9 @@ var assert = require('assert'); var async = require('async'); +var nock = require('nock'); + var phoneMng = require('../src/managers/phone'); var redisMng = require('../src/managers/redis'); -var cipherlayer = require('../src/cipherlayer'); - -var nock = require('nock'); var config = require('../config.json'); @@ -38,33 +37,13 @@ describe('phone', function () { var notifServiceURL = config.externalServices.notifications.base; beforeEach(function (done) { - async.parallel([ - function (done) { - cipherlayer.start(config.public_port, config.internal_port, done); - }, - function (done) { - async.series([ - function (done) { - redisMng.connect(done); - }, - function (done) { - redisMng.deleteAllKeys(done); - } - ], done); - } + async.series([ + redisMng.connect, + redisMng.deleteAllKeys ], done); }); - afterEach(function (done) { - async.parallel([ - function (done) { - cipherlayer.stop(done); - }, - function (done) { - redisMng.disconnect(done); - } - ], done); - }); + afterEach(redisMng.disconnect); it('create pin', function (done) { diff --git a/tests-unit/pinValidation.js b/tests-unit/pinValidation.js index 1eeaf29..bb6f55d 100644 --- a/tests-unit/pinValidation.js +++ b/tests-unit/pinValidation.js @@ -45,7 +45,7 @@ describe('middleware pinValidation', function () { } }; - function getPinNumber(userId, phone, country, cbk) { + function getPinNumber (userId, phone, country, cbk) { countries.countryFromIso(country, function (err, returnedCountry) { assert.equal(err, null); phone = '+' + returnedCountry.Dial + phone; @@ -434,4 +434,4 @@ describe('middleware pinValidation', function () { pinValidation(settings)(req, res, next); }); -}); \ No newline at end of file +}); diff --git a/tests-unit/platforms/salesforce.js b/tests-unit/platforms/salesforce.js index ac71149..d7051e6 100644 --- a/tests-unit/platforms/salesforce.js +++ b/tests-unit/platforms/salesforce.js @@ -1,6 +1,5 @@ var assert = require('assert'); -var cipherlayer = require('../../src/cipherlayer.js'); var sfPlatform = require('../../src/platforms/salesforce.js'); var config = require('../../config.json'); var SF_PROFILE = require('../resources/sfProfileTemplate.js'); @@ -15,13 +14,6 @@ var sfAccessToken = { describe('inject expiresAtTimestamp whit refresh token', function () { - beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, done); - }); - - afterEach(function (done) { - cipherlayer.stop(done); - }); it('expiresAtTimestamp must be provided along with sf refresh token', function (done) { sfPlatform.prepareSession(sfAccessToken, 'refreshToken123456', SF_PROFILE, function (err, data) { diff --git a/tests-unit/proxy.js b/tests-unit/proxy.js index a7a04ac..8f13ca1 100644 --- a/tests-unit/proxy.js +++ b/tests-unit/proxy.js @@ -1,81 +1,41 @@ -var assert = require('assert'); var spawn = require('child_process').spawn; var net = require('net'); -var config = require('../config.json'); var async = require('async'); -var cipherlayer = require('../src/cipherlayer'); -var dao = require('../src/managers/dao.js'); -var describeProtectedCallsStandard = require('./proxy/protectedCallsStandard.js'); -var describeProtectedCallsPassThrough = require('./proxy/protectedCallsPassThrough.js'); -var describeProtectedCallsStandard_SF = require('./proxy/protectedCallsStandard-platformSF.js'); -var accessTokenSettings = { - cipherKey: config.accessToken.cipherKey, - firmKey: config.accessToken.signKey, - tokenExpirationMinutes: config.accessToken.expiration * 60 -}; - -var refreshTokenSettings = { - cipherKey: config.refreshToken.cipherKey, - firmKey: config.refreshToken.signKey, - tokenExpirationMinutes: config.refreshToken.expiration * 1000 -}; +var TEST_PUBLIC_PORT = 4599; +var TEST_INTERNAL_PORT = 4598; describe('proxy', function () { + + this.timeout(5000); + it('launches', function (done) { var cipherlayer; async.series([ - function (done) { - cipherlayer = spawn('node', ['main']); + function (next) { + + cipherlayer = spawn('node', ['main'], { + env: { + PORT: TEST_PUBLIC_PORT, + INTERNAL_PORT: TEST_INTERNAL_PORT + } + }); + cipherlayer.stdout.pipe(process.stdout); + cipherlayer.stderr.pipe(process.stderr); cipherlayer.stdout.on('data', function (data) { if (String(data).indexOf('listening on port') > -1) { - done(); + return next(); } }); }, - function (done) { - var client = net.connect({port: config.public_port}, function () { + function (next) { + var client = net.connect({port: TEST_PUBLIC_PORT}, function () { client.destroy(); cipherlayer.kill('SIGTERM'); - done(); + return next(); }); } - ], function () { - done(); - }); + ], done); }); - describe('protected calls', function () { - beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, function (err) { - assert.equal(err, null); - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - done(); - }); - }); - }); - - afterEach(function (done) { - cipherlayer.stop(done); - }); - - describe('standard', function () { - describeProtectedCallsStandard.itUnauthorized(); - describeProtectedCallsStandard.itWithoutPlatforms(accessTokenSettings); - describeProtectedCallsStandard.itBodyResponseIsNotAJson(accessTokenSettings); - describe('with salesforce', function () { - describeProtectedCallsStandard_SF.itWithSalesforce(accessTokenSettings); - describeProtectedCallsStandard_SF.itRenewSFToken(accessTokenSettings); - }); - }); - - describe('pass through', function () { - describeProtectedCallsPassThrough.itCreated(accessTokenSettings, refreshTokenSettings); - describeProtectedCallsPassThrough.itPlatformInfo(accessTokenSettings, refreshTokenSettings); - describeProtectedCallsPassThrough.itAlreadyExists(accessTokenSettings, refreshTokenSettings); - describeProtectedCallsPassThrough.itNotSecurityToken(); - describeProtectedCallsPassThrough.itCreatedVerifyMail(accessTokenSettings, refreshTokenSettings); - }); - }); }); diff --git a/tests-unit/proxy/protectedCallsPassThrough.js b/tests-unit/proxy/protectedCallsPassThrough.js index 51f8a53..99c1f9f 100644 --- a/tests-unit/proxy/protectedCallsPassThrough.js +++ b/tests-unit/proxy/protectedCallsPassThrough.js @@ -12,158 +12,75 @@ var notificationsServiceURL = config.externalServices.notifications.base; var versionHeader = 'test/1'; -module.exports = { - itCreated: function created(accessTokenSettings, refreshTokenSettings) { - it.skip('201 Created', function (done) { - var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); - var expectedUserId = 'a1b2c3d4e5f6'; - var expectedUserPhone = '111111111'; - var expectedUserCountry = 'US'; - var expectedPublicRequest = {}; - expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; - expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; - expectedPublicRequest.phone = expectedUserPhone; - expectedPublicRequest.country = expectedUserCountry; +var accessTokenSettings = require('../token_settings').accessTokenSettings; +var refreshTokenSettings = require('../token_settings').refreshTokenSettings; - var expectedPrivateResponse = _.clone(expectedPublicRequest); - delete(expectedPrivateResponse[config.passThroughEndpoint.password]); - nock('http://' + config.private_host + ':' + config.private_port) - .post(config.passThroughEndpoint.path, expectedPrivateResponse) - .reply(201, {id: expectedUserId}); - - var redisKey = config.redisKeys.user_phone_verify.key; - redisKey = redisKey.replace('{userId}', expectedUsername).replace('{phone}', '+1' + expectedUserPhone); +describe('Protected calls passThrough', () => { - var pin = 'xxxx'; + it.skip('201 Created', function (done) { + var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); + var expectedUserId = 'a1b2c3d4e5f6'; + var expectedUserPhone = '111111111'; + var expectedUserCountry = 'US'; + var expectedPublicRequest = {}; + expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; + expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; + expectedPublicRequest.phone = expectedUserPhone; + expectedPublicRequest.country = expectedUserCountry; - redisMng.insertKeyValue(redisKey + '.pin', pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { - assert.equal(err, null); - redisMng.insertKeyValue(redisKey + '.attempts', config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { - assert.equal(err, null); + var expectedPrivateResponse = _.clone(expectedPublicRequest); + delete(expectedPrivateResponse[config.passThroughEndpoint.password]); - nock('http://' + config.private_host + ':' + config.private_port) - .post(config.passThroughEndpoint.path, expectedPrivateResponse) - .reply(201, {id: expectedUserId}); + nock('http://' + config.private_host + ':' + config.private_port) + .post(config.passThroughEndpoint.path, expectedPrivateResponse) + .reply(201, {id: expectedUserId}); - var options = { - url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, - headers: { - 'Content-Type': 'application/json; charset=utf-8', - 'x-otp-pin': pin - }, - method: 'POST', - body: JSON.stringify(expectedPublicRequest) - }; - options.headers[config.version.header] = versionHeader; + var redisKey = config.redisKeys.user_phone_verify.key; + redisKey = redisKey.replace('{userId}', expectedUsername).replace('{phone}', '+1' + expectedUserPhone); - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 201, body); - body = JSON.parse(body); + var pin = 'xxxx'; - assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); - assert.notEqual(body.accessToken, undefined); - ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { - assert.equal(err, null); - assert.equal(accessTokenInfo.userId, expectedUserId); - - assert.notEqual(body.refreshToken, undefined); - ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { - assert.equal(err, null); - assert.equal(refreshTokenInfo.userId, expectedUserId); - - dao.getFromUsername(expectedUsername, function (err, foundUser) { - assert.equal(err, null); - assert.equal(foundUser.platforms, undefined); - done(); - }); - }); - }); - }); - - }); - }); - - }); - }, - itPlatformInfo: function platformInfo(accessTokenSettings, refreshTokenSettings) { - it.skip('203 Platform Info', function (done) { - var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); - var expectedUserId = 'a1b2c3d4e5f6'; - var expectedUserPhone = '222222222'; - var expectedUserCountry = 'US'; - var expectedPublicRequest = {}; - expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; - expectedPublicRequest.phone = expectedUserPhone; - expectedPublicRequest.country = expectedUserCountry; - - ciphertoken.createToken(accessTokenSettings, expectedUserId, null, { - accessToken: 'acc', - refreshToken: 'ref', - expiresIn: accessTokenSettings.tokenExpirationMinutes * 60 - }, function (err, sfToken) { - expectedPublicRequest.sf = sfToken; - - var expectedPrivateResponse = _.clone(expectedPublicRequest); - delete(expectedPrivateResponse[config.passThroughEndpoint.password]); + redisMng.insertKeyValue(redisKey + '.pin', pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { + assert.equal(err, null); + redisMng.insertKeyValue(redisKey + '.attempts', config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { + assert.equal(err, null); nock('http://' + config.private_host + ':' + config.private_port) .post(config.passThroughEndpoint.path, expectedPrivateResponse) - .reply(203, {id: expectedUserId}); - - var redisKey = config.redisKeys.user_phone_verify.key; - redisKey = redisKey.replace('{userId}', expectedUsername).replace('{phone}', '+1' + expectedUserPhone); - - var pin = 'xxxx'; - - redisMng.insertKeyValue(redisKey + '.pin', pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { + .reply(201, {id: expectedUserId}); + + var options = { + url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'x-otp-pin': pin + }, + method: 'POST', + body: JSON.stringify(expectedPublicRequest) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { assert.equal(err, null); - redisMng.insertKeyValue(redisKey + '.attempts', config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { + assert.equal(res.statusCode, 201, body); + body = JSON.parse(body); + + assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); + assert.notEqual(body.accessToken, undefined); + ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { assert.equal(err, null); + assert.equal(accessTokenInfo.userId, expectedUserId); - var options = { - url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, - headers: { - 'Content-Type': 'application/json; charset=utf-8', - 'x-otp-pin': pin - }, - method: 'POST', - body: JSON.stringify(expectedPublicRequest) - }; - options.headers[config.version.header] = versionHeader; - - nock(notificationsServiceURL) - .post('/notification/email') - .reply(204); - - request(options, function (err, res, body) { + assert.notEqual(body.refreshToken, undefined); + ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { assert.equal(err, null); - assert.equal(res.statusCode, 201); - body = JSON.parse(body); + assert.equal(refreshTokenInfo.userId, expectedUserId); - assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); - assert.notEqual(body.accessToken, undefined); - ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { + dao.getFromUsername(expectedUsername, function (err, foundUser) { assert.equal(err, null); - assert.equal(accessTokenInfo.userId, expectedUserId); - - assert.notEqual(body.refreshToken, undefined); - ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { - assert.equal(err, null); - assert.equal(refreshTokenInfo.userId, expectedUserId); - - dao.getFromUsername(expectedUsername, function (err, foundUser) { - assert.equal(err, null); - assert.notEqual(foundUser.platforms, undefined); - assert.equal(foundUser.platforms.length, 1); - assert.equal(foundUser.platforms[0].platform, 'sf'); - assert.equal(foundUser.platforms[0].accessToken, 'acc'); - assert.equal(foundUser.platforms[0].refreshToken, 'ref'); - assert.notEqual(foundUser.platforms[0].expiry, undefined); - done(); - }); - }); + assert.equal(foundUser.platforms, undefined); + done(); }); }); }); @@ -171,25 +88,32 @@ module.exports = { }); }); - }, - itAlreadyExists: function alreadyExists(accessTokenSettings, refreshTokenSettings) { - it.skip('409 already exists', function (done) { - var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); - var expectedUserId = 'a1b2c3d4e5f6'; - var expectedPublicRequest = {}; - var expectedUserPhone = '222222222'; - var expectedUserCountry = 'US'; - expectedPublicRequest[config.passThroughEndpoint.username] = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); - expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; - expectedPublicRequest.phone = expectedUserPhone; - expectedPublicRequest.country = expectedUserCountry; + + }); + + it.skip('203 Platform Info', function (done) { + var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); + var expectedUserId = 'a1b2c3d4e5f6'; + var expectedUserPhone = '222222222'; + var expectedUserCountry = 'US'; + var expectedPublicRequest = {}; + expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; + expectedPublicRequest.phone = expectedUserPhone; + expectedPublicRequest.country = expectedUserCountry; + + ciphertoken.createToken(accessTokenSettings, expectedUserId, null, { + accessToken: 'acc', + refreshToken: 'ref', + expiresIn: accessTokenSettings.tokenExpirationMinutes * 60 + }, function (err, sfToken) { + expectedPublicRequest.sf = sfToken; var expectedPrivateResponse = _.clone(expectedPublicRequest); delete(expectedPrivateResponse[config.passThroughEndpoint.password]); nock('http://' + config.private_host + ':' + config.private_port) .post(config.passThroughEndpoint.path, expectedPrivateResponse) - .reply(201, {id: expectedUserId}); + .reply(203, {id: expectedUserId}); var redisKey = config.redisKeys.user_phone_verify.key; redisKey = redisKey.replace('{userId}', expectedUsername).replace('{phone}', '+1' + expectedUserPhone); @@ -218,7 +142,7 @@ module.exports = { request(options, function (err, res, body) { assert.equal(err, null); - assert.equal(res.statusCode, 201, body); + assert.equal(res.statusCode, 201); body = JSON.parse(body); assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); @@ -231,105 +155,181 @@ module.exports = { ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { assert.equal(err, null); assert.equal(refreshTokenInfo.userId, expectedUserId); - done(); + + dao.getFromUsername(expectedUsername, function (err, foundUser) { + assert.equal(err, null); + assert.notEqual(foundUser.platforms, undefined); + assert.equal(foundUser.platforms.length, 1); + assert.equal(foundUser.platforms[0].platform, 'sf'); + assert.equal(foundUser.platforms[0].accessToken, 'acc'); + assert.equal(foundUser.platforms[0].refreshToken, 'ref'); + assert.notEqual(foundUser.platforms[0].expiry, undefined); + done(); + }); }); }); }); }); }); + }); - }, - itNotSecurityToken: function notSecurityToken() { - it('400 not security token', function (done) { - var expectedPublicRequest = {}; - expectedPublicRequest[config.passThroughEndpoint.username] = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); - - var options = { - url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, - headers: { - 'Content-Type': 'application/json; charset=utf-8' - }, - method: 'POST', - body: JSON.stringify(expectedPublicRequest) - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { + }); + + it.skip('409 already exists', function (done) { + var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); + var expectedUserId = 'a1b2c3d4e5f6'; + var expectedPublicRequest = {}; + var expectedUserPhone = '222222222'; + var expectedUserCountry = 'US'; + expectedPublicRequest[config.passThroughEndpoint.username] = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); + expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; + expectedPublicRequest.phone = expectedUserPhone; + expectedPublicRequest.country = expectedUserCountry; + + var expectedPrivateResponse = _.clone(expectedPublicRequest); + delete(expectedPrivateResponse[config.passThroughEndpoint.password]); + + nock('http://' + config.private_host + ':' + config.private_port) + .post(config.passThroughEndpoint.path, expectedPrivateResponse) + .reply(201, {id: expectedUserId}); + + var redisKey = config.redisKeys.user_phone_verify.key; + redisKey = redisKey.replace('{userId}', expectedUsername).replace('{phone}', '+1' + expectedUserPhone); + + var pin = 'xxxx'; + + redisMng.insertKeyValue(redisKey + '.pin', pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { + assert.equal(err, null); + redisMng.insertKeyValue(redisKey + '.attempts', config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { assert.equal(err, null); - assert.equal(res.statusCode, 400); - body = JSON.parse(body); - assert.equal(body.err, 'invalid_security_token'); - assert.equal(body.des, 'you must provide a password or a salesforce token to create the user'); - done(); - }); - }); - }, - itCreatedVerifyMail: function createdVerifyMail() { - it.skip('201 Created (Verify email)', function (done) { - var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); - var expectedUserId = 'a1b2c3d4e5f6'; - var expectedUserPhone = '111111111'; - var expectedUserCountry = 'US'; - var expectedPublicRequest = {}; - expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; - expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; - expectedPublicRequest.phone = expectedUserPhone; - expectedPublicRequest.country = expectedUserCountry; - - var expectedPrivateResponse = _.clone(expectedPublicRequest); - delete(expectedPrivateResponse[config.passThroughEndpoint.password]); - - nock('http://' + config.private_host + ':' + config.private_port) - .post(config.passThroughEndpoint.path, expectedPrivateResponse) - .times(2) - .reply(201, {id: expectedUserId}); - - nock(notificationsServiceURL) - .post('/notification/email') - .reply(204); - - var redisKey = config.redisKeys.user_phone_verify.key; - redisKey = redisKey.replace('{userId}', expectedUsername).replace('{phone}', '+1' + expectedUserPhone); - - var pin = 'xxxx'; - redisMng.insertKeyValue(redisKey + '.pin', pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { - assert.equal(err, null); - redisMng.insertKeyValue(redisKey + '.attempts', config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { + var options = { + url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'x-otp-pin': pin + }, + method: 'POST', + body: JSON.stringify(expectedPublicRequest) + }; + options.headers[config.version.header] = versionHeader; + + nock(notificationsServiceURL) + .post('/notification/email') + .reply(204); + + request(options, function (err, res, body) { assert.equal(err, null); + assert.equal(res.statusCode, 201, body); + body = JSON.parse(body); - var options = { - url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, - headers: { - 'Content-Type': 'application/json; charset=utf-8', - 'x-otp-pin': pin - }, - method: 'POST', - body: JSON.stringify(expectedPublicRequest) - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { + assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); + assert.notEqual(body.accessToken, undefined); + ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - body = JSON.parse(body); - assert.deepEqual(body, {des: expectedUsername}, body); - - //Check the redis transactionId for the user - var redisKey = config.redisKeys.direct_login_transaction.key; - redisKey = redisKey.replace('{username}', expectedUsername); + assert.equal(accessTokenInfo.userId, expectedUserId); - redisMng.getKeyValue(redisKey, function (err, transactionId) { + assert.notEqual(body.refreshToken, undefined); + ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { assert.equal(err, null); - assert.notEqual(transactionId, null); - assert.equal(transactionId.length, 24); + assert.equal(refreshTokenInfo.userId, expectedUserId); done(); }); }); - }); }); + }); + }); + + it('400 not security token', function (done) { + var expectedPublicRequest = {}; + expectedPublicRequest[config.passThroughEndpoint.username] = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); + + var options = { + url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify(expectedPublicRequest) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 400); + body = JSON.parse(body); + assert.equal(body.err, 'invalid_security_token'); + assert.equal(body.des, 'you must provide a password or a salesforce token to create the user'); + done(); + }); + }); + + it.skip('201 Created (Verify email)', function (done) { + var expectedUsername = 'valid' + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''); + var expectedUserId = 'a1b2c3d4e5f6'; + var expectedUserPhone = '111111111'; + var expectedUserCountry = 'US'; + var expectedPublicRequest = {}; + expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; + expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; + expectedPublicRequest.phone = expectedUserPhone; + expectedPublicRequest.country = expectedUserCountry; + + var expectedPrivateResponse = _.clone(expectedPublicRequest); + delete(expectedPrivateResponse[config.passThroughEndpoint.password]); + + nock('http://' + config.private_host + ':' + config.private_port) + .post(config.passThroughEndpoint.path, expectedPrivateResponse) + .times(2) + .reply(201, {id: expectedUserId}); + + nock(notificationsServiceURL) + .post('/notification/email') + .reply(204); + + var redisKey = config.redisKeys.user_phone_verify.key; + redisKey = redisKey.replace('{userId}', expectedUsername).replace('{phone}', '+1' + expectedUserPhone); + + var pin = 'xxxx'; + + redisMng.insertKeyValue(redisKey + '.pin', pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { + assert.equal(err, null); + redisMng.insertKeyValue(redisKey + '.attempts', config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { + assert.equal(err, null); + var options = { + url: 'http://' + config.private_host + ':' + config.public_port + config.passThroughEndpoint.path, + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'x-otp-pin': pin + }, + method: 'POST', + body: JSON.stringify(expectedPublicRequest) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + body = JSON.parse(body); + assert.deepEqual(body, {des: expectedUsername}, body); + + //Check the redis transactionId for the user + var redisKey = config.redisKeys.direct_login_transaction.key; + redisKey = redisKey.replace('{username}', expectedUsername); + + redisMng.getKeyValue(redisKey, function (err, transactionId) { + assert.equal(err, null); + assert.notEqual(transactionId, null); + assert.equal(transactionId.length, 24); + done(); + }); + }); + + }); }); - } -}; + + }); + +}); diff --git a/tests-unit/proxy/protectedCallsStandard-platformSF.js b/tests-unit/proxy/protectedCallsStandard-platformSF.js index 8c337af..0c6045f 100644 --- a/tests-unit/proxy/protectedCallsStandard-platformSF.js +++ b/tests-unit/proxy/protectedCallsStandard-platformSF.js @@ -7,6 +7,8 @@ var nock = require('nock'); var dao = require('../../src/managers/dao.js'); var config = require('../../config.json'); +var accessTokenSettings = require('../token_settings').accessTokenSettings; + var expectedBody = {field1: 'value1', field2: 'value2'}; var SF_DATA = { userId: 'f6e5d4c3b2a1', @@ -44,89 +46,95 @@ var OPTIONS_STANDARD_CALL = { var versionHeader = 'test/1'; -module.exports = { - itWithSalesforce: function withSalesForce(accessTokenSettings) { - it('200 with salesforce', function (done) { - dao.addUser()(USER, function (err, createdUser) { - assert.equal(err, null); +describe('Protected calls standard with SF', () => { - ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { - nockProtectedStandartCall(createdUser._id, SF_DATA, expectedBody); + beforeEach(function (done) { + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + done(); + }); + }); - var options = _.clone(OPTIONS_STANDARD_CALL); - options.headers.Authorization = 'bearer ' + loginToken; - options.headers[config.version.header] = versionHeader; + it('200 with salesforce', function (done) { + dao.addUser()(USER, function (err, createdUser) { + assert.equal(err, null); - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - assert.notEqual(body, undefined); - done(); - }); + ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { + nockProtectedStandartCall(createdUser._id, SF_DATA, expectedBody); + + var options = _.clone(OPTIONS_STANDARD_CALL); + options.headers.Authorization = 'bearer ' + loginToken; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + assert.notEqual(body, undefined); + done(); }); }); }); - }, - itRenewSFToken: function renewSFToken(accessTokenSettings) { - it('200 with salesforce when renewing access token', function (done) { - var userWithSoonExpiry = _.clone(USER); - userWithSoonExpiry.platforms[0].expiry = new Date().getTime() + 0.9 * config.salesforce.renewWhenLessThan * 60 * 1000; // expire in less than a minute + }); - dao.addUser()(userWithSoonExpiry, function (err, createdUser) { - assert.equal(err, null); + it('200 with salesforce when renewing access token', function (done) { + var userWithSoonExpiry = _.clone(USER); + userWithSoonExpiry.platforms[0].expiry = new Date().getTime() + 0.9 * config.salesforce.renewWhenLessThan * 60 * 1000; // expire in less than a minute + + dao.addUser()(userWithSoonExpiry, function (err, createdUser) { + assert.equal(err, null); - ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { + ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { + assert.equal(err, null); + var oldAccessToken = USER.platforms[0].accessToken.params.access_token; + + var queryParams = 'grant_type=refresh_token&' + + 'client_id=' + config.salesforce.clientId + '&' + + 'client_secret=' + config.salesforce.clientSecret + '&' + + 'refresh_token=' + USER.platforms[0].refreshToken; + + var sfRenewTokenReturnedBody = { + "id": "https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P", + "issued_at": "1278448384422", + "instance_url": "https://na1.salesforce.com", + "signature": "SSSbLO/gBhmmyNUvN18ODBDFYHzakxOMgqYtu+hDPsc=", + "access_token": "00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0RNBaT1cyWk7TrqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4" + }; + nockSFRenewToken(queryParams, sfRenewTokenReturnedBody); + + var newSFData = _.clone(SF_DATA); + newSFData.accessToken = sfRenewTokenReturnedBody.access_token; + nockProtectedStandartCall(createdUser._id, newSFData, expectedBody); + + var options = _.clone(OPTIONS_STANDARD_CALL); + options.headers.Authorization = 'bearer ' + loginToken; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { assert.equal(err, null); - var oldAccessToken = USER.platforms[0].accessToken.params.access_token; - - var queryParams = 'grant_type=refresh_token&' + - 'client_id=' + config.salesforce.clientId + '&' + - 'client_secret=' + config.salesforce.clientSecret + '&' + - 'refresh_token=' + USER.platforms[0].refreshToken; - - var sfRenewTokenReturnedBody = { - "id": "https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P", - "issued_at": "1278448384422", - "instance_url": "https://na1.salesforce.com", - "signature": "SSSbLO/gBhmmyNUvN18ODBDFYHzakxOMgqYtu+hDPsc=", - "access_token": "00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0RNBaT1cyWk7TrqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4" - }; - nockSFRenewToken(queryParams, sfRenewTokenReturnedBody); - - var newSFData = _.clone(SF_DATA); - newSFData.accessToken = sfRenewTokenReturnedBody.access_token; - nockProtectedStandartCall(createdUser._id, newSFData, expectedBody); - - var options = _.clone(OPTIONS_STANDARD_CALL); - options.headers.Authorization = 'bearer ' + loginToken; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - assert.notEqual(body, undefined); + assert.equal(res.statusCode, 200, body); + assert.notEqual(body, undefined); - dao.getFromId(createdUser._id, function (err, foundUser) { - assert.equal(err, null); + dao.getFromId(createdUser._id, function (err, foundUser) { + assert.equal(err, null); - var updatedExpiry = foundUser.platforms[0].expiry; - var roundedUpdatedExpiry = (updatedExpiry / 10000).toFixed(); + var updatedExpiry = foundUser.platforms[0].expiry; + var roundedUpdatedExpiry = (updatedExpiry / 10000).toFixed(); - var expectedExpiry = (new Date().getTime()) + config.salesforce.expiration * 60 * 1000; - var roundedExpectedExpiry = (expectedExpiry / 10000).toFixed(); + var expectedExpiry = (new Date().getTime()) + config.salesforce.expiration * 60 * 1000; + var roundedExpectedExpiry = (expectedExpiry / 10000).toFixed(); - assert.equal(roundedUpdatedExpiry, roundedExpectedExpiry); - assert.notEqual(oldAccessToken, foundUser.platforms[0].accessToken.params.access_token); - done(); - }); + assert.equal(roundedUpdatedExpiry, roundedExpectedExpiry); + assert.notEqual(oldAccessToken, foundUser.platforms[0].accessToken.params.access_token); + done(); }); }); }); }); - } -}; + }); + +}); -function nockProtectedStandartCall(id, expectedSfData, expectedBody) { +function nockProtectedStandartCall (id, expectedSfData, expectedBody) { nock('http://' + config.private_host + ':' + config.private_port, { reqheaders: { 'x-user-id': id, @@ -138,7 +146,7 @@ function nockProtectedStandartCall(id, expectedSfData, expectedBody) { .reply(200, {field3: 'value3'}); } -function nockSFRenewToken(queryParams, bodyToReturn) { +function nockSFRenewToken (queryParams, bodyToReturn) { nock('https://login.salesforce.com', {}) .post('/services/oauth2/token' + '?' + queryParams) .reply(200, bodyToReturn); diff --git a/tests-unit/proxy/protectedCallsStandard.js b/tests-unit/proxy/protectedCallsStandard.js index 072ea49..80be18b 100644 --- a/tests-unit/proxy/protectedCallsStandard.js +++ b/tests-unit/proxy/protectedCallsStandard.js @@ -7,116 +7,122 @@ var dao = require('../../src/managers/dao.js'); var config = require('../../config.json'); var versionHeader = 'test/1'; +var accessTokenSettings = require('../token_settings').accessTokenSettings; -module.exports = { - itUnauthorized: function Unauthorized() { - it('401 Unauthorized', function (done) { - var expectedBody = {field1: 'value1', field2: 'value2'}; - - var options = { - url: 'http://localhost:' + config.public_port + '/api/standard', - headers: { - 'Content-Type': 'application/json; charset=utf-8' - }, - method: 'POST', - body: JSON.stringify(expectedBody) - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 401); - assert.notEqual(body, undefined); - done(); - }); +describe('Protected calls standard', () => { + + beforeEach(function (done) { + dao.deleteAllUsers(function (err) { + assert.equal(err, null); + done(); + }); + }); + + it('401 Unauthorized', function (done) { + var expectedBody = {field1: 'value1', field2: 'value2'}; + + var options = { + url: 'http://localhost:' + config.public_port + '/api/standard', + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify(expectedBody) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 401); + assert.notEqual(body, undefined); + done(); }); - }, - itWithoutPlatforms: function withoutPlatforms(accessTokenSettings) { - it('200 without platforms', function (done) { - var user = { - id: 'a1b2c3d4e5f6', - username: "valid" + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), - password: "12345678" - }; - - dao.addUser()(user, function (err, createdUser) { - assert.equal(err, null); - - ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { - var expectedBody = {field1: 'value1', field2: 'value2'}; - - nock('http://' + config.private_host + ':' + config.private_port, { - reqheaders: { - 'x-user-id': createdUser._id, - 'content-type': 'application/json; charset=utf-8' - } - }) - .post('/api/standard', expectedBody) - .reply(200, {field3: 'value3'}); - - var options = { - url: 'http://localhost:' + config.public_port + '/api/standard', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - 'Authorization': 'bearer ' + loginToken - }, - method: 'POST', - body: JSON.stringify(expectedBody) - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - assert.notEqual(body, undefined); - done(); - }); + }); + + it('200 without platforms', function (done) { + var user = { + id: 'a1b2c3d4e5f6', + username: "valid" + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), + password: "12345678" + }; + + dao.addUser()(user, function (err, createdUser) { + assert.equal(err, null); + + ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { + var expectedBody = {field1: 'value1', field2: 'value2'}; + + nock('http://' + config.private_host + ':' + config.private_port, { + reqheaders: { + 'x-user-id': createdUser._id, + 'content-type': 'application/json; charset=utf-8' + } + }) + .post('/api/standard', expectedBody) + .reply(200, {field3: 'value3'}); + + var options = { + url: 'http://localhost:' + config.public_port + '/api/standard', + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'Authorization': 'bearer ' + loginToken + }, + method: 'POST', + body: JSON.stringify(expectedBody) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + assert.notEqual(body, undefined); + done(); }); }); }); - }, - itBodyResponseIsNotAJson: function bodyResponseIsNotAJson(accessTokenSettings) { - it('body response is not a json', function (done) { - var user = { - id: 'a1b2c3d4e5f6', - username: "valid" + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), - password: "12345678" - }; - - dao.addUser()(user, function (err, createdUser) { - assert.equal(err, null); - - ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { - var expectedBody = {field1: 'value1', field2: 'value2'}; - - nock('http://' + config.private_host + ':' + config.private_port, { - reqheaders: { - 'x-user-id': createdUser._id, - 'content-type': 'application/json; charset=utf-8' - } - }) - .post('/api/standard', expectedBody) - .reply(200, 'not a json'); - - var options = { - url: 'http://localhost:' + config.public_port + '/api/standard', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - 'Authorization': 'bearer ' + loginToken - }, - method: 'POST', - body: JSON.stringify(expectedBody) - }; - options.headers[config.version.header] = versionHeader; - - request(options, function (err, res, body) { - assert.equal(err, null); - assert.equal(res.statusCode, 200, body); - assert.notEqual(body, undefined); - done(); - }); + }); + + it('body response is not a json', function (done) { + var user = { + id: 'a1b2c3d4e5f6', + username: "valid" + (config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''), + password: "12345678" + }; + + dao.addUser()(user, function (err, createdUser) { + assert.equal(err, null); + + ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { + var expectedBody = {field1: 'value1', field2: 'value2'}; + + nock('http://' + config.private_host + ':' + config.private_port, { + reqheaders: { + 'x-user-id': createdUser._id, + 'content-type': 'application/json; charset=utf-8' + } + }) + .post('/api/standard', expectedBody) + .reply(200, 'not a json'); + + var options = { + url: 'http://localhost:' + config.public_port + '/api/standard', + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'Authorization': 'bearer ' + loginToken + }, + method: 'POST', + body: JSON.stringify(expectedBody) + }; + options.headers[config.version.header] = versionHeader; + + request(options, function (err, res, body) { + assert.equal(err, null); + assert.equal(res.statusCode, 200, body); + assert.notEqual(body, undefined); + done(); }); }); }); - } -}; + }); + +}); diff --git a/tests-unit/public_routes/auth/loginRefreshToken.js b/tests-unit/public_routes/auth/loginRefreshToken.js index 78d0b7b..4c24cb0 100644 --- a/tests-unit/public_routes/auth/loginRefreshToken.js +++ b/tests-unit/public_routes/auth/loginRefreshToken.js @@ -47,7 +47,7 @@ describe('public routes', function () { should.not.exist(body); }, - header: function(headerName, headerValue){ + header: function (headerName, headerValue) { should.exist(headerName); headerName.toLowerCase().should.equal('location'); should.exist(headerValue); diff --git a/tests-unit/redirect.js b/tests-unit/redirect.js index 38c593b..bda3ae7 100644 --- a/tests-unit/redirect.js +++ b/tests-unit/redirect.js @@ -3,7 +3,6 @@ var nock = require('nock'); var request = require('request'); var ciphertoken = require('ciphertoken'); var dao = require('../src/managers/dao.js'); -var cipherlayer = require('../src/cipherlayer'); var config = require('../config.json'); var accessTokenSettings = { @@ -16,19 +15,7 @@ var versionHeader = 'test/1'; describe('redirect', function () { - beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, function (err) { - assert.equal(err, null); - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - done(); - }); - }); - }); - - afterEach(function (done) { - cipherlayer.stop(done); - }); + beforeEach(dao.deleteAllUsers); it('OK', function (done) { diff --git a/tests-unit/redis.js b/tests-unit/redis.js index 67cf4c5..a54b556 100644 --- a/tests-unit/redis.js +++ b/tests-unit/redis.js @@ -5,13 +5,11 @@ var assert = require('assert'); var async = require('async'); describe('redis', function () { - beforeEach(function (done) { - redisMng.connect(done); - }); - afterEach(function (done) { - redisMng.disconnect(done); - }); + this.timeout(4000); + + beforeEach(redisMng.connect); + afterEach(redisMng.disconnect); var baseKey = 'key'; var baseValue = 'value'; @@ -91,7 +89,6 @@ describe('redis', function () { }); it('expire', function (done) { - this.timeout(3000); async.series([ //createKey function (done) { @@ -102,21 +99,18 @@ describe('redis', function () { }, // checkExpire function (done) { - setTimeout( - function () { - redisMng.getKeyValue(baseKey, function (err, value) { - assert.equal(err, null); - assert.equal(value, null); - done(); - }); - }, 1500 - ); + setTimeout(function () { + redisMng.getKeyValue(baseKey, function (err, value) { + assert.equal(err, null); + assert.equal(value, null); + done(); + }); + }, 1500); } ], done); }); it('update', function (done) { - this.timeout(4000); var val = 'new value'; async.series([ // createKey @@ -128,36 +122,31 @@ describe('redis', function () { }, // updateKey function (done) { - setTimeout( - function () { - redisMng.updateKeyValue(baseKey, val, function (err) { + setTimeout(function () { + redisMng.updateKeyValue(baseKey, val, function (err) { + assert.equal(err, null); + redisMng.getKeyValue(baseKey, function (err, value) { assert.equal(err, null); - redisMng.getKeyValue(baseKey, function (err, value) { - assert.equal(err, null); - assert.equal(value, val); - done(); - }); + assert.equal(value, val); + done(); }); - }, 1000 - ); + }); + }, 1000); }, // checkExpire function (done) { - setTimeout( - function () { - redisMng.getKeyValue(baseKey, function (err, value) { - assert.equal(err, null); - assert.equal(value, null); - done(); - }); - }, 1500 - ); + setTimeout(function () { + redisMng.getKeyValue(baseKey, function (err, value) { + assert.equal(err, null); + assert.equal(value, null); + done(); + }); + }, 1500); } ], done); }); it('update - disconnected', function (done) { - this.timeout(4000); var val = 'new value'; async.series([ // createKey diff --git a/tests-unit/routesRealms.js b/tests-unit/routesRealms.js index a0a2f18..064c5ea 100644 --- a/tests-unit/routesRealms.js +++ b/tests-unit/routesRealms.js @@ -4,7 +4,6 @@ var async = require('async'); var _ = require('lodash'); var config = require('../config.json'); -var cipherlayer = require('../src/cipherlayer.js'); var daoMng = require('../src/managers/dao.js'); describe('realms', function () { @@ -43,32 +42,20 @@ describe('realms', function () { ]; beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, function (err) { - assert.equal(err, null); - async.parallel([ - function (finish) { - daoMng.resetRealmsVariables(); - daoMng.deleteAllRealms(finish); - }, - function (finish) { - async.eachSeries(_.cloneDeep(baseRealms), function (realm, next) { - daoMng.addRealm(realm, function () { - assert.equal(err, null); - next(); - }); - }, function () { - finish(); - }); - } - ], done); - }); + async.parallel([ + function (finish) { + daoMng.resetRealmsVariables(); + daoMng.deleteAllRealms(finish); + }, + function (finish) { + async.eachSeries(_.cloneDeep(baseRealms), function (realm, next) { + daoMng.addRealm(realm, next); + }, finish); + } + ], done); }); - afterEach(function (done) { - daoMng.deleteAllRealms(function () { - cipherlayer.stop(done); - }); - }); + afterEach(daoMng.deleteAllRealms); it('Get all realms', function (done) { if (!config.internal_port) { diff --git a/tests-unit/routesUser.js b/tests-unit/routesUser.js index 53e6dfd..88abc60 100644 --- a/tests-unit/routesUser.js +++ b/tests-unit/routesUser.js @@ -1,11 +1,9 @@ var assert = require('assert'); -var _ = require('lodash'); var request = require('request'); var ciphertoken = require('ciphertoken'); var nock = require('nock'); var fs = require('fs'); var _ = require('lodash'); -var cipherlayer = require('../src/cipherlayer.js'); var config = JSON.parse(fs.readFileSync('config.json', 'utf8')); var dao = require('../src/managers/dao.js'); @@ -35,7 +33,7 @@ describe('user', function () { password: 'validpassword' }; - function validatePwd(clear, crypted, cbk) { + function validatePwd (clear, crypted, cbk) { var cryptoMng = crypto(config.password); cryptoMng.verify(clear, crypted, function (err) { assert.equal(err, null); @@ -44,32 +42,25 @@ describe('user', function () { } beforeEach(function (done) { - cipherlayer.start(config.public_port, config.internal_port, function (err) { + dao.deleteAllUsers(function (err) { assert.equal(err, null); - dao.deleteAllUsers(function (err) { - assert.equal(err, null); - var userToCreate = _.clone(baseUser); + var userToCreate = _.clone(baseUser); - cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { - userToCreate.password = encryptedPwd; - dao.addUser()(userToCreate, function (err, createdUser) { - assert.equal(err, null); - assert.notEqual(createdUser, undefined); - createdUserId = createdUser._id; - ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { - AUTHORIZATION = config.authHeaderKey + loginToken; - done(); - }); + cryptoMng.encrypt(userToCreate.password, function (encryptedPwd) { + userToCreate.password = encryptedPwd; + dao.addUser()(userToCreate, function (err, createdUser) { + assert.equal(err, null); + assert.notEqual(createdUser, undefined); + createdUserId = createdUser._id; + ciphertoken.createToken(accessTokenSettings, createdUser._id, null, {}, function (err, loginToken) { + AUTHORIZATION = config.authHeaderKey + loginToken; + return done(); }); }); }); }); }); - afterEach(function (done) { - cipherlayer.stop(done); - }); - describe('Forgot Password', function () { it('Send new Password', function (done) { diff --git a/tests-unit/server.js b/tests-unit/server.js index 94c7b77..4d268a4 100644 --- a/tests-unit/server.js +++ b/tests-unit/server.js @@ -3,7 +3,7 @@ var assert = require('assert'); var net = require('net'); var config = require('../config.json'); -describe('server control ', function () { +describe.skip('server control ', function () { it('start', function (done) { cipherlayer.start(config.public_port, config.internal_port, function (err) { assert.equal(err, null); diff --git a/tests-unit/start_stop_cipherlayer.js b/tests-unit/start_stop_cipherlayer.js new file mode 100644 index 0000000..8dfec5d --- /dev/null +++ b/tests-unit/start_stop_cipherlayer.js @@ -0,0 +1,12 @@ +'use strict'; + +var cipherlayer = require('../src/cipherlayer.js'); +var config = require('../config.json'); + +beforeEach(function (done) { + cipherlayer.start(config.public_port, config.internal_port, done); +}); + +afterEach(function (done) { + cipherlayer.stop(done); +}); diff --git a/tests-unit/token_settings.js b/tests-unit/token_settings.js new file mode 100644 index 0000000..90fd4a0 --- /dev/null +++ b/tests-unit/token_settings.js @@ -0,0 +1,16 @@ +'use strict'; + +var config = require('../config.json'); + +module.exports = { + accessTokenSettings: { + cipherKey: config.accessToken.cipherKey, + firmKey: config.accessToken.signKey, + tokenExpirationMinutes: config.accessToken.expiration + }, + refreshTokenSettings: { + cipherKey: config.refreshToken.cipherKey, + firmKey: config.refreshToken.signKey, + tokenExpirationMinutes: config.refreshToken.expiration + } +}; diff --git a/tests-unit/verifyPhone.js b/tests-unit/verifyPhone.js index 8e32bab..3f4d2fd 100644 --- a/tests-unit/verifyPhone.js +++ b/tests-unit/verifyPhone.js @@ -6,7 +6,6 @@ var _ = require('lodash'); var config = require('../config.json'); var dao = require('../src/managers/dao'); -var cipherlayer = require('../src/cipherlayer'); var redisMng = require('../src/managers/redis'); var HEADERS_WITHOUT_AUTHORIZATION_BASIC = { @@ -15,7 +14,9 @@ var HEADERS_WITHOUT_AUTHORIZATION_BASIC = { var versionHeader = 'test/1'; -describe('/api/profile (verify phone)', function () { +describe.skip('/api/profile (verify phone)', function () { + + this.timeout(10000); var notifServiceURL = config.externalServices.notifications.base; @@ -28,9 +29,6 @@ describe('/api/profile (verify phone)', function () { beforeEach(function (done) { async.series([ - function (done) { - cipherlayer.start(config.public_port, config.internal_port, done); - }, function (done) { redisMng.deleteAllKeys(done); }, @@ -40,15 +38,7 @@ describe('/api/profile (verify phone)', function () { ], done); }); - afterEach(function (done) { - async.series([ - function (done) { - cipherlayer.stop(done); - } - ], done); - }); - - it.skip('POST empty phone', function (done) { + it('POST empty phone', function (done) { var user = _.clone(baseUser); user.phone = null; @@ -73,7 +63,7 @@ describe('/api/profile (verify phone)', function () { }); }); - it.skip('POST empty country', function (done) { + it('POST empty country', function (done) { var user = _.clone(baseUser); user.country = ''; @@ -98,7 +88,7 @@ describe('/api/profile (verify phone)', function () { }); }); - it.skip('POST phone not verified', function (done) { + it('POST phone not verified', function (done) { var user = _.clone(baseUser); var options = { @@ -122,7 +112,7 @@ describe('/api/profile (verify phone)', function () { }); }); - it.skip('POST incorrect PIN sent (1 attempt)', function (done) { + it('POST incorrect PIN sent (1 attempt)', function (done) { var user = _.clone(baseUser); var options = { @@ -156,8 +146,7 @@ describe('/api/profile (verify phone)', function () { }); }); - it.skip('POST correct PIN sent', function (done) { - this.timeout(10000); + it('POST correct PIN sent', function (done) { var user = _.clone(baseUser); @@ -212,7 +201,7 @@ describe('/api/profile (verify phone)', function () { }); }); - it.skip('POST incorrect PIN sent (3 attempts)', function (done) { + it('POST incorrect PIN sent (3 attempts)', function (done) { var user = _.clone(baseUser); var options = { @@ -309,8 +298,7 @@ describe('/api/profile (verify phone)', function () { }); }); - it.skip('POST user already exists', function (done) { - this.timeout(10000); + it('POST user already exists', function (done) { var user = _.clone(baseUser); From 699b61bc5d0730e350ea35b6e448eef5a369a71b Mon Sep 17 00:00:00 2001 From: guumaster Date: Sat, 27 Feb 2016 15:31:04 +0100 Subject: [PATCH 2/7] updated dependencies. modified package.json and .editorconfig to match NPM format. --- .editorconfig | 5 ++ package.json | 150 ++++++++++++++++++++++---------------------- tests-unit/redis.js | 1 - 3 files changed, 80 insertions(+), 76 deletions(-) diff --git a/.editorconfig b/.editorconfig index 472d26d..67499cd 100644 --- a/.editorconfig +++ b/.editorconfig @@ -12,6 +12,11 @@ charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true +# NPM rewrites package.json after every install with this settings +[package.json] +indent_style = space +indent_size = 2 + [*.md] trim_trailing_whitespace = false diff --git a/package.json b/package.json index 66e7513..855b0b3 100644 --- a/package.json +++ b/package.json @@ -1,77 +1,77 @@ { - "name": "cipherlayer", - "version": "0.0.1", - "description": "cipherlayer", - "main": "src/cipherlayer.js", - "scripts": { - "test": "npm run lint && npm run test-unit && npm run test-acceptance", - "test-unit": "mocha tests-unit --recursive", - "test-acceptance": "cucumber.js tests-acceptance -f pretty --tags ~@ignore", - "test-acceptance-only": "cucumber.js tests-acceptance -f pretty --tags @only", - "lint": "jshint ./src ./tests-unit ./tests-acceptance main.js", - "coverage-unit": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/unit _mocha -- tests-unit --recursive --reporter mocha-lcov-reporter", - "coverage-acceptance": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/acceptance cucumber.js -- tests-acceptance --tags ~@ignore --format json", - "coverage-merge": "istanbul-combine coverage/**/coverage.json", - "coverage": "npm run coverage-unit && npm run coverage-acceptance && npm run coverage-merge", - "coveralls": "istanbul-coveralls", - "codeclimate": "codeclimate-test-reporter < ./coverage/lcov.info" - }, - "dependencies": { - "async": "^0.9.0", - "aws-sdk": "^2.1.0", - "bunyan": "^1.4.0", - "ciphertoken": "^0.9.5", - "countries-info": "^1.0.6", - "escape-regexp": "0.0.1", - "http-proxy": "^1.8.1", - "jsonschema": "^1.0.0", - "lodash": "^4.3.0", - "mongodb": "^1.4.40", - "passport": "^0.2.1", - "passport-forcedotcom": "^0.1.1", - "passport-google-oauth2": "^0.1.6", - "passport-linkedin-oauth2": "^1.2.1", - "randexp": "^0.4.2", - "redis": "^0.12.1", - "request": "^2.47.0", - "restify": "^2.8.5", - "version-control": "^1.2.4" - }, - "devDependencies": { - "assert": "^1.1.2", - "chai": "^3.5.0", - "codeclimate-test-reporter": "^0.3.1", - "coveralls": "^2.11.4", - "cucumber": "^0.5.2", - "istanbul": "^0.3.22", - "istanbul-combine": "^0.3.0", - "istanbul-coveralls": "^1.0.3", - "jshint": "^2.8.0", - "mocha": "^2.0.1", - "mocha-lcov-reporter": "^1.2.0", - "mockery": "^1.4.0", - "nock": "^7.3.0", - "pre-commit": "^1.0.7", - "sinon": "^1.12.2", - "which": "^1.0.8" - }, - "repository": { - "type": "git", - "url": "https://github.com/thegameofcode/cipherlayer.git" - }, - "author": "luismesas", - "license": "ISC", - "bugs": { - "url": "https://github.com/thegameofcode/cipherlayer/issues" - }, - "homepage": "https://github.com/thegameofcode/cipherlayer", - "pre-commit": [ - "lint" - ], - "jshintConfig": { - "esnext": true, - "node": true, - "unused": true, - "mocha": true - } + "name": "cipherlayer", + "version": "0.0.1", + "description": "cipherlayer", + "main": "src/cipherlayer.js", + "scripts": { + "test": "npm run lint && npm run test-unit && npm run test-acceptance", + "test-unit": "mocha tests-unit --recursive", + "test-acceptance": "cucumber.js tests-acceptance -f pretty --tags ~@ignore", + "test-acceptance-only": "cucumber.js tests-acceptance -f pretty --tags @only", + "lint": "jshint ./src ./tests-unit ./tests-acceptance main.js", + "coverage-unit": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/unit _mocha -- tests-unit --recursive --reporter mocha-lcov-reporter", + "coverage-acceptance": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/acceptance cucumber.js -- tests-acceptance --tags ~@ignore --format json", + "coverage-merge": "istanbul-combine coverage/**/coverage.json", + "coverage": "npm run coverage-unit && npm run coverage-acceptance && npm run coverage-merge", + "coveralls": "istanbul-coveralls", + "codeclimate": "codeclimate-test-reporter < ./coverage/lcov.info" + }, + "dependencies": { + "async": "^1.5.2", + "aws-sdk": "^2.1.0", + "bunyan": "^1.4.0", + "ciphertoken": "^0.9.5", + "countries-info": "^1.0.6", + "escape-regexp": "0.0.1", + "http-proxy": "^1.8.1", + "jsonschema": "^1.0.0", + "lodash": "^4.3.0", + "mongodb": "^1.4.40", + "passport": "^0.3.2", + "passport-forcedotcom": "^0.1.1", + "passport-google-oauth2": "^0.1.6", + "passport-linkedin-oauth2": "^1.2.1", + "randexp": "^0.4.2", + "redis": "^2.4.2", + "request": "^2.47.0", + "restify": "^4.0.4", + "version-control": "^1.2.4" + }, + "devDependencies": { + "assert": "^1.1.2", + "chai": "^3.5.0", + "codeclimate-test-reporter": "^0.3.1", + "coveralls": "^2.11.4", + "cucumber": "^0.5.2", + "istanbul": "^0.4.2", + "istanbul-combine": "^0.3.0", + "istanbul-coveralls": "^1.0.3", + "jshint": "^2.8.0", + "mocha": "^2.0.1", + "mocha-lcov-reporter": "^1.2.0", + "mockery": "^1.4.0", + "nock": "^7.2.2", + "pre-commit": "^1.0.7", + "sinon": "^1.12.2", + "which": "^1.0.8" + }, + "repository": { + "type": "git", + "url": "https://github.com/thegameofcode/cipherlayer.git" + }, + "author": "luismesas", + "license": "ISC", + "bugs": { + "url": "https://github.com/thegameofcode/cipherlayer/issues" + }, + "homepage": "https://github.com/thegameofcode/cipherlayer", + "pre-commit": [ + "lint" + ], + "jshintConfig": { + "esnext": true, + "node": true, + "unused": true, + "mocha": true + } } diff --git a/tests-unit/redis.js b/tests-unit/redis.js index a54b556..af80f86 100644 --- a/tests-unit/redis.js +++ b/tests-unit/redis.js @@ -9,7 +9,6 @@ describe('redis', function () { this.timeout(4000); beforeEach(redisMng.connect); - afterEach(redisMng.disconnect); var baseKey = 'key'; var baseValue = 'value'; From f98d2cea04a12f0f3d45e4ff98af0a099cc67c5b Mon Sep 17 00:00:00 2001 From: guumaster Date: Sat, 27 Feb 2016 16:14:56 +0100 Subject: [PATCH 3/7] small changes to support cucumber-js@^0.9.5 --- package.json | 2 +- tests-acceptance/post_profile.feature | 2 +- tests-acceptance/proxy.feature | 2 +- tests-acceptance/restrictedArea.feature | 7 +++---- .../step_definitions/protected_service_definiton.js | 6 +++--- tests-acceptance/support/hooks.js | 6 ++---- tests-acceptance/support/service.js | 4 ++-- tests-acceptance/support/serviceValidCors.js | 7 ++++--- 8 files changed, 17 insertions(+), 19 deletions(-) diff --git a/package.json b/package.json index 855b0b3..4383ddb 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "chai": "^3.5.0", "codeclimate-test-reporter": "^0.3.1", "coveralls": "^2.11.4", - "cucumber": "^0.5.2", + "cucumber": "^0.9.5", "istanbul": "^0.4.2", "istanbul-combine": "^0.3.0", "istanbul-coveralls": "^1.0.3", diff --git a/tests-acceptance/post_profile.feature b/tests-acceptance/post_profile.feature index a39cdc0..8f8f86d 100644 --- a/tests-acceptance/post_profile.feature +++ b/tests-acceptance/post_profile.feature @@ -4,7 +4,7 @@ Feature: client application POST a profile to create @service Scenario Outline: Client post data for a new profile - Given a protected service replies to a request with to with status and a body + Given a protected service replies to a request with to with status and a responseBody And config has no param emailverification When the client makes a pass through with the following in the body Then the response status code is 403 diff --git a/tests-acceptance/proxy.feature b/tests-acceptance/proxy.feature index 7673f60..fdd4076 100644 --- a/tests-acceptance/proxy.feature +++ b/tests-acceptance/proxy.feature @@ -3,7 +3,7 @@ Feature: reverse proxy protects an applicacion behind cipherlayer @service Scenario Outline: A protected service needs an accessToken auth to be called Given a user with role user and a valid access token - And a protected service replies to a request with to with status and a body + And a protected service replies to a request with to with status and a responseBody When the application makes a with to a protected Then the response status code is And the response body must be diff --git a/tests-acceptance/restrictedArea.feature b/tests-acceptance/restrictedArea.feature index 5827418..e8e114f 100644 --- a/tests-acceptance/restrictedArea.feature +++ b/tests-acceptance/restrictedArea.feature @@ -9,11 +9,10 @@ Feature: client application logs in with admin role And the response body contains json attribute "refreshToken" And the response body contains json attribute "expiresIn" - @service Scenario Outline: A protected admin service needs an accessToken with admin role attribute auth to be called Given a user with role admin and a valid access token - And a protected service replies to a request with to with status and a body + And a protected service replies to a request with to with status and a responseBody When the application makes a with to a protected Then the response status code is And the response body must be @@ -25,7 +24,7 @@ Feature: client application logs in with admin role @service Scenario Outline: A protected admin service needs an accessToken with admin role attribute auth to be called Given a user with role admin and a valid access token - And a protected service replies to a request with to with status and a body "" + And a protected service replies to a request with to with status and a responseBody "" When the application makes a with to a protected Then the response status code is Examples: @@ -36,7 +35,7 @@ Feature: client application logs in with admin role @service Scenario Outline: Client with no admin role request restricted endpoints Given a user with role user and a valid access token - And a protected service replies to a request with to with status and a body + And a protected service replies to a request with to with status and a responseBody When the application makes a with to a protected Then the response status code is And the response body must be diff --git a/tests-acceptance/step_definitions/protected_service_definiton.js b/tests-acceptance/step_definitions/protected_service_definiton.js index 73828b2..874a28d 100644 --- a/tests-acceptance/step_definitions/protected_service_definiton.js +++ b/tests-acceptance/step_definitions/protected_service_definiton.js @@ -3,7 +3,7 @@ var nock = require('nock'); var config = require('../../config.json'); module.exports = function(){ - this.Given(/^a protected service replies to a GET request with (.*) to (.*) with status (.*) and a body (.*)$/, function (REQUEST_PAYLOAD, PATH, STATUS, RESPONSE_PAYLOAD, callback){ + this.Given(/^a protected service replies to a GET request with (.*) to (.*) with status (.*) and a responseBody (.*)$/, function (REQUEST_PAYLOAD, PATH, STATUS, RESPONSE_PAYLOAD, callback){ nock('http://localhost:'+config.private_port, { reqheaders: { 'Content-Type': 'application/json; charset=utf-8', @@ -27,7 +27,7 @@ module.exports = function(){ callback(); }); - this.Given(/^a protected service replies to a POST request with (.*) to (.*) with status (.*) and a body (.*)$/, function (REQUEST_PAYLOAD, PATH, STATUS, RESPONSE_PAYLOAD, callback){ + this.Given(/^a protected service replies to a POST request with (.*) to (.*) with status (.*) and a responseBody (.*)$/, function (REQUEST_PAYLOAD, PATH, STATUS, RESPONSE_PAYLOAD, callback){ nock('http://localhost:'+config.private_port) .post(PATH, JSON.parse(REQUEST_PAYLOAD)) .reply(Number(STATUS), JSON.parse(RESPONSE_PAYLOAD)); @@ -36,7 +36,7 @@ module.exports = function(){ }); - this.Given(/^a protected service replies to a PUT request with (.*) to (.*) with status (.*) and a body (.*)$/, function (REQUEST_PAYLOAD, PATH, STATUS, RESPONSE_PAYLOAD, callback){ + this.Given(/^a protected service replies to a PUT request with (.*) to (.*) with status (.*) and a responseBody (.*)$/, function (REQUEST_PAYLOAD, PATH, STATUS, RESPONSE_PAYLOAD, callback){ nock('http://localhost:'+config.private_port) .put(PATH, JSON.parse(REQUEST_PAYLOAD)) .reply(Number(STATUS), JSON.parse(RESPONSE_PAYLOAD)); diff --git a/tests-acceptance/support/hooks.js b/tests-acceptance/support/hooks.js index 8e92d93..3153483 100644 --- a/tests-acceptance/support/hooks.js +++ b/tests-acceptance/support/hooks.js @@ -4,14 +4,12 @@ var world = require('./world'); var config = require('../../config.json'); module.exports = function () { - this.Before(function (done) { + this.Before(function () { world.resetUser(); world.config = _.clone(config); - done(); }); - this.After(function (done) { + this.After(function () { config = world.config; - done(); }); }; diff --git a/tests-acceptance/support/service.js b/tests-acceptance/support/service.js index 1073a33..4f3ef73 100644 --- a/tests-acceptance/support/service.js +++ b/tests-acceptance/support/service.js @@ -8,7 +8,7 @@ var world = require('./world'); var config = require('../../config.json'); module.exports = function () { - this.Before("@service", function (done) { + this.Before("@service", function (scenario, done) { cipherlayer.start(config.public_port, config.internal_port, function (err) { assert.equal(err, null); var options = { @@ -30,7 +30,7 @@ module.exports = function () { }); }); - this.After("@service", function (done) { + this.After("@service", function (scenario, done) { cipherlayer.stop(done); }); }; diff --git a/tests-acceptance/support/serviceValidCors.js b/tests-acceptance/support/serviceValidCors.js index be15118..56c5c79 100644 --- a/tests-acceptance/support/serviceValidCors.js +++ b/tests-acceptance/support/serviceValidCors.js @@ -8,11 +8,12 @@ var world = require('./world'); var config = require('../../config.json'); module.exports = function () { - this.Before("@serviceValidCors", function (done) { - this.accessControlAllow = config.accessControlAllow = { + this.Before("@serviceValidCors", function (scenario, done) { + config.accessControlAllow = { headers: ['custom-header-1', 'custom-header-2'], origins: ['http://valid.origin.com'] }; + this.accessControlAllow = config.accessControlAllow; cipherlayer.start(config.public_port, config.internal_port, function (err) { assert.equal(err, null); @@ -35,7 +36,7 @@ module.exports = function () { }); }); - this.After("@serviceValidCors", function (done) { + this.After("@serviceValidCors", function (scenario, done) { cipherlayer.stop(done); }); }; From e0e31dea2650fb556a5623946d9e0594d4b4eff3 Mon Sep 17 00:00:00 2001 From: guumaster Date: Sat, 27 Feb 2016 16:55:11 +0100 Subject: [PATCH 4/7] removed unnecessary tests, start/stop is executed before/after each test. --- tests-unit/proxy.js | 41 ----------------------------------------- tests-unit/server.js | 36 ------------------------------------ 2 files changed, 77 deletions(-) delete mode 100644 tests-unit/proxy.js delete mode 100644 tests-unit/server.js diff --git a/tests-unit/proxy.js b/tests-unit/proxy.js deleted file mode 100644 index 8f13ca1..0000000 --- a/tests-unit/proxy.js +++ /dev/null @@ -1,41 +0,0 @@ -var spawn = require('child_process').spawn; -var net = require('net'); -var async = require('async'); - -var TEST_PUBLIC_PORT = 4599; -var TEST_INTERNAL_PORT = 4598; - -describe('proxy', function () { - - this.timeout(5000); - - it('launches', function (done) { - var cipherlayer; - async.series([ - function (next) { - - cipherlayer = spawn('node', ['main'], { - env: { - PORT: TEST_PUBLIC_PORT, - INTERNAL_PORT: TEST_INTERNAL_PORT - } - }); - cipherlayer.stdout.pipe(process.stdout); - cipherlayer.stderr.pipe(process.stderr); - cipherlayer.stdout.on('data', function (data) { - if (String(data).indexOf('listening on port') > -1) { - return next(); - } - }); - }, - function (next) { - var client = net.connect({port: TEST_PUBLIC_PORT}, function () { - client.destroy(); - cipherlayer.kill('SIGTERM'); - return next(); - }); - } - ], done); - }); - -}); diff --git a/tests-unit/server.js b/tests-unit/server.js deleted file mode 100644 index 4d268a4..0000000 --- a/tests-unit/server.js +++ /dev/null @@ -1,36 +0,0 @@ -var cipherlayer = require('../src/cipherlayer.js'); -var assert = require('assert'); -var net = require('net'); -var config = require('../config.json'); - -describe.skip('server control ', function () { - it('start', function (done) { - cipherlayer.start(config.public_port, config.internal_port, function (err) { - assert.equal(err, null); - var client = net.connect({port: config.public_port}, function () { - client.destroy(); - done(); - }); - }); - }); - - it('stop', function (done) { - cipherlayer.stop(function () { - var free = true; - var tester = net.createServer(); - tester.once('error', function (err) { - if (err.code === 'EADDRINUSE') { - free = false; - } - }); - - tester.once('listening', function () { - tester.close(function () { - if (free) done(); - }); - }); - - tester.listen(config.public_port); - }); - }); -}); From cf6772c8d505eb9afc19d342fbee64a62de65a51 Mon Sep 17 00:00:00 2001 From: guumaster Date: Sat, 27 Feb 2016 17:13:58 +0100 Subject: [PATCH 5/7] only report coverage if commit is in main repo --- circle.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/circle.yml b/circle.yml index 2ec86f9..ebe6e17 100644 --- a/circle.yml +++ b/circle.yml @@ -10,8 +10,8 @@ test: override: - npm run test - npm run coverage - - npm run coveralls - - npm run codeclimate + - if [[ -z $CIRCLE_PR_REPONAME ]] ; then npm run coveralls ; fi + - if [[ -z $CIRCLE_PR_REPONAME ]] ; then npm run codeclimate ; fi deployment: npm: branch: master From 7e83d6f91bab1ff837347c99b0e9ea037ad86490 Mon Sep 17 00:00:00 2001 From: guumaster Date: Sun, 28 Feb 2016 14:11:47 +0100 Subject: [PATCH 6/7] tweaking circleci config to show coverage reports inside the build report. --- circle.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/circle.yml b/circle.yml index ebe6e17..cc48e50 100644 --- a/circle.yml +++ b/circle.yml @@ -19,3 +19,6 @@ deployment: - npm version 1.3.$CIRCLE_BUILD_NUM --no-git-tag-version - echo -e "$NPM_USERNAME\n$NPM_PASSWORD\n$NPM_EMAIL" | npm login - npm publish +general: + artifacts: + - "coverage" From bef48049565c294f50f7757d903b54f40ae3416f Mon Sep 17 00:00:00 2001 From: guumaster Date: Sun, 28 Feb 2016 14:58:17 +0100 Subject: [PATCH 7/7] moves reports to $CIRCLE_TEST_REPORTS after build. --- .editorconfig | 10 +++++----- circle.yml | 12 ++++++++---- package.json | 8 ++++++-- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/.editorconfig b/.editorconfig index 67499cd..7d3addd 100644 --- a/.editorconfig +++ b/.editorconfig @@ -12,11 +12,6 @@ charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true -# NPM rewrites package.json after every install with this settings -[package.json] -indent_style = space -indent_size = 2 - [*.md] trim_trailing_whitespace = false @@ -24,6 +19,11 @@ trim_trailing_whitespace = false indent_style = tab indent_size = 4 +# NPM rewrites package.json after every install with this settings +[package.json] +indent_style = space +indent_size = 2 + [*.feature] indent_style = tab indent_size = 2 diff --git a/circle.yml b/circle.yml index cc48e50..1d4b42e 100644 --- a/circle.yml +++ b/circle.yml @@ -4,14 +4,21 @@ machine: services: - mongodb - redis +general: + artifacts: + - $CIRCLE_TEST_REPORTS test: pre: - cp config_sample.json config.json + - mkdir -p $CIRCLE_TEST_REPORTS/mocha + - mkdir -p $CIRCLE_TEST_REPORTS/cucumber + - mkdir -p $CIRCLE_TEST_REPORTS/coverage override: - - npm run test + - npm run test-ci - npm run coverage - if [[ -z $CIRCLE_PR_REPONAME ]] ; then npm run coveralls ; fi - if [[ -z $CIRCLE_PR_REPONAME ]] ; then npm run codeclimate ; fi + - cp coverage $CIRCLE_ARTIFACTS/coverage -r deployment: npm: branch: master @@ -19,6 +26,3 @@ deployment: - npm version 1.3.$CIRCLE_BUILD_NUM --no-git-tag-version - echo -e "$NPM_USERNAME\n$NPM_PASSWORD\n$NPM_EMAIL" | npm login - npm publish -general: - artifacts: - - "coverage" diff --git a/package.json b/package.json index 4383ddb..9ae8c67 100644 --- a/package.json +++ b/package.json @@ -8,13 +8,16 @@ "test-unit": "mocha tests-unit --recursive", "test-acceptance": "cucumber.js tests-acceptance -f pretty --tags ~@ignore", "test-acceptance-only": "cucumber.js tests-acceptance -f pretty --tags @only", - "lint": "jshint ./src ./tests-unit ./tests-acceptance main.js", + "lint": "jshint src tests-unit tests-acceptance main.js", "coverage-unit": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/unit _mocha -- tests-unit --recursive --reporter mocha-lcov-reporter", "coverage-acceptance": "istanbul cover --root src --include-all-sources --lcovonly --dir ./coverage/acceptance cucumber.js -- tests-acceptance --tags ~@ignore --format json", "coverage-merge": "istanbul-combine coverage/**/coverage.json", "coverage": "npm run coverage-unit && npm run coverage-acceptance && npm run coverage-merge", "coveralls": "istanbul-coveralls", - "codeclimate": "codeclimate-test-reporter < ./coverage/lcov.info" + "codeclimate": "codeclimate-test-reporter < ./coverage/lcov.info", + "test-ci": "npm run lint && npm run test-unit-ci && npm run test-acceptance-ci", + "test-unit-ci": "mocha tests-unit --recursive --reporter mocha-junit-reporter --reporter-options mochaFile=$CIRCLE_TEST_REPORTS/mocha/junit.xml", + "test-acceptance-ci": "cucumber.js tests-acceptance --tags ~@ignore --format json --out $CIRCLE_TEST_REPORTS/cucumber/tests.cucumber" }, "dependencies": { "async": "^1.5.2", @@ -48,6 +51,7 @@ "istanbul-coveralls": "^1.0.3", "jshint": "^2.8.0", "mocha": "^2.0.1", + "mocha-junit-reporter": "^1.9.1", "mocha-lcov-reporter": "^1.2.0", "mockery": "^1.4.0", "nock": "^7.2.2",