I'm little frustrated because I don't know how well I can refactor this script. I wrote the authentication function but it's too complicated, maybe too large in one function, and seems like spaghetti code. How will I be able to make this a little better?
I'm using Restify framework for NodeJS. There are a function that checks if a user is logged. There is a session hash (pnp_access_token
) that I need check with another webservice, but I don't need check all times, only the first, so I'm using a cache. I'm using Redis to set a cache and only check the first time.
I don't want refactor business rules. What can be done about this?
"use strict";
var errorResponse = require('../errorResponse'),
paynopain = require('../../core/paynopain'),
User = require('../../core/User'),
cache = require('../../core/cache/cache'),
validateValues = require('../validateValues'),
API_PATH = 'v1/';
function authenticate(req, res, next) {
if (req.url.indexOf(API_PATH) == 0){
var pnpUserId;
var validated = validateValues(req, ['pnp_access_token']);
if(validated.error){
return next(validated.error);
}
var pnpAccessToken = req.params.pnp_access_token;
cache.read('pnpToken:' + pnpAccessToken)
.then(function(userId){
if(userId){
storeUserIdInRequest(req, next, userId);
}else{
var user = new User(req.logger);
return paynopain.getIdFromAccessToken(pnpAccessToken)
.then(function(pnpUserIdResult){
pnpUserId = pnpUserIdResult;
return user.findByPnpID(pnpUserIdResult);
})
.then(function(userData){
if(userData._id){
return storeUserIdInRequest(req, next, userData._id.toString());
}else{
var newUser = {
pnpId: pnpUserId,
radius: 1000
};
return user.create(newUser)
.then(function(userData){
return storeUserIdInRequest(req, next, userData._id);
});
}
});
}
})
.fail(function(e){
if(e.message === 'invalid_grant'){
next(errorResponse.unauthorized());
}else{
req.logger.log('error', 'Error authenticating', {
error: {
message: e.message,
stack: e.stack
}
});
next(errorResponse.internalError());
}
});
}else{
next();
}
}
function storeUserIdInRequest(req, next, userId){
var oneHourInSeconds = 60 * 60;
cache.write('pnpToken:' + req.params.pnp_access_token, userId, {
expire: oneHourInSeconds
})
.then(function(){
req.userId = userId;
req.logger.setExtra({
userId: userId
});
next();
});
}
function init(server){
server.use(authenticate);
require('./configuration/routes')(API_PATH, server);
require('./products/routes')(API_PATH, server);
require('./tracking/routes')(API_PATH, server);
require('./lists/routes')(API_PATH, server);
}
module.exports = init;