Skip to content

Commit

Permalink
Fix issues with auth tests
Browse files Browse the repository at this point in the history
  • Loading branch information
fdelavega committed Mar 1, 2019
1 parent b094685 commit 7e1c7c2
Showing 1 changed file with 103 additions and 111 deletions.
214 changes: 103 additions & 111 deletions lib/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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 = {};
Expand All @@ -108,15 +105,15 @@ 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();
}
}
};

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');
Expand All @@ -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);
Expand All @@ -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();
Expand All @@ -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) {
Expand All @@ -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([
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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];
}
Expand All @@ -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
Expand All @@ -370,18 +361,19 @@ function auth () {
}
});
};

var getCache = function() {
var getCache = function () {
return tokensCache;
};

return {
headerAuthentication: headerAuthentication,
checkOrganizations: checkOrganizations,
setPartyObj: setPartyObj,
FIWARE_STRATEGY: FIWARE_STRATEGY,
getCache: getCache
};
}

};

exports.auth = auth;
exports.auth = auth;

0 comments on commit 7e1c7c2

Please sign in to comment.