webapi-eca/js-coffee/request_handler.js
2013-11-29 18:41:55 +01:00

373 lines
9.3 KiB
JavaScript

// Generated by CoffeeScript 1.6.3
/*
Request Handler
============
> TODO Add documentation
*/
(function() {
var crypto, db, exports, fAdminCommands, fs, getHandlerFileAsString, getHandlerPath, log, mm, mustache, objAdminCmds, objUserCmds, onAdminCommand, path, qs, renderPage, sendLoginOrPage,
_this = this;
log = require('./logging');
db = require('./db_interface');
mm = require('./module_manager');
fs = require('fs');
path = require('path');
qs = require('querystring');
mustache = require('mustache');
crypto = require('crypto-js');
objAdminCmds = {
'loadrules': mm.loadRulesFromFS,
'loadaction': mm.loadActionModuleFromFS,
'loadactions': mm.loadActionModulesFromFS,
'loadevent': mm.loadEventModuleFromFS,
'loadevents': mm.loadEventModulesFromFS
};
objUserCmds = {
'store_action': mm.storeActionModule,
'store_event': mm.storeEventModule,
'store_rule': mm.storeRule
};
exports = module.exports = function(args) {
var user, users, _i, _len;
args = args != null ? args : {};
log(args);
db(args);
mm(args);
mm.addDBLink(db);
users = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'config', 'users.json')));
for (_i = 0, _len = users.length; _i < _len; _i++) {
user = users[_i];
db.storeUser(user);
}
return module.exports;
};
/*
This allows the parent to add handlers. The event handler will receive
the events that were received. The shutdown function will be called if the
admin command shutdown is issued.
@public addHandlers( *fShutdown* )
@param {function} fShutdown
*/
exports.addHandlers = function(fShutdown) {
return objAdminCmds.shutdown = fShutdown;
};
/*
Handles possible events that were posted to this server and pushes them into the
event queue.
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public handleEvent( *req, resp* )
*/
exports.handleEvent = function(req, resp) {
var body;
body = '';
req.on('data', function(data) {
return body += data;
});
return req.on('end', function() {
var obj;
obj = qs.parse(body);
if (obj && obj.event && obj.eventid) {
resp.send('Thank you for the event: ' + obj.event + ' (' + obj.eventid + ')!');
return db.pushEvent(obj);
} else {
resp.writeHead(400, {
"Content-Type": "text/plain"
});
return resp.send('Your event was missing important parameters!');
}
});
};
/*
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public handleLogin( *req, resp* )
*/
exports.handleLogin = function(req, resp) {
var body;
body = '';
req.on('data', function(data) {
return body += data;
});
return req.on('end', function() {
var obj;
if (!req.session || !req.session.user) {
obj = qs.parse(body);
return db.loginUser(obj.username, obj.password, function(err, usr) {
if (err) {
log.print('RH', ("AUTH-UH-OH (" + obj.username + "): ") + err.message);
} else {
req.session.user = usr;
}
if (req.session.user) {
return resp.send('OK!');
} else {
return resp.send(401, 'NO!');
}
});
} else {
return resp.send('Welcome ' + req.session.user.name + '!');
}
});
};
/*
A post request retrieved on this handler causes the user object to be
purged from the session, thus the user will be logged out.
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public handleLogout( *req, resp* )
*/
exports.handleLogout = function(req, resp) {
if (req.session) {
req.session.user = null;
return resp.send('Bye!');
}
};
/*
Resolves the path to a handler webpage.
@private getHandlerPath( *name* )
@param {String} name
*/
getHandlerPath = function(name) {
return path.resolve(__dirname, '..', 'webpages', 'handlers', name + '.html');
};
/*
Resolves the path to a handler webpage and returns it as a string.
@private getHandlerFileAsString( *name* )
@param {String} name
*/
getHandlerFileAsString = function(name) {
return fs.readFileSync(getHandlerPath(name), 'utf8');
};
/*
Renders a page depending on the user session and returns it.
@private renderPage( *name, sess* )
@param {String} name
@param {Object} sess
*/
renderPage = function(name, sess) {
var menubar, template, view;
template = getHandlerFileAsString(name);
menubar = getHandlerFileAsString('menubar');
view = {
user: sess.user,
div_menubar: menubar
};
return mustache.render(template, view);
};
/*
Sends the desired page or the login to the user.
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public renderPageOrLogin( *req, resp, pagename* )
@param {String} pagename
*/
sendLoginOrPage = function(pagename, req, resp) {
if (req.session && req.session.user) {
return resp.send(renderPage(pagename, req.session));
} else {
return resp.sendfile(getHandlerPath('login'));
}
};
/*
Handles the user command requests.
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public handleUser( *req, resp* )
*/
exports.handleUserCommand = function(req, resp) {
var body;
if (!req.session || !req.session.user) {
return resp.send(401, 'Login first!');
} else {
body = '';
req.on('data', function(data) {
return body += data;
});
return req.on('end', function() {
var obj;
obj = qs.parse(body);
if (objUserCmds[obj.command] === 'function') {
resp.send('Command accepted!');
return objUserCmds[obj.command](req.session.user, obj);
} else {
return resp.send(404, 'Command unknown!');
}
});
}
};
/*
Present the module forge to the user.
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public handleForgeModules( *req, resp* )
*/
exports.handleForgeModules = function(req, resp) {
return sendLoginOrPage('forge_modules', req, resp);
};
/*
Present the event invoke page to the user.
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public handleInvokeEvent( *req, resp* )
*/
exports.handleInvokeEvent = function(req, resp) {
return sendLoginOrPage('push_event', req, resp);
};
/*
Handles the admin command requests.
*Requires
the [request](http://nodejs.org/api/http.html#http_class_http_clientrequest)
and [response](http://nodejs.org/api/http.html#http_class_http_serverresponse)
objects.*
@public handleAdmin( *req, resp* )
*/
exports.handleAdmin = function(req, resp) {
if (req.session && req.session.user) {
if (req.session.user.isAdmin === "true") {
return resp.send(renderPage('welcome', req.session));
} else {
return resp.send(renderPage('unauthorized', req.session));
}
} else {
return resp.sendfile(getHandlerPath('login'));
}
};
onAdminCommand = function(req, response) {
var q;
q = req.query;
log.print('RH', 'Received admin request: ' + q);
if (q.cmd) {
return fAdminCommands(q, answerHandler(response));
} else {
return answerError(response, 'I\'m not sure about what you want from me...');
}
};
/*
admin commands handler receives all command arguments and an answerHandler
object that eases response handling to the HTTP request issuer.
@private fAdminCommands( *args, answHandler* )
*/
fAdminCommands = function(args, answHandler) {
var fAnsw, _name;
if (args && args.cmd) {
if (typeof adminCmds[_name = args.cmd] === "function") {
adminCmds[_name](args, answHandler);
}
} else {
log.print('RH', 'No command in request');
}
/*
The fAnsw function receives an answerHandler object as an argument when called
and returns an anonymous function
*/
fAnsw = function(ah) {
/*
The anonymous function checks whether the answerHandler was already used to
issue an answer, if no answer was provided we answer with an error message
*/
return function() {
if (!ah.isAnswered()) {
return ah.answerError('Not handled...');
}
};
};
/*
Delayed function call of the anonymous function that checks the answer handler
*/
return setTimeout(fAnsw(answHandler), 2000);
};
}).call(this);