diff --git a/api/index.js b/api/index.js index 37363f1c..719d2b23 100644 --- a/api/index.js +++ b/api/index.js @@ -12,186 +12,188 @@ const marriageSearch = `${baseURL}/v1/registration/marriage`; const partnershipSearch = `${baseURL}/v1/registration/partnership`; const userActivity = `${baseURL}/api/v0/audit/user-activity`; -const requestData = (url, accessToken) => +const requestData = (url, requestInfo) => new Promise((resolve, reject) => levRequest.get({ 'url': url }, - accessToken, + requestInfo, helpers.responseHandler(resolve, reject) )); -const findByNameDOB = (searchFields, accessToken) => { +const findByNameDOB = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findByNameDOB(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findByNameDOB(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findByNameDOB(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findByNameDOB(): second argument, requestInfo, must be an object'); } - return requestData(helpers.buildQueryUri(birthSearch, searchFields), accessToken) + return requestData(helpers.buildQueryUri(birthSearch, searchFields), requestInfo) .then((data) => data.map(helpers.processRecord)); }; -const findBySystemNumber = (systemNumber, accessToken) => { +const findBySystemNumber = (systemNumber, requestInfo) => { if (systemNumber === undefined) { throw new ReferenceError('findBySystemNumber(): first argument, systemNumber, was not defined'); } else if ((!Number.isInteger(systemNumber))) { throw new TypeError('findBySystemNumber(): first argument, systemNumber, must be an integer'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findBySystemNumber(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findBySystemNumber(): second argument, requestInfo, must be an object'); } - return requestData(birthSearch + '/' + systemNumber, accessToken) + return requestData(birthSearch + '/' + systemNumber, requestInfo) .then(helpers.processRecord); }; -const findBirths = (searchFields, accessToken) => { +const findBirths = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findBirths(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findBirths(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findBirths(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findBirths(): second argument, requestInfo, must be an object'); } const systemNumber = searchFields['system-number'] && Number.parseInt(searchFields['system-number'], 10); return systemNumber - ? findBySystemNumber(systemNumber, accessToken).then((data) => [data]) - : findByNameDOB(searchFields, accessToken); + ? findBySystemNumber(systemNumber, requestInfo).then((data) => [data]) + : findByNameDOB(searchFields, requestInfo); }; -const findDeathsByNameDate = (searchFields, accessToken) => { +const findDeathsByNameDate = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findDeathsByNameDate(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findDeathsByNameDate(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findDeathsByNameDate(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findDeathsByNameDate(): second argument, requestInfo, must be an object'); } - return requestData(helpers.buildQueryUri(deathSearch, searchFields), accessToken) + return requestData(helpers.buildQueryUri(deathSearch, searchFields), requestInfo) .then((data) => data.map(helpers.processDeathRecord)); }; -const findDeathBySystemNumber = (systemNumber, accessToken) => { +const findDeathBySystemNumber = (systemNumber, requestInfo) => { if (systemNumber === undefined) { throw new ReferenceError('findBySystemNumber(): first argument, systemNumber, was not defined'); } else if ((!Number.isInteger(systemNumber))) { throw new TypeError('findDeathsBySystemNumber(): first argument, systemNumber, must be an integer'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findDeathsBySystemNumber(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findDeathsBySystemNumber(): second argument, requestInfo, must be an object'); } - return requestData(deathSearch + '/' + systemNumber, accessToken) + return requestData(deathSearch + '/' + systemNumber, requestInfo) .then(helpers.processDeathRecord); }; -const findDeaths = (searchFields, accessToken) => { +const findDeaths = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findDeaths(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findDeaths(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findDeaths(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findDeaths(): second argument, requestInfo, must be an object'); } const systemNumber = searchFields['system-number'] && Number.parseInt(searchFields['system-number'], 10); return systemNumber - ? findDeathBySystemNumber(systemNumber, accessToken).then((data) => [data]) - : findDeathsByNameDate(searchFields, accessToken); + ? findDeathBySystemNumber(systemNumber, requestInfo).then((data) => [data]) + : findDeathsByNameDate(searchFields, requestInfo); }; -const findMarriagesByNameDOM = (searchFields, accessToken) => { +const findMarriagesByNameDOM = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findMarriagesByNameDOM(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findMarriagesByNameDOM(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findMarriagesByNameDOM(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findMarriagesByNameDOM(): second argument, requestInfo, must be an object'); } - return requestData(helpers.buildQueryUri(marriageSearch, searchFields), accessToken) + return requestData(helpers.buildQueryUri(marriageSearch, searchFields), requestInfo) .then((data) => data.map(helpers.processMarriageRecord)); }; -const findMarriageBySystemNumber = (systemNumber, accessToken) => { +const findMarriageBySystemNumber = (systemNumber, requestInfo) => { if (systemNumber === undefined) { throw new ReferenceError('findMarriagesBySystemNumber(): first argument, systemNumber, was not defined'); } else if ((!Number.isInteger(systemNumber))) { throw new TypeError('findMarriagesBySystemNumber(): first argument, systemNumber, must be an integer'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findMarriagesBySystemNumber(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findMarriagesBySystemNumber(): second argument, requestInfo, must be an object'); } - return requestData(marriageSearch + '/' + systemNumber, accessToken) + return requestData(marriageSearch + '/' + systemNumber, requestInfo) .then(helpers.processMarriageRecord); }; -const findMarriages = (searchFields, accessToken) => { +const findMarriages = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findMarriages(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findMarriages(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findMarriages(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findMarriages(): second argument, requestInfo, must be an object'); } const systemNumber = searchFields['system-number'] && Number.parseInt(searchFields['system-number'], 10); return systemNumber - ? findMarriageBySystemNumber(systemNumber, accessToken).then((data) => [data]) - : findMarriagesByNameDOM(searchFields, accessToken); + ? findMarriageBySystemNumber(systemNumber, requestInfo).then((data) => [data]) + : findMarriagesByNameDOM(searchFields, requestInfo); }; -const findPartnershipsByNameDOP = (searchFields, accessToken) => { +const findPartnershipsByNameDOP = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findPartnershipsByNameDOP(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findPartnershipsByNameDOP(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findPartnershipsByNameDOP(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findPartnershipsByNameDOP(): second argument, requestInfo, must be an object'); } - return requestData(helpers.buildQueryUri(partnershipSearch, searchFields), accessToken) + return requestData(helpers.buildQueryUri(partnershipSearch, searchFields), requestInfo) .then((data) => data.map(helpers.processPartnershipRecord)); }; -const findPartnershipBySystemNumber = (systemNumber, accessToken) => { +const findPartnershipBySystemNumber = (systemNumber, requestInfo) => { if (systemNumber === undefined) { throw new ReferenceError('findPartnershipsBySystemNumber(): first argument, systemNumber, was not defined'); } else if ((!Number.isInteger(systemNumber))) { throw new TypeError('findPartnershipsBySystemNumber(): first argument, systemNumber, must be an integer'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findPartnershipsBySystemNumber(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findPartnershipsBySystemNumber(): second argument, requestInfo, must be an object'); } - return requestData(partnershipSearch + '/' + systemNumber, accessToken) + return requestData(partnershipSearch + '/' + systemNumber, requestInfo) .then(helpers.processPartnershipRecord); }; -const findPartnerships = (searchFields, accessToken) => { +const findPartnerships = (searchFields, requestInfo) => { if (searchFields === undefined) { throw new ReferenceError('findPartnerships(): first argument, searchFields, was not defined'); } else if (!(searchFields instanceof Object)) { throw new TypeError('findPartnerships(): first argument, searchFields, must be an object'); - } else if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('findPartnerships(): second argument, accessToken, must be a string'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('findPartnerships(): second argument, requestInfo, must be an object'); } const systemNumber = searchFields['system-number'] && Number.parseInt(searchFields['system-number'], 10); return systemNumber - ? findPartnershipBySystemNumber(systemNumber, accessToken).then((data) => [data]) - : findPartnershipsByNameDOP(searchFields, accessToken); + ? findPartnershipBySystemNumber(systemNumber, requestInfo).then((data) => [data]) + : findPartnershipsByNameDOP(searchFields, requestInfo); }; -const userActivityReport = (accessToken, from, to, userFilter) => { // eslint-disable-line complexity - if (accessToken !== undefined && typeof accessToken !== 'string') { - throw new TypeError('The "accessToken" parameter must be a string'); +const userActivityReport = (requestInfo, from, to, userFilter) => { // eslint-disable-line complexity + if (requestInfo === undefined) { + throw new ReferenceError('The "requestInfo" parameter must be an object'); + } else if (!(requestInfo instanceof Object)) { + throw new TypeError('The "requestInfo" parameter must be an object'); } if (!from || !to) { throw new ReferenceError('"from" and "to" dates must be provided for the User Activity report'); @@ -218,7 +220,7 @@ const userActivityReport = (accessToken, from, to, userFilter) => { // eslint-di user: userFilter }; - return requestData(helpers.buildQueryUri(userActivity, data), accessToken); + return requestData(helpers.buildQueryUri(userActivity, data), requestInfo); }; module.exports = { diff --git a/controllers/audit.js b/controllers/audit.js index da3aa979..c4d7f2b2 100644 --- a/controllers/audit.js +++ b/controllers/audit.js @@ -3,6 +3,7 @@ const moment = require('moment'); const Parent = require('../lib/hof-standalone'); const api = require('../api'); +const reqInfo = require('../lib/req-info'); const validators = require('../lib/custom-validators'); const util = require('util'); @@ -68,7 +69,7 @@ const expandUsers = (records, days) => { }; AuditController.prototype.successHandler = function successHandler(req, res, callback) { - const accessToken = req.headers['X-Auth-Token'] || req.headers['x-auth-token']; + const ri = reqInfo(req); const from = validators.parseDate(req.form.values.from).floor(24, 'hours'); const to = validators.parseDate(req.form.values.to).floor(24, 'hours'); const toInclusive = moment(to).add(1, 'day'); @@ -100,7 +101,7 @@ AuditController.prototype.successHandler = function successHandler(req, res, cal callback(error, req, res); }; - api.userActivityReport(accessToken, from, toInclusive, userFilter).then(resolved, rejected); + api.userActivityReport(ri, from, toInclusive, userFilter).then(resolved, rejected); }; const form = new AuditController({ diff --git a/controllers/death-details.js b/controllers/death-details.js index 3c4f4a68..bcb55aa8 100644 --- a/controllers/death-details.js +++ b/controllers/death-details.js @@ -28,7 +28,7 @@ module.exports = function renderDetails(req, res, next) { const canRedirectToResults = (req.query && req.query.multipleResults) !== undefined; - return api.findDeathBySystemNumber(Number(systemNumber), ri.token) + return api.findDeathBySystemNumber(Number(systemNumber), ri) .then(result => res.render('pages/death-details', { record: result, showAll: helpers.showFullDetails(ri), diff --git a/controllers/death-search.js b/controllers/death-search.js index 8daeb465..71de2d65 100644 --- a/controllers/death-search.js +++ b/controllers/death-search.js @@ -5,6 +5,7 @@ const api = require('../api'); const helpers = require('../lib/helpers'); const validators = require('../lib/custom-validators'); const fields = require('../fields/death'); +const reqInfo = require('../lib/req-info'); const util = require('util'); const _ = require('lodash'); @@ -19,9 +20,9 @@ util.inherits(SearchController, Parent); // Only redirect when a single result is returned, otherwise render // results page SearchController.prototype.successHandler = function successHandler(req, res, callback) { - const accessToken = req.headers['X-Auth-Token'] || req.headers['x-auth-token']; const query = _.pick(req.query, _.keys(fields)); const querystring = helpers.serialize(query); + const ri = reqInfo(req); const resolved = (records) => { if (records.length === 1) { @@ -53,7 +54,7 @@ SearchController.prototype.successHandler = function successHandler(req, res, ca } }; - api.findDeaths(req.form.values, accessToken) + api.findDeaths(req.form.values, ri) .then(resolved, rejected); this.emit('complete', req, res); }; diff --git a/controllers/details.js b/controllers/details.js index 8c697f22..0c9e8b94 100644 --- a/controllers/details.js +++ b/controllers/details.js @@ -3,6 +3,7 @@ const api = require('../api'); const helpers = require('../lib/helpers'); const fields = require('../fields'); +const reqInfo = require('../lib/req-info'); const _ = require('lodash'); const handleError = (err, next) => { @@ -16,6 +17,7 @@ const handleError = (err, next) => { module.exports = function renderDetails(req, res, next) { req.params = req.params || {}; const systemNumber = req.params.sysnum; + const ri = reqInfo(req); if (systemNumber === undefined) { return next(new ReferenceError('The parameter \'id\' was not defined'), req, res); @@ -24,10 +26,9 @@ module.exports = function renderDetails(req, res, next) { return next(new TypeError('The parameter \'id\' was not an integer'), req, res); } - const accessToken = req.headers['X-Auth-Token'] || req.headers['x-auth-token']; const canRedirectToResults = (req.query && req.query.multipleResults) !== undefined; - return api.findBySystemNumber(Number(systemNumber), accessToken) + return api.findBySystemNumber(Number(systemNumber), ri) .then(result => res.render('pages/details', { record: result, querystring: helpers.serialize(_.pick(req.query, _.keys(fields))), diff --git a/controllers/marriage-details.js b/controllers/marriage-details.js index c2530679..4d0be93f 100644 --- a/controllers/marriage-details.js +++ b/controllers/marriage-details.js @@ -28,7 +28,7 @@ module.exports = function renderDetails(req, res, next) { const canRedirectToResults = (req.query && req.query.multipleResults) !== undefined; - return api.findMarriageBySystemNumber(Number(systemNumber), ri.token) + return api.findMarriageBySystemNumber(Number(systemNumber), ri) .then(result => res.render('pages/marriage-details', { record: result, showAll: helpers.showFullDetails(ri), diff --git a/controllers/marriage-search.js b/controllers/marriage-search.js index 77e95e45..10e30148 100644 --- a/controllers/marriage-search.js +++ b/controllers/marriage-search.js @@ -5,6 +5,7 @@ const api = require('../api'); const helpers = require('../lib/helpers'); const validators = require('../lib/custom-validators'); const fields = require('../fields/marriage'); +const reqInfo = require('../lib/req-info'); const util = require('util'); const _ = require('lodash'); @@ -19,9 +20,9 @@ util.inherits(SearchController, Parent); // Only redirect when a single result is returned, otherwise render // results page SearchController.prototype.successHandler = function successHandler(req, res, callback) { - const accessToken = req.headers['X-Auth-Token'] || req.headers['x-auth-token']; const query = _.pick(req.query, _.keys(fields)); const querystring = helpers.serialize(query); + const ri = reqInfo(req); const resolved = (records) => { if (records.length === 1) { @@ -53,7 +54,7 @@ SearchController.prototype.successHandler = function successHandler(req, res, ca } }; - api.findMarriages(req.form.values, accessToken) + api.findMarriages(req.form.values, ri) .then(resolved, rejected); this.emit('complete', req, res); }; diff --git a/controllers/partnership-details.js b/controllers/partnership-details.js index 37590b88..f6e56394 100644 --- a/controllers/partnership-details.js +++ b/controllers/partnership-details.js @@ -28,7 +28,7 @@ module.exports = function renderDetails(req, res, next) { const canRedirectToResults = (req.query && req.query.multipleResults) !== undefined; - return api.findPartnershipBySystemNumber(Number(systemNumber), ri.token) + return api.findPartnershipBySystemNumber(Number(systemNumber), ri) .then(result => res.render('pages/partnership-details', { record: result, showAll: helpers.showFullDetails(ri), diff --git a/controllers/partnership-search.js b/controllers/partnership-search.js index d4ee444a..792e6a18 100644 --- a/controllers/partnership-search.js +++ b/controllers/partnership-search.js @@ -5,6 +5,7 @@ const api = require('../api'); const helpers = require('../lib/helpers'); const validators = require('../lib/custom-validators'); const fields = require('../fields/partnership'); +const reqInfo = require('../lib/req-info'); const util = require('util'); const _ = require('lodash'); @@ -19,9 +20,9 @@ util.inherits(SearchController, Parent); // Only redirect when a single result is returned, otherwise render // results page SearchController.prototype.successHandler = function successHandler(req, res, callback) { - const accessToken = req.headers['X-Auth-Token'] || req.headers['x-auth-token']; const query = _.pick(req.query, _.keys(fields)); const querystring = helpers.serialize(query); + const ri = reqInfo(req); const resolved = (records) => { if (records.length === 1) { @@ -53,7 +54,7 @@ SearchController.prototype.successHandler = function successHandler(req, res, ca } }; - api.findPartnerships(req.form.values, accessToken) + api.findPartnerships(req.form.values, ri) .then(resolved, rejected); this.emit('complete', req, res); }; diff --git a/controllers/search.js b/controllers/search.js index 1b692fcd..eb4bf97e 100644 --- a/controllers/search.js +++ b/controllers/search.js @@ -5,6 +5,7 @@ const api = require('../api'); const helpers = require('../lib/helpers'); const validators = require('../lib/custom-validators'); const fields = require('../fields'); +const reqInfo = require('../lib/req-info'); const util = require('util'); const _ = require('lodash'); @@ -19,9 +20,9 @@ util.inherits(SearchController, Parent); // Only redirect when a single result is returned, otherwise render // results page SearchController.prototype.successHandler = function successHandler(req, res, callback) { - const accessToken = req.headers['X-Auth-Token'] || req.headers['x-auth-token']; const query = _.pick(req.query, _.keys(fields)); const querystring = helpers.serialize(query); + const ri = reqInfo(req); const resolved = (records) => { if (records.length === 1) { @@ -53,7 +54,7 @@ SearchController.prototype.successHandler = function successHandler(req, res, ca } }; - api.findBirths(req.form.values, accessToken) + api.findBirths(req.form.values, ri) .then(resolved, rejected); this.emit('complete', req, res); }; diff --git a/lib/lev-request.js b/lib/lev-request.js index c46e93ce..da70958f 100644 --- a/lib/lev-request.js +++ b/lib/lev-request.js @@ -20,7 +20,10 @@ const addTlsConfig = (requestArgs) => { return requestArgs; }; -const addAuthHeaders = (requestArgs, token) => { +const addAuthHeaders = (requestArgs, requestInfo) => { + const token = requestInfo && requestInfo.token; + const roles = requestInfo && requestInfo.roles; + requestArgs = requestHelper.urlToObject(requestArgs); requestArgs.headers = requestArgs.headers || {}; requestArgs.headers['X-Auth-Username'] = config.api.username; @@ -28,13 +31,17 @@ const addAuthHeaders = (requestArgs, token) => { if (token) { requestArgs.headers.Authorization = 'Bearer ' + token; + } else if (roles) { + requestArgs.headers['X-Auth-Roles'] = roles.join(','); } return requestArgs; }; -const get = (requestGetArgs, accessToken, callback) => { - return request.get(addTlsConfig(addAuthHeaders(requestGetArgs, accessToken)), accessToken, callback); +const get = (requestGetArgs, requestInfo, callback) => { + const token = requestInfo && requestInfo.token; + + return request.get(addTlsConfig(addAuthHeaders(requestGetArgs, requestInfo)), token, callback); }; module.exports = { diff --git a/test/unit/api/index.js b/test/unit/api/index.js index 02ef0d6d..03074def 100644 --- a/test/unit/api/index.js +++ b/test/unit/api/index.js @@ -350,6 +350,7 @@ const parsedPartnershipResponse = { }; const accessToken = 'access_token'; +const ri = { token: accessToken }; const expectedHeaders = { 'Authorization': 'Bearer ' + accessToken, 'X-Auth-Username': 'user', @@ -415,7 +416,7 @@ describe('api/index.js', () => { dob: '01/01/2001' }; - result = api.findByNameDOB(query, accessToken); + result = api.findByNameDOB(query, ri); }); it('make a request using the correct query string and adds auth headers', () => @@ -437,7 +438,7 @@ describe('api/index.js', () => { describe('when the api returns a valid list of records', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, JSON.stringify([response])); - result = api.findByNameDOB({}, ''); + result = api.findByNameDOB({}, {}); }); it('resolves to a processed record', () => @@ -447,7 +448,7 @@ describe('api/index.js', () => { describe('when the api returns invalid JSON', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, '[}'); - result = api.findByNameDOB({}, ''); + result = api.findByNameDOB({}, {}); }); it('rejects with an error', () => @@ -457,7 +458,7 @@ describe('api/index.js', () => { describe('when the api gives a 404', () => { before(() => { requestGet.yields(null, { statusCode: 404 }, ''); - result = api.findByNameDOB({}, ''); + result = api.findByNameDOB({}, {}); }); it('rejects with a \'NotFoundError\' error', () => @@ -467,7 +468,7 @@ describe('api/index.js', () => { describe('when the api gives a 401', () => { before(() => { requestGet.yields(null, { statusCode: 401 }, ''); - result = api.findByNameDOB({}, ''); + result = api.findByNameDOB({}, {}); }); it('rejects with a \'NotAuthorized\' error', () => @@ -477,7 +478,7 @@ describe('api/index.js', () => { describe('when something else happens', () => { before(() => { requestGet.yields(new Error('Something else happened')); - result = api.findByNameDOB({}, ''); + result = api.findByNameDOB({}, {}); }); it('rejects with an error', () => @@ -509,7 +510,7 @@ describe('api/index.js', () => { describe('and the second IS a string', () => { let result; let query; - const read = () => api.findBirths(query, accessToken); + const read = () => api.findBirths(query, ri); describe('and the first DOES NOT contain a \'system-number\' property', () => { @@ -697,7 +698,7 @@ describe('api/index.js', () => { this.resetStubs = false; const id = 400000001; - result = api.findBySystemNumber(id, accessToken); + result = api.findBySystemNumber(id, ri); }); it('makes a request using the correct query string and adds auth headers', () => @@ -718,7 +719,7 @@ describe('api/index.js', () => { describe('when the api returns a valid record', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, JSON.stringify(response)); - result = api.findBySystemNumber(0, ''); + result = api.findBySystemNumber(0, {}); }); it('resolves to a processed record', () => result.should.eventually.eql(parsedResponse)); @@ -727,7 +728,7 @@ describe('api/index.js', () => { describe('when the api returns invalid JSON', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, '[}'); - result = api.findBySystemNumber(0, ''); + result = api.findBySystemNumber(0, {}); }); it('rejects with an error', () => result.should.be.rejectedWith(Error)); @@ -736,7 +737,7 @@ describe('api/index.js', () => { describe('when the api gives a 404', () => { before(() => { requestGet.yields(null, { statusCode: 404 }, ''); - result = api.findBySystemNumber(0, ''); + result = api.findBySystemNumber(0, {}); }); it('rejects with a \'NotFoundError\' error', () => @@ -746,7 +747,7 @@ describe('api/index.js', () => { describe('when the api gives a 401', () => { before(() => { requestGet.yields(null, { statusCode: 401 }, ''); - result = api.findBySystemNumber(0, ''); + result = api.findBySystemNumber(0, {}); }); it('rejects with a \'NotAuthorized\' error', () => @@ -756,7 +757,7 @@ describe('api/index.js', () => { describe('when something else happens', () => { before(() => { requestGet.yields(new Error('Something else happened')); - result = api.findBySystemNumber(0, ''); + result = api.findBySystemNumber(0, {}); }); it('rejects with an error', () => @@ -799,7 +800,7 @@ describe('api/index.js', () => { dop: '01/01/2001' }; - result = api.findPartnershipsByNameDOP(query, accessToken); + result = api.findPartnershipsByNameDOP(query, ri); }); it('make a request using the correct query string and adds auth headers', () => @@ -821,7 +822,7 @@ describe('api/index.js', () => { describe('when the api returns a valid list of records', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, JSON.stringify([partnershipResponse])); - result = api.findPartnershipsByNameDOP({}, ''); + result = api.findPartnershipsByNameDOP({}, {}); }); it('resolves to a processed record', () => @@ -831,7 +832,7 @@ describe('api/index.js', () => { describe('when the api returns invalid JSON', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, '[}'); - result = api.findPartnershipsByNameDOP({}, ''); + result = api.findPartnershipsByNameDOP({}, {}); }); it('rejects with an error', () => @@ -841,7 +842,7 @@ describe('api/index.js', () => { describe('when the api gives a 404', () => { before(() => { requestGet.yields(null, { statusCode: 404 }, ''); - result = api.findPartnershipsByNameDOP({}, ''); + result = api.findPartnershipsByNameDOP({}, {}); }); it('rejects with a \'NotFoundError\' error', () => @@ -851,7 +852,7 @@ describe('api/index.js', () => { describe('when the api gives a 401', () => { before(() => { requestGet.yields(null, { statusCode: 401 }, ''); - result = api.findPartnershipsByNameDOP({}, ''); + result = api.findPartnershipsByNameDOP({}, {}); }); it('rejects with a \'NotAuthorized\' error', () => @@ -861,7 +862,7 @@ describe('api/index.js', () => { describe('when something else happens', () => { before(() => { requestGet.yields(new Error('Something else happened')); - result = api.findPartnershipsByNameDOP({}, ''); + result = api.findPartnershipsByNameDOP({}, {}); }); it('rejects with an error', () => @@ -893,7 +894,7 @@ describe('api/index.js', () => { describe('and the second IS a string', () => { let result; let query; - const read = () => api.findPartnerships(query, accessToken); + const read = () => api.findPartnerships(query, ri); describe('and the first DOES NOT contain a \'system-number\' property', () => { @@ -1081,7 +1082,7 @@ describe('api/index.js', () => { this.resetStubs = false; const id = 400000001; - result = api.findPartnershipBySystemNumber(id, accessToken); + result = api.findPartnershipBySystemNumber(id, ri); }); it('makes a request using the correct query string and adds auth headers', () => @@ -1102,7 +1103,7 @@ describe('api/index.js', () => { describe('when the api returns a valid record', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, JSON.stringify(partnershipResponse)); - result = api.findPartnershipBySystemNumber(0, ''); + result = api.findPartnershipBySystemNumber(0, {}); }); it('resolves to a processed record', () => result.should.eventually.eql(parsedPartnershipResponse)); @@ -1111,7 +1112,7 @@ describe('api/index.js', () => { describe('when the api returns invalid JSON', () => { before(() => { requestGet.yields(null, { statusCode: 200 }, '[}'); - result = api.findPartnershipBySystemNumber(0, ''); + result = api.findPartnershipBySystemNumber(0, {}); }); it('rejects with an error', () => result.should.be.rejectedWith(Error)); @@ -1120,7 +1121,7 @@ describe('api/index.js', () => { describe('when the api gives a 404', () => { before(() => { requestGet.yields(null, { statusCode: 404 }, ''); - result = api.findPartnershipBySystemNumber(0, ''); + result = api.findPartnershipBySystemNumber(0, {}); }); it('rejects with a \'NotFoundError\' error', () => @@ -1130,7 +1131,7 @@ describe('api/index.js', () => { describe('when the api gives a 401', () => { before(() => { requestGet.yields(null, { statusCode: 401 }, ''); - result = api.findPartnershipBySystemNumber(0, ''); + result = api.findPartnershipBySystemNumber(0, {}); }); it('rejects with a \'NotAuthorized\' error', () => @@ -1140,7 +1141,7 @@ describe('api/index.js', () => { describe('when something else happens', () => { before(() => { requestGet.yields(new Error('Something else happened')); - result = api.findPartnershipBySystemNumber(0, ''); + result = api.findPartnershipBySystemNumber(0, {}); }); it('rejects with an error', () => @@ -1160,36 +1161,36 @@ describe('api/index.js', () => { describe('when called with an invalid system user', () => { it('should throw a TypeError if the `user` parameter is not a proper string', () => { - expect(() => api.userActivityReport(accessToken, moment().add(-1, 'days'), moment(), null)).to.throw(TypeError); - expect(() => api.userActivityReport(accessToken, moment().add(-1, 'days'), moment(), 42)).to.throw(TypeError); + expect(() => api.userActivityReport(ri, moment().add(-1, 'days'), moment(), null)).to.throw(TypeError); + expect(() => api.userActivityReport(ri, moment().add(-1, 'days'), moment(), 42)).to.throw(TypeError); }); }); describe('when called without the required `from` or `to` dates', () => { it('should throw a ReferenceError if either parameter is omitted', () => { - expect(from => api.userActivityReport(accessToken, from, moment())).to.throw(ReferenceError); - expect(() => api.userActivityReport(accessToken, moment())).to.throw(ReferenceError); + expect(from => api.userActivityReport(ri, from, moment())).to.throw(ReferenceError); + expect(() => api.userActivityReport(ri, moment())).to.throw(ReferenceError); }); it('should throw a TypeError if either parameter is not a `moment` date object', () => { - expect(() => api.userActivityReport(accessToken, 'from', moment())).to.throw(TypeError); - expect(() => api.userActivityReport(accessToken, moment(), 'to')).to.throw(TypeError); + expect(() => api.userActivityReport(ri, 'from', moment())).to.throw(TypeError); + expect(() => api.userActivityReport(ri, moment(), 'to')).to.throw(TypeError); }); it('should throw a RangeError if either parameter is not a valid date object', () => { - expect(() => api.userActivityReport(accessToken, moment('from'), moment())) + expect(() => api.userActivityReport(ri, moment('from'), moment())) .to.throw(RangeError); - expect(() => api.userActivityReport(accessToken, moment('2017-02-27'), moment('2017-02-29'))) + expect(() => api.userActivityReport(ri, moment('2017-02-27'), moment('2017-02-29'))) .to.throw(RangeError); }); }); describe('when called with valid dates', () => { it('should throw a RangeError if the `to` date is before `from`', () => - expect(() => api.userActivityReport(accessToken, moment().add(1, 'days'), moment())).to.throw(RangeError) + expect(() => api.userActivityReport(ri, moment().add(1, 'days'), moment())).to.throw(RangeError) ); const days = config.MAX_AUDIT_RANGE + 1; it(`should throw a RangeError if the date range is greater than the ${config.MAX_AUDIT_RANGE} day limit`, () => - expect(() => api.userActivityReport(accessToken, moment().subtract(days, 'days'), moment())) + expect(() => api.userActivityReport(ri, moment().subtract(days, 'days'), moment())) .to.throw(RangeError, `less than ${config.MAX_AUDIT_RANGE} days`) ); @@ -1200,7 +1201,7 @@ describe('api/index.js', () => { before('try to get the user activity data', () => { this.resetStubs = false; - result = api.userActivityReport(accessToken, moment(from), moment(to)); + result = api.userActivityReport(ri, moment(from), moment(to)); }); it('should make a request to the API', () => @@ -1227,7 +1228,7 @@ describe('api/index.js', () => { before('try to get the user activity data', () => { this.resetStubs = false; - result = api.userActivityReport(accessToken, moment(from), moment(to), 'fred'); + result = api.userActivityReport(ri, moment(from), moment(to), 'fred'); }); it('should make a request to the API', () => diff --git a/test/unit/controllers/audit.js b/test/unit/controllers/audit.js index 31097360..bda6119c 100644 --- a/test/unit/controllers/audit.js +++ b/test/unit/controllers/audit.js @@ -7,6 +7,7 @@ const rewire = require('rewire'); var _ = require('lodash'); const auditController = rewire('../../../controllers/audit'); +const reqInfo = require('../../../lib/req-info'); /* eslint-disable no-underscore-dangle */ const dayGenerator = auditController.__get__('dayGenerator'); const daysInDateRange = auditController.__get__('daysInDateRange'); @@ -61,6 +62,7 @@ describe('Audit Controller', () => { describe('when there is a query string', () => { let req; + let ri; beforeEach(() => { req = _.extend(reqres.req(), { @@ -70,6 +72,7 @@ describe('Audit Controller', () => { }, method: 'GET' }); + ri = reqInfo(req); }); describe('the resolved promise', () => { @@ -82,7 +85,7 @@ describe('Audit Controller', () => { const toAdjusted = '02/01/1900'; const matchFrom = sinon.match.object.and(momentMatcher(moment(req.query.from, 'DD/MM/YYYY'))); const matchTo = sinon.match.object.and(momentMatcher(moment(toAdjusted, 'DD/MM/YYYY'))); - api.userActivityReport.withArgs(accessToken, matchFrom, matchTo).returns(Promise.resolve({})); + api.userActivityReport.withArgs(ri, matchFrom, matchTo).returns(Promise.resolve({})); res.render = (view, data) => { try { @@ -113,7 +116,7 @@ describe('Audit Controller', () => { const toAdjusted = '03/03/1900'; const matchFrom = sinon.match.object.and(momentMatcher(moment(req.query.from, 'DD/MM/YYYY'))); const matchTo = sinon.match.object.and(momentMatcher(moment(toAdjusted, 'DD/MM/YYYY'))); - api.userActivityReport.withArgs(accessToken, matchFrom, matchTo, req.query.user) + api.userActivityReport.withArgs(ri, matchFrom, matchTo, req.query.user) .returns(Promise.resolve({})); res.render = (view, data) => { @@ -150,7 +153,7 @@ describe('Audit Controller', () => { const toAdjusted = '04/02/2017'; const matchFrom = sinon.match.object.and(momentMatcher(moment(req.query.from, 'DD/MM/YYYY'))); const matchTo = sinon.match.object.and(momentMatcher(moment(toAdjusted, 'DD/MM/YYYY'))); - api.userActivityReport.withArgs(accessToken, matchFrom, matchTo).returns(Promise.resolve(records)); + api.userActivityReport.withArgs(ri, matchFrom, matchTo).returns(Promise.resolve(records)); res.render = (view, data) => { try { @@ -195,7 +198,7 @@ describe('Audit Controller', () => { const toAdjusted = '04/02/2017'; const matchFrom = sinon.match.object.and(momentMatcher(moment(req.query.from, 'DD/MM/YYYY'))); const matchTo = sinon.match.object.and(momentMatcher(moment(toAdjusted, 'DD/MM/YYYY'))); - api.userActivityReport.withArgs(accessToken, matchFrom, matchTo, req.query.user) + api.userActivityReport.withArgs(ri, matchFrom, matchTo, req.query.user) .returns(Promise.resolve(records)); res.render = (view, data) => { @@ -225,7 +228,7 @@ describe('Audit Controller', () => { const toAdjusted = '16/01/2016'; const matchFrom = sinon.match.object.and(momentMatcher(moment(req.query.from, 'DD/MM/YYYY'))); const matchTo = sinon.match.object.and(momentMatcher(moment(toAdjusted, 'DD/MM/YYYY'))); - api.userActivityReport.withArgs(accessToken, matchFrom, matchTo).returns(Promise.reject(err)); + api.userActivityReport.withArgs(ri, matchFrom, matchTo).returns(Promise.reject(err)); const next = (error) => { try { @@ -248,7 +251,7 @@ describe('Audit Controller', () => { const toAdjusted = '21/01/2009'; const matchFrom = sinon.match.object.and(momentMatcher(moment(req.query.from, 'DD/MM/YYYY'))); const matchTo = sinon.match.object.and(momentMatcher(moment(toAdjusted, 'DD/MM/YYYY'))); - api.userActivityReport.withArgs(accessToken, matchFrom, matchTo).returns(Promise.reject(err.message)); + api.userActivityReport.withArgs(ri, matchFrom, matchTo).returns(Promise.reject(err.message)); const next = (error) => { try { diff --git a/test/unit/controllers/details.js b/test/unit/controllers/details.js index bc27074b..91c5b4dc 100644 --- a/test/unit/controllers/details.js +++ b/test/unit/controllers/details.js @@ -2,20 +2,18 @@ const rewire = require('rewire'); const detailsController = rewire('../../../controllers/details'); +const reqInfo = require('../../../lib/req-info'); const api = detailsController.__get__('api'); // eslint-disable-line no-underscore-dangle const accessToken = 'accessToken'; describe('controllers/details', function() { + var ri; var req; var res; var next; beforeEach(() => { - sinon.stub(api, 'findBySystemNumber'); - api.findBySystemNumber.withArgs(1234, accessToken).resolves({ records: [] }); - api.findBySystemNumber.withArgs(34404, accessToken).rejects('error'); - req = { params: { sysnum: '1234' @@ -31,6 +29,12 @@ describe('controllers/details', function() { }; next = sinon.spy(); + + ri = reqInfo(req); + + sinon.stub(api, 'findBySystemNumber'); + api.findBySystemNumber.withArgs(1234, ri).resolves({ records: [] }); + api.findBySystemNumber.withArgs(34404, ri).rejects('error'); }); afterEach(() => { @@ -67,7 +71,7 @@ describe('controllers/details', function() { it('calls the api with the request GET params', function() { detailsController(req, res, next); - api.findBySystemNumber.should.have.been.calledWith(1234, accessToken); + api.findBySystemNumber.should.have.been.calledWith(1234, ri); }); it('raises an error with no GET params', function() { diff --git a/test/unit/controllers/marriage-details.js b/test/unit/controllers/marriage-details.js index c5a79cec..4698390c 100644 --- a/test/unit/controllers/marriage-details.js +++ b/test/unit/controllers/marriage-details.js @@ -2,21 +2,19 @@ const rewire = require('rewire'); const detailsController = rewire('../../../controllers/marriage-details'); +const reqInfo = require('../../../lib/req-info'); const api = detailsController.__get__('api'); // eslint-disable-line no-underscore-dangle const role = require('../../../config').fullDetailsRoleName; const accessToken = 'accessToken'; describe('controllers/marriage-details', function() { + let ri; let req; let res; let next; beforeEach(() => { - sinon.stub(api, 'findMarriageBySystemNumber'); - api.findMarriageBySystemNumber.withArgs(1234, accessToken).resolves({ records: [] }); - api.findMarriageBySystemNumber.withArgs(34404, accessToken).rejects('error'); - req = { params: { sysnum: '1234' @@ -30,6 +28,11 @@ describe('controllers/marriage-details', function() { redirect: sinon.spy() }; next = sinon.spy(); + ri = reqInfo(req); + + sinon.stub(api, 'findMarriageBySystemNumber'); + api.findMarriageBySystemNumber.withArgs(1234, ri).resolves({ records: [] }); + api.findMarriageBySystemNumber.withArgs(34404, ri).rejects('error'); }); afterEach(() => { @@ -65,7 +68,7 @@ describe('controllers/marriage-details', function() { it('calls the api with the request GET params', () => { detailsController(req, res, next); - api.findMarriageBySystemNumber.should.have.been.calledWith(1234, accessToken); + api.findMarriageBySystemNumber.should.have.been.calledWith(1234, ri); }); it('raises an error with no GET params', () => { @@ -87,6 +90,9 @@ describe('controllers/marriage-details', function() { describe('with "full-details" role', () => { beforeEach(() => { req.headers['x-auth-roles'] = role; + ri = reqInfo(req); + api.findMarriageBySystemNumber.withArgs(1234, ri).resolves({ records: [] }); + api.findMarriageBySystemNumber.withArgs(34404, ri).rejects('error'); }); it('renders the full details page', () => diff --git a/test/unit/controllers/partnership-details.js b/test/unit/controllers/partnership-details.js index 9d59bba5..f7c7b678 100644 --- a/test/unit/controllers/partnership-details.js +++ b/test/unit/controllers/partnership-details.js @@ -2,21 +2,19 @@ const rewire = require('rewire'); const detailsController = rewire('../../../controllers/partnership-details'); +const reqInfo = require('../../../lib/req-info'); const api = detailsController.__get__('api'); // eslint-disable-line no-underscore-dangle const role = require('../../../config').fullDetailsRoleName; const accessToken = 'accessToken'; describe('controllers/partnership-details', function() { + let ri; let req; let res; let next; beforeEach(() => { - sinon.stub(api, 'findPartnershipBySystemNumber'); - api.findPartnershipBySystemNumber.withArgs(1234, accessToken).resolves({ records: [] }); - api.findPartnershipBySystemNumber.withArgs(34404, accessToken).rejects('error'); - req = { params: { sysnum: '1234' @@ -30,6 +28,11 @@ describe('controllers/partnership-details', function() { redirect: sinon.spy() }; next = sinon.spy(); + ri = reqInfo(req); + + sinon.stub(api, 'findPartnershipBySystemNumber'); + api.findPartnershipBySystemNumber.withArgs(1234, ri).resolves({ records: [] }); + api.findPartnershipBySystemNumber.withArgs(34404, ri).rejects('error'); }); afterEach(() => { @@ -65,7 +68,7 @@ describe('controllers/partnership-details', function() { it('calls the api with the request GET params', () => { detailsController(req, res, next); - api.findPartnershipBySystemNumber.should.have.been.calledWith(1234, accessToken); + api.findPartnershipBySystemNumber.should.have.been.calledWith(1234, ri); }); it('raises an error with no GET params', () => { @@ -95,6 +98,9 @@ describe('controllers/partnership-details', function() { describe('with "full-details" role', () => { beforeEach(() => { req.headers['x-auth-roles'] = role; + ri = reqInfo(req); + api.findPartnershipBySystemNumber.withArgs(1234, ri).resolves({ records: [] }); + api.findPartnershipBySystemNumber.withArgs(34404, ri).rejects('error'); }); it('renders the full details page', () => diff --git a/test/unit/lib/lev-request.js b/test/unit/lib/lev-request.js index f426cf7f..9c749650 100644 --- a/test/unit/lib/lev-request.js +++ b/test/unit/lib/lev-request.js @@ -78,7 +78,7 @@ describe('lib/lev-request', function() { }); it('Adds a bearer token when provided', () => { - levRequest.get('http://testhost.com', 'access_token'); + levRequest.get('http://testhost.com', { token: 'access_token' }); requestGet.should.have.been.calledWith({ url: 'http://testhost.com',