openhim-core
Version:
The OpenHIM core application that provides logging and routing of http requests
274 lines (255 loc) • 9.22 kB
JavaScript
var AutoRetry, Channel, Channels, Q, Task, Transaction, areTransactionChannelsValid, authorisation, buildFilteredTransactionsArray, isRerunPermissionsValid, logger, utils;
Task = require('../model/tasks').Task;
Transaction = require('../model/transactions').Transaction;
AutoRetry = require('../model/autoRetry').AutoRetry;
Channels = require('../model/channels');
Channel = Channels.Channel;
Q = require('q');
logger = require('winston');
authorisation = require('./authorisation');
utils = require('../utils');
isRerunPermissionsValid = function(user, transactions, callback) {
if (authorisation.inGroup("admin", user) === true) {
return callback(null, true);
} else {
return Transaction.distinct("channelID", {
_id: {
$in: transactions.tids
}
}, function(err, transChannels) {
return Channel.distinct("_id", {
txRerunAcl: {
$in: user.groups
}
}, function(err, allowedChannels) {
var chan, j, k, len, len1, matchFound, trx;
for (j = 0, len = transChannels.length; j < len; j++) {
trx = transChannels[j];
matchFound = false;
for (k = 0, len1 = allowedChannels.length; k < len1; k++) {
chan = allowedChannels[k];
if (trx.equals(chan)) {
matchFound = true;
}
}
if (!matchFound) {
return callback(null, false);
}
}
return callback(null, true);
});
});
}
};
exports.getTasks = function*() {
var err, error, filterLimit, filterPage, filterSkip, filters, filtersObject, projectionFiltersObject;
if (!authorisation.inGroup('admin', this.authenticated)) {
utils.logAndSetResponse(this, 403, "User " + this.authenticated.email + " is not an admin, API access to getTasks denied.", 'info');
return;
}
try {
filtersObject = this.request.query;
filterLimit = filtersObject.filterLimit;
filterPage = filtersObject.filterPage;
filterSkip = filterPage * filterLimit;
filters = JSON.parse(filtersObject.filters);
if (filters['created']) {
filters['created'] = JSON.parse(filters['created']);
}
projectionFiltersObject = {
'transactions': 0
};
this.body = (yield Task.find({}).exec());
return this.body = (yield Task.find(filters, projectionFiltersObject).skip(filterSkip).limit(parseInt(filterLimit)).sort({
'created': -1
}).exec());
} catch (error) {
err = error;
return utils.logAndSetResponse(this, 500, "Could not fetch all tasks via the API: " + err, 'error');
}
};
areTransactionChannelsValid = function(transactions, callback) {
return Transaction.distinct("channelID", {
_id: {
$in: transactions.tids
}
}, function(err, trxChannelIDs) {
if (err) {
return callback(err);
}
return Channel.find({
_id: {
$in: trxChannelIDs
}
}, {
status: 1
}, function(err, trxChannels) {
var chan, j, len;
if (err) {
return callback(err);
}
for (j = 0, len = trxChannels.length; j < len; j++) {
chan = trxChannels[j];
if (!Channels.isChannelEnabled(chan)) {
return callback(null, false);
}
}
return callback(null, true);
});
});
};
exports.addTask = function*() {
var allowRerunTaskCreation, areTrxChannelsValid, err, error, isRerunPermsValid, j, len, ref, result, task, taskObject, tid, transactions, transactionsArr, trxChannelsValid;
transactions = this.request.body;
try {
taskObject = {};
transactionsArr = [];
taskObject.remainingTransactions = transactions.tids.length;
taskObject.user = this.authenticated.email;
if (transactions.batchSize != null) {
if (transactions.batchSize <= 0) {
return utils.logAndSetResponse(this, 400, 'Invalid batch size specified', 'info');
}
taskObject.batchSize = transactions.batchSize;
}
if (transactions.paused) {
taskObject.status = 'Paused';
}
isRerunPermsValid = Q.denodeify(isRerunPermissionsValid);
allowRerunTaskCreation = (yield isRerunPermsValid(this.authenticated, transactions));
if (allowRerunTaskCreation === true) {
areTrxChannelsValid = Q.denodeify(areTransactionChannelsValid);
trxChannelsValid = (yield areTrxChannelsValid(transactions));
if (!trxChannelsValid) {
utils.logAndSetResponse(this, 400, 'Cannot queue task as there are transactions with disabled or deleted channels', 'info');
return;
}
ref = transactions.tids;
for (j = 0, len = ref.length; j < len; j++) {
tid = ref[j];
transactionsArr.push({
tid: tid
});
}
taskObject.transactions = transactionsArr;
taskObject.totalTransactions = transactionsArr.length;
task = new Task(taskObject);
result = (yield Q.ninvoke(task, 'save'));
utils.logAndSetResponse(this, 201, "User " + this.authenticated.email + " created task with id " + task.id, 'info');
return AutoRetry.remove({
transactionID: {
$in: transactions.tids
}
}, function(err) {
if (err) {
return logger.err(err);
}
});
} else {
return utils.logAndSetResponse(this, 403, "Insufficient permissions prevents this rerun task from being created", 'error');
}
} catch (error) {
err = error;
return utils.logAndSetResponse(this, 500, "Could not add Task via the API: " + err, 'error');
}
};
buildFilteredTransactionsArray = function(filters, transactions) {
var filtersFailed, i, tempTransactions;
tempTransactions = [];
i = 0;
while (i < transactions.length) {
filtersFailed = false;
if (filters.tstatus) {
if (filters.tstatus !== transactions[i].tstatus) {
filtersFailed = true;
}
}
if (filters.rerunStatus) {
if (filters.rerunStatus !== transactions[i].rerunStatus) {
filtersFailed = true;
}
}
if (filters.hasErrors) {
if (filters.hasErrors === 'yes' && !transactions[i].hasErrors) {
filtersFailed = true;
} else if (filters.hasErrors === 'no' && transactions[i].hasErrors) {
filtersFailed = true;
}
}
if (filtersFailed === false) {
tempTransactions.push(transactions[i]);
}
i++;
}
return tempTransactions;
};
exports.getTask = function*(taskId) {
var err, error, filterLimit, filterPage, filterSkip, filters, filtersObject, result, sliceFrom, sliceTo, tempTransactions, totalFilteredTransactions;
taskId = unescape(taskId);
try {
filtersObject = this.request.query;
filterLimit = filtersObject.filterLimit;
filterPage = filtersObject.filterPage;
filterSkip = filterPage * filterLimit;
filters = JSON.parse(filtersObject.filters);
result = (yield Task.findById(taskId).lean().exec());
tempTransactions = result.transactions;
if (Object.keys(filters).length > 0) {
tempTransactions = buildFilteredTransactionsArray(filters, result.transactions);
}
totalFilteredTransactions = tempTransactions.length;
result.totalFilteredTransactions = totalFilteredTransactions;
sliceFrom = filterSkip;
sliceTo = filterSkip + parseInt(filterLimit);
result.transactions = tempTransactions.slice(sliceFrom, sliceTo);
if (result === null) {
return utils.logAndSetResponse(this, 404, "We could not find a Task with this ID: " + taskId + ".", 'info');
} else {
return this.body = result;
}
} catch (error) {
err = error;
return utils.logAndSetResponse(this, 500, "Could not fetch Task by ID {taskId} via the API: " + err, 'error');
}
};
exports.updateTask = function*(taskId) {
var err, error, taskData;
if (!authorisation.inGroup('admin', this.authenticated)) {
utils.logAndSetResponse(this, 403, "User " + this.authenticated.email + " is not an admin, API access to updateTask denied.", 'info');
return;
}
taskId = unescape(taskId);
taskData = this.request.body;
if (taskData._id != null) {
delete taskData._id;
}
try {
(yield Task.findOneAndUpdate({
_id: taskId
}, taskData).exec());
this.body = 'The Task was successfully updated';
return logger.info("User " + this.authenticated.email + " updated task with id " + taskId);
} catch (error) {
err = error;
return utils.logAndSetResponse(this, 500, "Could not update Task by ID {taskId} via the API: " + err, 'error');
}
};
exports.removeTask = function*(taskId) {
var err, error;
if (!authorisation.inGroup('admin', this.authenticated)) {
utils.logAndSetResponse(this, 403, "User " + this.authenticated.email + " is not an admin, API access to removeTask denied.", 'info');
return;
}
taskId = unescape(taskId);
try {
(yield Task.remove({
_id: taskId
}).exec());
this.body = 'The Task was successfully deleted';
return logger.info("User " + this.authenticated.email + " removed task with id " + taskId);
} catch (error) {
err = error;
return utils.logAndSetResponse(this, 500, "Could not remove Task by ID {taskId} via the API: " + err, 'error');
}
};
//# sourceMappingURL=tasks.js.map