From 7e1c7c2efb073fb77e39b3e3a21f14ddde68ef62 Mon Sep 17 00:00:00 2001 From: Francisco de la Vega Date: Fri, 1 Mar 2019 12:57:14 +0100 Subject: [PATCH] Fix issues with auth tests --- lib/auth.js | 214 +++++++++++++++++++++++++--------------------------- 1 file changed, 103 insertions(+), 111 deletions(-) diff --git a/lib/auth.js b/lib/auth.js index c385f836..d059a6c0 100755 --- a/lib/auth.js +++ b/lib/auth.js @@ -28,43 +28,40 @@ var async = require('async'), function auth () { var tokensCache = {}; - var orgsEnum = { PENDING: 1, PROCESSING: 2, PROCESSED: 3 }; - - var FIWARE_STRATEGY = new FIWAREStrategy( - { - clientID: config.oauth2.clientID, - clientSecret: config.oauth2.clientSecret, - callbackURL: config.oauth2.callbackURL, - serverURL: config.oauth2.server, - isLegacy: config.oauth2.isLegacy - }, - function(accessToken, refreshToken, profile, done) { - profile['accessToken'] = accessToken; - profile['refreshToken'] = refreshToken; - profile['expire'] = Date.now() + 3600000; - - // Save - TokenService.update( - { userId: profile.id }, - { authToken: accessToken, refreshToken: refreshToken, expire: profile['expire'] }, - { upsert: true, setDefaultsOnInsert: true }, - function(err) { - if (err) { - done(err); - } else { - done(null, profile); - } + var orgsEnum = {PENDING: 1, PROCESSING: 2, PROCESSED: 3}; + + var FIWARE_STRATEGY = new FIWAREStrategy({ + clientID: config.oauth2.clientID, + clientSecret: config.oauth2.clientSecret, + callbackURL: config.oauth2.callbackURL, + serverURL: config.oauth2.server, + isLegacy: config.oauth2.isLegacy + }, function (accessToken, refreshToken, profile, done) { + profile['accessToken'] = accessToken; + profile['refreshToken'] = refreshToken; + profile['expire'] = Date.now() + 3600000; + + // Save + TokenService.update( + { userId: profile.id }, + { authToken: accessToken, refreshToken: refreshToken, expire: profile['expire'] }, + { upsert: true, setDefaultsOnInsert: true }, + function (err) { + if (err) { + done(err); + } else { + done(null, profile); } - ); - } - ); + }); + }); // Replace userProfile function to check FIWARE_STRATEGY._userProfile = FIWARE_STRATEGY.userProfile; FIWARE_STRATEGY.userProfile = function(authToken, callback) { - if (tokensCache[authToken] && tokensCache[authToken].expire - Date.now() >= 5000) { - logger.debug('Using cached token for user ' + tokensCache[authToken].id); + + if (tokensCache[authToken] && (tokensCache[authToken].expire - Date.now() >= 5000)) { + logger.debug('Using cached token for user ' + tokensCache[authToken].id); callback(null, tokensCache[authToken]); } else { FIWARE_STRATEGY._userProfile(authToken, function(err, userProfile) { @@ -87,14 +84,14 @@ function auth () { } }; - var setPartyObj = function(req, res, next) { + var setPartyObj = function (req, res, next) { if (!req.user) { next(); } else { - var orgId = req.headers && req.headers['x-organization'] ? req.headers['x-organization'] : ''; - var org = req.user.organizations ? req.user.organizations.find((x) => x.id === orgId) : undefined; + var orgId = (req.headers && req.headers['x-organization']) ? req.headers['x-organization'] : ''; + var org = req.user.organizations ? req.user.organizations.find( x => x.id === orgId) : undefined; - if (!org && orgId !== '') { + if (!org && orgId != ''){ utils.sendUnauthorized(res, 'You are not allowed to act on behalf the provided organization'); } else { var orgTemplate = {}; @@ -108,7 +105,7 @@ function auth () { orgTemplate.refreshToken = req.user.refreshToken; orgTemplate.email = org.id + '@emailnotusable.com'; } - req.user = req.headers && req.headers['x-organization'] && orgTemplate.id ? orgTemplate : req.user; + req.user = (req.headers && req.headers['x-organization'] && orgTemplate.id) ? orgTemplate : req.user; next(); } @@ -116,7 +113,7 @@ function auth () { }; var headerAuthentication = function(req, res, next) { - var askUserToken = function(token, end) { + var askUserToken = function (token, end) { FIWARE_STRATEGY.userProfile(token, (err, userProfile) => { if (err) { utils.log(logger, 'warn', req, 'Token ' + token + ' invalid'); @@ -125,10 +122,7 @@ function auth () { if (userProfile.appId !== config.oauth2.clientID) { utils.log(logger, 'warn', req, 'Token ' + token + ' is from a different app'); if (end) { - utils.sendUnauthorized( - res, - 'It has not been possible to obtain your user info. Have you authorized this app to access your info?' - ); + utils.sendUnauthorized(res, 'It has not been possible to obtain your user info. Have you authorized this app to access your info?'); } else { sameToken(token, userProfile.id, () => { askUserToken(token, true); @@ -149,7 +143,9 @@ function auth () { try { var authToken = utils.getAuthToken(req.headers); askUserToken(authToken, false); + } catch (err) { + if (err.name === 'AuthorizationTokenNotFound') { utils.log(logger, 'info', req, 'request without authentication'); next(); @@ -158,38 +154,36 @@ function auth () { utils.sendUnauthorized(res, err.message); } } + } else { next(); } }; - var checkOrganizations = function(req, res, next) { - var concatRoles = function(newRoles, oldRoles) { + var checkOrganizations = function(req, res, next){ + var concatRoles = function(newRoles, oldRoles){ oldRoles.relatedParty = oldRoles.relatedParty.concat(newRoles); - return oldRoles; + return oldRoles }; var buildOrganization = function(element, finalRoles, callback) { - var concatOrgRoles = function(res) { + var concatOrgRoles = function (res) { var org = JSON.parse(res.body); - finalRoles = concatRoles( - { - id: org.id, - name: org.tradingName, - href: org.href, - role: element.roles.map((role) => role.name).join(',') - }, - finalRoles - ); + finalRoles = concatRoles({ + 'id': org.id, + 'name': org.tradingName, + 'href': org.href, + 'role': element.roles.map(role => role.name).join(',') + }, finalRoles); callback(null); }; party.getOrganization(element.id, (err, res) => { - if (err && err.status === '404') { + if (err && err.status == '404') { var content = { - id: element.id, - tradingName: element.name + 'id': element.id, + 'tradingName': element.name }; party.createOrganization(content, (err, res) => { if (err) { @@ -198,18 +192,20 @@ function auth () { concatOrgRoles(res); } }); + } else if (err) { callback(err); + } else { concatOrgRoles(res); } }); }; - if (!req.user || tokensCache[req.user.accessToken].orgState !== orgsEnum.PENDING) { + if (!req.user || tokensCache[req.user.accessToken].orgState != orgsEnum.PENDING){ next(); } else { - var finalRoles = { relatedParty: [] }; + var finalRoles = {"relatedParty": []}; tokensCache[req.user.accessToken].orgState = orgsEnum.PROCESSING; async.waterfall([ @@ -260,60 +256,54 @@ function auth () { p.reject(err); } else { p.resolve(); - } - }); - return p; + } }); + return p; }); + }); - promise - .then(() => { - callback(null, finalRoles); - }) - .catch((err) => { - callback(err); - }); - }, - function(finalRoles, callback) { - // Update individual object with new organizations and roles - party.updateIndividual(req.user.id, finalRoles, callback); - } - ], - (err) => { - if (err) { - // An error happened processing party info, thus the user request cannot be processed - utils.log(logger, 'warn', req, err.message); - tokensCache[req.user.accessToken].orgState = orgsEnum.PENDING; - utils.sendUnexpectedError(res, 'Unexpected Error: ' + err.message); - } else { - // Organization info for the current access token has been processed and cached - tokensCache[req.user.accessToken].orgState = orgsEnum.PROCESSED; - next(); - } + promise.then(() => { + callback(null, finalRoles); + }).catch((err) => { + callback(err); + }); + + }, + function(finalRoles, callback) { + // Update individual object with new organizations and roles + party.updateIndividual(req.user.id, finalRoles, callback); } - ); + ], (err) => { + if (err){ + // An error happened processing party info, thus the user request cannot be processed + utils.log(logger, 'warn', req, err.message); + tokensCache[req.user.accessToken].orgState = orgsEnum.PENDING; + utils.sendUnexpectedError(res, 'Unexpected Error: ' + err.message) + + } else { + // Organization info for the current access token has been processed and cached + tokensCache[req.user.accessToken].orgState = orgsEnum.PROCESSED; + next(); + } + }); } }; - + // Refresh token & update data in db var refreshToken = function refreshToken(id, refreshToken, cb) { - FIWARE_STRATEGY._oauth2.getOAuthAccessToken( - refreshToken, - { grant_type: 'refresh_token' }, - (err, authToken, newRefresh) => { - if (err) { - cb(err); - } else { - TokenService.update( - { userId: id }, - { authToken: authToken, refreshToken: newRefresh, expire: Date.now() + 3600000 }, - () => { - cb(err, authToken, newRefresh); - } - ); - } + FIWARE_STRATEGY._oauth2.getOAuthAccessToken(refreshToken, { grant_type: "refresh_token" }, (err, authToken, newRefresh) => { + if (err) { + cb(err); + } else { + TokenService.update( + { userId: id }, + { authToken: authToken, refreshToken: newRefresh, expire: Date.now() + 3600000 }, + () => { + cb(err, authToken, newRefresh); + } + ); } - ); + }); }; var refresh = function refresh(data, cb) { @@ -341,8 +331,8 @@ function auth () { } }; - var sameToken = function(authToken, id, cb) { - var refreshHandler = function(err, token) { + var sameToken = function (authToken, id, cb) { + var refreshHandler = function (err, token) { if (!err) { tokensCache[authToken] = tokensCache[token]; } @@ -355,6 +345,7 @@ function auth () { if (!tokensCache[data.authToken]) { // The token is not in the cache askProfileOrRefresh(data, refreshHandler); + return; } else if (tokensCache[data.authToken].expire - Date.now() <= 5000) { // The token is in the cache but it is expired // Drop the old userinfo data to avoid a memory leak @@ -370,11 +361,11 @@ function auth () { } }); }; - - var getCache = function() { + + var getCache = function () { return tokensCache; }; - + return { headerAuthentication: headerAuthentication, checkOrganizations: checkOrganizations, @@ -382,6 +373,7 @@ function auth () { FIWARE_STRATEGY: FIWARE_STRATEGY, getCache: getCache }; -} + +}; -exports.auth = auth; +exports.auth = auth; \ No newline at end of file