From 0e087b6c429e1f2cc15ecc63b43754cb63032fc5 Mon Sep 17 00:00:00 2001 From: Dominic Date: Wed, 19 Mar 2014 23:28:59 +0100 Subject: [PATCH] persistence interface errors almost fixed, FLUSHALL on DB and then run unit tests again --- coffee/config.coffee | 12 +- coffee/persistence.coffee | 4 +- coffee/webapi-eca.coffee | 7 + config/config.json | 11 +- js-coffee/components-manager.js | 291 ++--- js-coffee/config.js | 123 +- js-coffee/dynamic-modules.js | 87 +- js-coffee/http-listener.js | 115 +- js-coffee/logging.js | 101 +- js-coffee/persistence.js | 1182 ++++++++++-------- js-coffee/request-handler.js | 231 ++-- js-coffee/webapi-eca.js | 195 +-- testing/test_config.coffee | 2 +- testing/test_persistence.coffee | 30 +- webpages/handlers/js/admin.js | 2 +- webpages/handlers/js/error.js | 2 +- webpages/handlers/js/forge_action_invoker.js | 2 +- webpages/handlers/js/forge_event.js | 2 +- webpages/handlers/js/forge_event_poller.js | 2 +- webpages/handlers/js/forge_rule.js | 2 +- webpages/handlers/js/login.js | 2 +- 21 files changed, 1289 insertions(+), 1116 deletions(-) diff --git a/coffee/config.coffee b/coffee/config.coffee index 1a014d8..f6c0b0f 100644 --- a/coffee/config.coffee +++ b/coffee/config.coffee @@ -50,13 +50,13 @@ loadConfigFile = ( configPath ) => #TODO Try to get rid of crypto key try @config = JSON.parse fs.readFileSync path.resolve __dirname, '..', configPath - isReady = true + @isReady = true for prop in confProperties if !@config[prop] - isReady = false - if not isReady and not @nolog - console.error """Missing property in config file, requires: - - #{ confProperties.join "\n -" }""" + @isReady = false + if not @isReady and not @nolog + console.error "Missing property in config file, requires:\n" + + " - #{ confProperties.join "\n - " }" catch e if not @nolog console.error "Failed loading config file: #{ e.message }" @@ -75,7 +75,7 @@ fetchProp = ( prop ) => @config?[prop] @public isReady() ### -exports.isReady = => @config? +exports.isReady = => @isReady ### ***Returns*** the HTTP port diff --git a/coffee/persistence.coffee b/coffee/persistence.coffee index 847232d..86f06af 100644 --- a/coffee/persistence.coffee +++ b/coffee/persistence.coffee @@ -231,7 +231,9 @@ class IndexedModules @log.info "DB | storeModule(#{ @setname }): #{ mId }" @db.sadd "#{ @setname }s", mId, replyHandler "Storing '#{ @setname }' key '#{ mId }'" - @db.hmset "#{ @setname }:#{ mId }", data, + @db.hmset "#{ @setname }:#{ mId }", 'code', data['code'], + replyHandler "Storing '#{ @setname }:#{ mId }'" + @db.hmset "#{ @setname }:#{ mId }", 'reqparams', data['reqparams'], replyHandler "Storing '#{ @setname }:#{ mId }'" #TODO add testing diff --git a/coffee/webapi-eca.coffee b/coffee/webapi-eca.coffee index d322652..3be47dd 100644 --- a/coffee/webapi-eca.coffee +++ b/coffee/webapi-eca.coffee @@ -106,6 +106,7 @@ init = => process.exit() logconf = conf.getLogConf() + if argv.m logconf[ 'mode' ] = argv.m if argv.i @@ -145,11 +146,17 @@ init = => # Start the event poller. The module manager will emit events for it @log.info 'RS | Forking a child process for the event poller' + # Grab all required log config fields cliArgs = [ + # the log mode: [development|productive] args.logconf['mode'] + # the I/O log level, refer to logging.coffee for the different levels args.logconf['io-level'] + # the file log level, refer to logging.coffee for the different levels args.logconf['file-level'] + # the optional path to the log file args.logconf['file-path'] + # whether a log file shall be written at all: null else args.logconf['nolog'] ] poller = cp.fork path.resolve( __dirname, nameEP ), cliArgs diff --git a/config/config.json b/config/config.json index c1cdb90..d59d64f 100644 --- a/config/config.json +++ b/config/config.json @@ -1,6 +1,9 @@ { - "http_port": 8125, - "db_port": 6379, - "crypto_key": "[choose_a_safe_cypto_key(max_256_bit)]", - "session_secret": "[choose_a_safe_session_key]" + "http-port": 8125, + "db-port": 6379, + "log": { + "mode": "development", + "io-level": "info", + "file-level": "info" + } } \ No newline at end of file diff --git a/js-coffee/components-manager.js b/js-coffee/components-manager.js index 7f02cbd..043af28 100644 --- a/js-coffee/components-manager.js +++ b/js-coffee/components-manager.js @@ -1,4 +1,5 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 + /* Components Manager @@ -6,12 +7,10 @@ Components Manager > The components manager takes care of the dynamic JS modules and the rules. > Event Poller and Action Invoker modules are loaded as strings and stored in the database, > then compiled into node modules and rules and used in the engine and event poller. -*/ - + */ (function() { - var commandFunctions, db, dynmod, events, exports, fs, path, vm, - _this = this; + var commandFunctions, db, dynmod, events, exports, fs, path, vm; db = require('./persistence'); @@ -25,86 +24,94 @@ Components Manager events = require('events'); + /* Module call ----------- Initializes the HTTP listener and its request handler. @param {Object} args - */ + */ + exports = module.exports = (function(_this) { + return function(args) { + _this.log = args.logger; + _this.ee = new events.EventEmitter(); + db(args); + dynmod(args); + return module.exports; + }; + })(this); - exports = module.exports = function(args) { - _this.log = args.logger; - _this.ee = new events.EventEmitter(); - db(args); - dynmod(args); - return module.exports; - }; - - exports.addListener = function(evt, eh) { - _this.ee.addListener(evt, eh); - return db.getRules(function(err, obj) { - var id, rule, _results; - _results = []; - for (id in obj) { - rule = obj[id]; - _results.push(_this.ee.emit('init', rule)); - } - return _results; - }); - }; - - exports.processRequest = function(user, obj, cb) { - var answ; - if (commandFunctions[obj.command]) { - return answ = commandFunctions[obj.command](user, obj, cb); - } else { - return cb({ - code: 404, - message: 'Strange request!' + exports.addListener = (function(_this) { + return function(evt, eh) { + _this.ee.addListener(evt, eh); + return db.getRules(function(err, obj) { + var id, rule, _results; + _results = []; + for (id in obj) { + rule = obj[id]; + _results.push(_this.ee.emit('init', rule)); + } + return _results; }); - } - }; + }; + })(this); + + exports.processRequest = (function(_this) { + return function(user, obj, cb) { + var answ; + if (commandFunctions[obj.command]) { + return answ = commandFunctions[obj.command](user, obj, cb); + } else { + return cb({ + code: 404, + message: 'Strange request!' + }); + } + }; + })(this); commandFunctions = { - forge_event_poller: function(user, obj, cb) { - var answ; - answ = { - code: 200 - }; - return db.getEventPoller(obj.id, function(err, mod) { - var cm, id, name, src, _ref; - if (mod) { - answ.code = 409; - answ.message = 'Event Poller module name already existing: ' + obj.id; - } else { - src = obj.data; - cm = dynmod.compileString(src, obj.id, {}, obj.lang); - answ = cm.answ; - if (answ.code === 200) { - events = []; - _ref = cm.module; - for (name in _ref) { - id = _ref[name]; - events.push(name); - } - _this.log.info("CM | Storing new eventpoller with events " + events); - answ.message = "Event Poller module successfully stored! Found following event(s): " + events; - db.storeEventPoller(obj.id, user.username, { - code: obj.data, - lang: obj.lang, - params: obj.params, - events: events - }); - if (obj["public"] === 'true') { - db.publishEventPoller(obj.id); + forge_event_poller: (function(_this) { + return function(user, obj, cb) { + var answ; + answ = { + code: 200 + }; + return db.getEventPoller(obj.id, function(err, mod) { + var cm, id, name, src, _ref; + if (mod) { + answ.code = 409; + answ.message = 'Event Poller module name already existing: ' + obj.id; + } else { + src = obj.data; + cm = dynmod.compileString(src, obj.id, {}, obj.lang); + answ = cm.answ; + if (answ.code === 200) { + events = []; + _ref = cm.module; + for (name in _ref) { + id = _ref[name]; + events.push(name); + } + _this.log.info("CM | Storing new eventpoller with events " + events); + answ.message = "Event Poller module successfully stored! Found following event(s): " + events; + db.storeEventPoller(obj.id, user.username, { + code: obj.data, + lang: obj.lang, + params: obj.params, + events: events + }); + if (obj["public"] === 'true') { + db.publishEventPoller(obj.id); + } } } - } - return cb(answ); - }); - }, + return cb(answ); + }); + }; + })(this), get_event_pollers: function(user, obj, cb) { return db.getAvailableEventPollerIds(user.username, function(err, obj) { var fGetEvents, id, oRes, sem, _i, _len, _results; @@ -169,80 +176,84 @@ Components Manager }); }); }, - forge_action_invoker: function(user, obj, cb) { - var answ; - answ = { - code: 200 - }; - return db.getActionInvoker(obj.id, function(err, mod) { - var actions, cm, id, name, src, _ref; - if (mod) { - answ.code = 409; - answ.message = 'Action Invoker module name already existing: ' + obj.id; - } else { - src = obj.data; - cm = dynmod.compileString(src, obj.id, {}, obj.lang); - answ = cm.answ; - if (answ.code === 200) { - actions = []; - _ref = cm.module; - for (name in _ref) { - id = _ref[name]; - actions.push(name); - } - _this.log.info("CM | Storing new eventpoller with actions " + actions); - answ.message = "Action Invoker module successfully stored! Found following action(s): " + actions; - db.storeActionInvoker(obj.id, user.username, { - code: obj.data, - lang: obj.lang, - params: obj.params, - actions: actions - }); - if (obj["public"] === 'true') { - db.publishActionInvoker(obj.id); + forge_action_invoker: (function(_this) { + return function(user, obj, cb) { + var answ; + answ = { + code: 200 + }; + return db.getActionInvoker(obj.id, function(err, mod) { + var actions, cm, id, name, src, _ref; + if (mod) { + answ.code = 409; + answ.message = 'Action Invoker module name already existing: ' + obj.id; + } else { + src = obj.data; + cm = dynmod.compileString(src, obj.id, {}, obj.lang); + answ = cm.answ; + if (answ.code === 200) { + actions = []; + _ref = cm.module; + for (name in _ref) { + id = _ref[name]; + actions.push(name); + } + _this.log.info("CM | Storing new eventpoller with actions " + actions); + answ.message = "Action Invoker module successfully stored! Found following action(s): " + actions; + db.storeActionInvoker(obj.id, user.username, { + code: obj.data, + lang: obj.lang, + params: obj.params, + actions: actions + }); + if (obj["public"] === 'true') { + db.publishActionInvoker(obj.id); + } } } - } - return cb(answ); - }); - }, + return cb(answ); + }); + }; + })(this), get_rules: function(user, obj, cb) { return console.log('CM | Implement get_rules'); }, - forge_rule: function(user, obj, cb) { - obj.event = JSON.parse(obj.event); - return db.getRule(obj.id, function(err, objRule) { - var answ, id, modules, params, rule; - if (objRule !== null) { - answ = { - code: 409, - message: 'Rule name already existing!' - }; - } else { - answ = { - code: 200, - message: 'Rule stored and activated!' - }; - rule = { - id: obj.id, - event: "" + obj.event.module + " -> " + obj.event["function"], - conditions: JSON.parse(obj.conditions), - actions: JSON.parse(obj.actions) - }; - modules = JSON.parse(obj.action_params); - db.storeRule(rule.id, JSON.stringify(rule)); - db.linkRule(rule.id, user.username); - db.activateRule(rule.id, user.username); - db.storeEventUserParams(obj.event.module, user.username, obj.event_params); - for (id in modules) { - params = modules[id]; - db.storeActionUserParams(id, user.username, JSON.stringify(params)); + forge_rule: (function(_this) { + return function(user, obj, cb) { + obj.event = JSON.parse(obj.event); + return db.getRule(obj.id, function(err, objRule) { + var answ, id, modules, params, rule; + if (objRule !== null) { + answ = { + code: 409, + message: 'Rule name already existing!' + }; + } else { + answ = { + code: 200, + message: 'Rule stored and activated!' + }; + rule = { + id: obj.id, + event: "" + obj.event.module + " -> " + obj.event["function"], + conditions: JSON.parse(obj.conditions), + actions: JSON.parse(obj.actions) + }; + modules = JSON.parse(obj.action_params); + db.storeRule(rule.id, JSON.stringify(rule)); + db.linkRule(rule.id, user.username); + db.activateRule(rule.id, user.username); + db.storeEventUserParams(obj.event.module, user.username, obj.event_params); + for (id in modules) { + params = modules[id]; + db.storeActionUserParams(id, user.username, JSON.stringify(params)); + } + _this.ee.emit('newRule', JSON.stringify(rule)); } - _this.ee.emit('newRule', JSON.stringify(rule)); - } - return cb(answ); - }); - } + return cb(answ); + }); + }; + })(this) }; }).call(this); diff --git a/js-coffee/config.js b/js-coffee/config.js index de034c7..6e76c45 100644 --- a/js-coffee/config.js +++ b/js-coffee/config.js @@ -1,20 +1,20 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 + /* Configuration ============= > Loads the configuration file and acts as an interface to it. -*/ - + */ (function() { - var exports, fetchProp, fs, loadConfigFile, path, - _this = this; + var exports, fetchProp, fs, loadConfigFile, path; fs = require('fs'); path = require('path'); + /* Module call ----------- @@ -24,21 +24,23 @@ Configuration be generated) and configPath for a custom configuration file path. @param {Object} args - */ + */ + exports = module.exports = (function(_this) { + return function(args) { + args = args != null ? args : {}; + if (args.nolog) { + _this.nolog = true; + } + if (args.configPath) { + loadConfigFile(args.configPath); + } else { + loadConfigFile(path.join('config', 'config.json')); + } + return module.exports; + }; + })(this); - exports = module.exports = function(args) { - args = args != null ? args : {}; - if (args.nolog) { - _this.nolog = true; - } - if (args.configPath) { - loadConfigFile(args.configPath); - } else { - loadConfigFile(path.join('config', 'config.json')); - } - return module.exports; - }; /* Tries to load a configuration file from the path relative to this module's parent folder. @@ -46,96 +48,101 @@ Configuration @private loadConfigFile @param {String} configPath - */ + */ - - loadConfigFile = function(configPath) { - var confProperties, e, isReady, prop, _i, _len; - _this.config = null; - confProperties = ['log', 'http-port', 'db-port']; - try { - _this.config = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', configPath))); - isReady = true; - for (_i = 0, _len = confProperties.length; _i < _len; _i++) { - prop = confProperties[_i]; - if (!_this.config[prop]) { - isReady = false; + loadConfigFile = (function(_this) { + return function(configPath) { + var confProperties, e, prop, _i, _len; + _this.config = null; + confProperties = ['log', 'http-port', 'db-port']; + try { + _this.config = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', configPath))); + _this.isReady = true; + for (_i = 0, _len = confProperties.length; _i < _len; _i++) { + prop = confProperties[_i]; + if (!_this.config[prop]) { + _this.isReady = false; + } + } + if (!_this.isReady && !_this.nolog) { + return console.error("Missing property in config file, requires:\n" + (" - " + (confProperties.join("\n - ")))); + } + } catch (_error) { + e = _error; + if (!_this.nolog) { + return console.error("Failed loading config file: " + e.message); } } - if (!isReady && !_this.nolog) { - return console.error("Missing property in config file, requires: \n- " + (confProperties.join("\n -"))); - } - } catch (_error) { - e = _error; - if (!_this.nolog) { - return console.error("Failed loading config file: " + e.message); - } - } - }; + }; + })(this); + /* Fetch a property from the configuration @private fetchProp( *prop* ) @param {String} prop - */ + */ + fetchProp = (function(_this) { + return function(prop) { + var _ref; + return (_ref = _this.config) != null ? _ref[prop] : void 0; + }; + })(this); - fetchProp = function(prop) { - var _ref; - return (_ref = _this.config) != null ? _ref[prop] : void 0; - }; /* ***Returns*** true if the config file is ready, else false @public isReady() - */ + */ + exports.isReady = (function(_this) { + return function() { + return _this.isReady; + }; + })(this); - exports.isReady = function() { - return _this.config != null; - }; /* ***Returns*** the HTTP port @public getHttpPort() - */ - + */ exports.getHttpPort = function() { return fetchProp('http-port'); }; + /* ***Returns*** the DB port* @public getDBPort() - */ - + */ exports.getDbPort = function() { return fetchProp('db-port'); }; + /* ***Returns*** the log conf object @public getLogConf() - */ - + */ exports.getLogConf = function() { return fetchProp('log'); }; + /* ***Returns*** the crypto key @public getCryptoKey() - */ - + */ exports.getCryptoKey = function() { return fetchProp('crypto-key'); diff --git a/js-coffee/dynamic-modules.js b/js-coffee/dynamic-modules.js index 27876fc..a826e61 100644 --- a/js-coffee/dynamic-modules.js +++ b/js-coffee/dynamic-modules.js @@ -1,16 +1,15 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 + /* Dynamic Modules =============== > Compiles CoffeeScript modules and loads JS modules in a VM, together > with only a few allowed node.js modules. -*/ - + */ (function() { - var cs, exports, needle, vm, - _this = this; + var cs, exports, needle, vm; vm = require('vm'); @@ -18,19 +17,22 @@ Dynamic Modules cs = require('coffee-script'); + /* Module call ----------- Initializes the dynamic module handler. @param {Object} args - */ + */ + exports = module.exports = (function(_this) { + return function(args) { + _this.log = args.logger; + return module.exports; + }; + })(this); - exports = module.exports = function(args) { - _this.log = args.logger; - return module.exports; - }; /* Try to run a JS module from a string, together with the @@ -42,44 +44,45 @@ Dynamic Modules @param {String} id @param {Object} params @param {String} lang - */ + */ - - exports.compileString = function(src, id, params, lang) { - var answ, err, ret, sandbox; - answ = { - code: 200, - message: 'Successfully compiled' - }; - if (lang === '0') { + exports.compileString = (function(_this) { + return function(src, id, params, lang) { + var answ, err, ret, sandbox; + answ = { + code: 200, + message: 'Successfully compiled' + }; + if (lang === '0') { + try { + src = cs.compile(src); + } catch (_error) { + err = _error; + answ.code = 400; + answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line; + } + } + sandbox = { + id: id, + params: params, + needle: needle, + log: console.log, + exports: {} + }; try { - src = cs.compile(src); + vm.runInNewContext(src, sandbox, id + '.vm'); } catch (_error) { err = _error; + console.log(err); answ.code = 400; - answ.message = 'Compilation of CoffeeScript failed at line ' + err.location.first_line; + answ.message = 'Loading Module failed: ' + err.message; } - } - sandbox = { - id: id, - params: params, - needle: needle, - log: console.log, - exports: {} + ret = { + answ: answ, + module: sandbox.exports + }; + return ret; }; - try { - vm.runInNewContext(src, sandbox, id + '.vm'); - } catch (_error) { - err = _error; - console.log(err); - answ.code = 400; - answ.message = 'Loading Module failed: ' + err.message; - } - ret = { - answ: answ, - module: sandbox.exports - }; - return ret; - }; + })(this); }).call(this); diff --git a/js-coffee/http-listener.js b/js-coffee/http-listener.js index ba133cc..aa686b2 100644 --- a/js-coffee/http-listener.js +++ b/js-coffee/http-listener.js @@ -1,4 +1,5 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 + /* HTTP Listener @@ -6,12 +7,10 @@ HTTP Listener > Receives the HTTP requests to the server at the given port. The requests > (bound to a method) are then redirected to the appropriate handler which > takes care of the request. -*/ - + */ (function() { - var app, exports, express, initRouting, path, qs, requestHandler, - _this = this; + var app, exports, express, initRouting, path, qs, requestHandler; requestHandler = require('./request-handler'); @@ -23,73 +22,77 @@ HTTP Listener app = express(); + /* Module call ----------- Initializes the HTTP listener and its request handler. @param {Object} args - */ + */ + exports = module.exports = (function(_this) { + return function(args) { + _this.log = args.logger; + _this.shutDownSystem = args['shutdown-function']; + requestHandler(args); + initRouting(args['http-port']); + return module.exports; + }; + })(this); - exports = module.exports = function(args) { - _this.log = args.logger; - _this.shutDownSystem = args['shutdown-function']; - requestHandler(args); - initRouting(args['http-port']); - return module.exports; - }; /* Initializes the request routing and starts listening on the given port. @param {int} port @private initRouting( *fShutDown* ) - */ + */ + initRouting = (function(_this) { + return function(port) { + var server, sess_sec; + app.use(express.cookieParser()); + sess_sec = "149u*y8C:@kmN/520Gt\\v'+KFBnQ!\\r<>5X/xRI`sT 'action-invokers' and then stored in the db with the key 'action-invoker:' + ID > (e.g. action-invoker:probinder). > -*/ - + */ (function() { var IndexedModules, crypto, decrypt, encrypt, exports, getSetRecords, hash, redis, replyHandler, - _this = this, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; crypto = require('crypto-js'); redis = require('redis'); + /* Module call ----------- Initializes the DB connection with the given `db-port` property in the `args` object. @param {Object} args - */ + */ - - exports = module.exports = function(args) { - var _ref; - _this.log = args.logger; - if ((_ref = _this.db) != null) { - _ref.quit(); - } - _this.crypto_key = "}f6y1y}B{.an$}2c$Yl.$mSnF\\HX149u*y8C:@kmN/520Gt\\v'+KFBnQ!\\r<>5X/xRI`sT -1) { - _this.connRefused = true; - return _this.log.error(err, 'DB | Wrong port?'); + exports = module.exports = (function(_this) { + return function(args) { + var _ref; + _this.log = args.logger; + if ((_ref = _this.db) != null) { + _ref.quit(); } - }); - _this.ep = new IndexedModules('event-poller', _this.db, _this.log); - return _this.ai = new IndexedModules('action-invoker', _this.db, _this.log); - }; + _this.crypto_key = "}f6y1y}B{.an$}2c$Yl.$mSnF\\HX149u*y8C:@kmN/520Gt\\v'+KFBnQ!\\r<>5X/xRI`sT -1) { + _this.connRefused = true; + return _this.log.error(err, 'DB | Wrong port?'); + } + }); + _this.ep = new IndexedModules('event-poller', _this.db, _this.log); + return _this.ai = new IndexedModules('action-invoker', _this.db, _this.log); + }; + })(this); + /* Checks whether the db is connected and passes either an error on failure after @@ -64,165 +66,181 @@ Persistence @public isConnected( *cb* ) @param {function} cb - */ + */ - - exports.isConnected = function(cb) { - var fCheckConnection, numAttempts; - if (_this.db.connected) { - return cb(); - } else { - numAttempts = 0; - fCheckConnection = function() { - if (_this.connRefused) { - return cb(new Error('DB | Connection refused! Wrong port?')); - } else { - if (_this.db.connected) { - _this.log.info('DB | Successfully connected to DB!'); - return cb(); - } else if (numAttempts++ < 10) { - return setTimeout(fCheckConnection, 100); + exports.isConnected = (function(_this) { + return function(cb) { + var fCheckConnection, numAttempts; + if (_this.db.connected) { + return cb(); + } else { + numAttempts = 0; + fCheckConnection = function() { + if (_this.connRefused) { + return cb(new Error('DB | Connection refused! Wrong port?')); } else { - return cb(new Error('DB | Connection to DB failed!')); + if (_this.db.connected) { + _this.log.info('DB | Successfully connected to DB!'); + return cb(); + } else if (numAttempts++ < 10) { + return setTimeout(fCheckConnection, 100); + } else { + return cb(new Error('DB | Connection to DB failed!')); + } } - } - }; - return setTimeout(fCheckConnection, 100); - } - }; + }; + return setTimeout(fCheckConnection, 100); + } + }; + })(this); + /* Abstracts logging for simple action replies from the DB. @private replyHandler( *action* ) @param {String} action - */ + */ - - replyHandler = function(action) { - return function(err, reply) { - if (err) { - return _this.log.warn(err, "during '" + action + "'"); - } else { - return _this.log.info("DB | " + action + ": " + reply); - } + replyHandler = (function(_this) { + return function(action) { + return function(err, reply) { + if (err) { + return _this.log.warn(err, "during '" + action + "'"); + } else { + return _this.log.info("DB | " + action + ": " + reply); + } + }; }; - }; + })(this); + /* Push an event into the event queue. @public pushEvent( *oEvent* ) @param {Object} oEvent - */ + */ + exports.pushEvent = (function(_this) { + return function(oEvent) { + if (oEvent) { + _this.log.info("DB | Event pushed into the queue: '" + oEvent.eventid + "'"); + return _this.db.rpush('event_queue', JSON.stringify(oEvent)); + } else { + return _this.log.warn('DB | Why would you give me an empty event...'); + } + }; + })(this); - exports.pushEvent = function(oEvent) { - if (oEvent) { - _this.log.info("DB | Event pushed into the queue: '" + oEvent.eventid + "'"); - return _this.db.rpush('event_queue', JSON.stringify(oEvent)); - } else { - return _this.log.warn('DB | Why would you give me an empty event...'); - } - }; /* Pop an event from the event queue and pass it to cb(err, obj). @public popEvent( *cb* ) @param {function} cb - */ + */ - - exports.popEvent = function(cb) { - var makeObj; - makeObj = function(pcb) { - return function(err, obj) { - return pcb(err, JSON.parse(obj)); + exports.popEvent = (function(_this) { + return function(cb) { + var makeObj; + makeObj = function(pcb) { + return function(err, obj) { + return pcb(err, JSON.parse(obj)); + }; }; + return _this.db.lpop('event_queue', makeObj(cb)); }; - return _this.db.lpop('event_queue', makeObj(cb)); - }; + })(this); + /* Purge the event queue. @public purgeEventQueue() - */ + */ + exports.purgeEventQueue = (function(_this) { + return function() { + return _this.db.del('event_queue', replyHandler('purging event queue')); + }; + })(this); - exports.purgeEventQueue = function() { - return _this.db.del('event_queue', replyHandler('purging event queue')); - }; /* Hashes a string based on SHA-3-512. @private hash( *plainText* ) @param {String} plainText - */ + */ + hash = (function(_this) { + return function(plainText) { + var err; + if (plainText == null) { + return null; + } + try { + return (crypto.SHA3(plainText, { + outputLength: 512 + })).toString(); + } catch (_error) { + err = _error; + _this.log.warn(err, 'DB | during hashing'); + return null; + } + }; + })(this); - hash = function(plainText) { - var err; - if (plainText == null) { - return null; - } - try { - return (crypto.SHA3(plainText, { - outputLength: 512 - })).toString(); - } catch (_error) { - err = _error; - _this.log.warn(err, 'DB | during hashing'); - return null; - } - }; /* Encrypts a string using the crypto key from the config file, based on aes-256-cbc. @private encrypt( *plainText* ) @param {String} plainText - */ + */ + encrypt = (function(_this) { + return function(plainText) { + var err; + if (plainText == null) { + return null; + } + try { + return crypto.AES.encrypt(plainText, _this.crypto_key); + } catch (_error) { + err = _error; + _this.log.warn(err, 'DB | during encryption'); + return null; + } + }; + })(this); - encrypt = function(plainText) { - var err; - if (plainText == null) { - return null; - } - try { - return crypto.AES.encrypt(plainText, _this.crypto_key); - } catch (_error) { - err = _error; - _this.log.warn(err, 'DB | during encryption'); - return null; - } - }; /* Decrypts an encrypted string and hands it back on success or null. @private decrypt( *crypticText* ) @param {String} crypticText - */ + */ + decrypt = (function(_this) { + return function(crypticText) { + var dec, err; + if (crypticText == null) { + return null; + } + try { + dec = crypto.AES.decrypt(crypticText, _this.crypto_key); + return dec.toString(crypto.enc.Utf8); + } catch (_error) { + err = _error; + _this.log.warn(err, 'DB | during decryption'); + return null; + } + }; + })(this); - decrypt = function(crypticText) { - var dec, err; - if (crypticText == null) { - return null; - } - try { - dec = crypto.AES.decrypt(crypticText, _this.crypto_key); - return dec.toString(crypto.enc.Utf8); - } catch (_error) { - err = _error; - _this.log.warn(err, 'DB | during decryption'); - return null; - } - }; /* Fetches all linked data set keys from a linking set, fetches the single @@ -234,50 +252,51 @@ Persistence per set entry @param {function} cb the callback(err, obj) function that receives all the retrieved data or an error - */ + */ - - getSetRecords = function(set, fSingle, cb) { - _this.log.info("DB | Fetching set records: '" + set + "'"); - return _this.db.smembers(set, function(err, arrReply) { - var fCallback, objReplies, reply, semaphore, _i, _len, _results; - if (err) { - _this.log.warn(err, "DB | fetching '" + set + "'"); - return cb(err); - } else if (arrReply.length === 0) { - return cb(); - } else { - semaphore = arrReply.length; - objReplies = {}; - setTimeout(function() { - if (semaphore > 0) { - return cb(new Error("Timeout fetching '" + set + "'")); - } - }, 2000); - fCallback = function(prop) { - return function(err, data) { - --semaphore; - if (err) { - _this.log.warn(err, "DB | fetching single element: '" + prop + "'"); - } else if (!data) { - _this.log.warn(new Error("Empty key in DB: '" + prop + "'")); - } else { - objReplies[prop] = data; - } - if (semaphore === 0) { - return cb(null, objReplies); + getSetRecords = (function(_this) { + return function(set, fSingle, cb) { + _this.log.info("DB | Fetching set records: '" + set + "'"); + return _this.db.smembers(set, function(err, arrReply) { + var fCallback, objReplies, reply, semaphore, _i, _len, _results; + if (err) { + _this.log.warn(err, "DB | fetching '" + set + "'"); + return cb(err); + } else if (arrReply.length === 0) { + return cb(); + } else { + semaphore = arrReply.length; + objReplies = {}; + setTimeout(function() { + if (semaphore > 0) { + return cb(new Error("Timeout fetching '" + set + "'")); } + }, 2000); + fCallback = function(prop) { + return function(err, data) { + --semaphore; + if (err) { + _this.log.warn(err, "DB | fetching single element: '" + prop + "'"); + } else if (!data) { + _this.log.warn(new Error("Empty key in DB: '" + prop + "'")); + } else { + objReplies[prop] = data; + } + if (semaphore === 0) { + return cb(null, objReplies); + } + }; }; - }; - _results = []; - for (_i = 0, _len = arrReply.length; _i < _len; _i++) { - reply = arrReply[_i]; - _results.push(fSingle(reply, fCallback(reply))); + _results = []; + for (_i = 0, _len = arrReply.length; _i < _len; _i++) { + reply = arrReply[_i]; + _results.push(fSingle(reply, fCallback(reply))); + } + return _results; } - return _results; - } - }); - }; + }); + }; + })(this); IndexedModules = (function() { function IndexedModules(setname, db, log) { @@ -305,7 +324,8 @@ Persistence IndexedModules.prototype.storeModule = function(mId, data) { this.log.info("DB | storeModule(" + this.setname + "): " + mId); this.db.sadd("" + this.setname + "s", mId, replyHandler("Storing '" + this.setname + "' key '" + mId + "'")); - return this.db.hmset("" + this.setname + ":" + mId, data, replyHandler("Storing '" + this.setname + ":" + mId + "'")); + this.db.hmset("" + this.setname + ":" + mId, 'code', data['code'], replyHandler("Storing '" + this.setname + ":" + mId + "'")); + return this.db.hmset("" + this.setname + ":" + mId, 'reqparams', data['reqparams'], replyHandler("Storing '" + this.setname + ":" + mId + "'")); }; IndexedModules.prototype.linkModule = function(mId, userId) { @@ -389,9 +409,10 @@ Persistence })(); + /* - ## Action Invokers - */ + *# Action Invokers + */ /* @@ -401,37 +422,43 @@ Persistence @param {String} aiId @param {String} userId @param {String} data - */ + */ + exports.storeActionInvoker = (function(_this) { + return function(aiId, userId, data) { + _this.ai.storeModule(aiId, data); + return _this.ai.linkModule(aiId, userId); + }; + })(this); - exports.storeActionInvoker = function(aiId, userId, data) { - _this.ai.storeModule(aiId, data); - return _this.ai.linkModule(aiId, userId); - }; /* Make an action invoker public. @public publishActionInvoker ( *aiId* ) @param {String} aiId - */ + */ + exports.publishActionInvoker = (function(_this) { + return function(aiId) { + return _this.ai.publish(aiId); + }; + })(this); - exports.publishActionInvoker = function(aiId) { - return _this.ai.publish(aiId); - }; /* Make an action invoker private. @public unpublishActionInvoker ( *aiId* ) @param {String} aiId - */ + */ + exports.unpublishActionInvoker = (function(_this) { + return function(aiId) { + return _this.ai.unpublish(aiId); + }; + })(this); - exports.unpublishActionInvoker = function(aiId) { - return _this.ai.unpublish(aiId); - }; /* Query the DB for an action invoker and pass it to cb(err, obj). @@ -439,12 +466,14 @@ Persistence @public getActionInvoker( *aiId, cb* ) @param {String} aiId @param {function} cb - */ + */ + exports.getActionInvoker = (function(_this) { + return function(aiId, cb) { + return _this.ai.getModule(aiId, cb); + }; + })(this); - exports.getActionInvoker = function(aiId, cb) { - return _this.ai.getModule(aiId, cb); - }; /* Query the DB for action invoker required params and pass it to cb(err, obj). @@ -452,24 +481,28 @@ Persistence @public getActionInvokerEventPollerRequiredParams( *epId, cb* ) @param {String} epId @param {function} cb - */ + */ + exports.getActionInvokerRequiredParams = (function(_this) { + return function(epId, cb) { + return _this.ai.getModuleParams(epId, cb); + }; + })(this); - exports.getActionInvokerRequiredParams = function(epId, cb) { - return _this.ai.getModuleParams(epId, cb); - }; /* Fetch all action invoker IDs and hand them to cb(err, obj). @public getActionInvokerIds( *cb* ) @param {function} cb - */ + */ + exports.getActionInvokerIds = (function(_this) { + return function(cb) { + return _this.ai.getModuleIds(cb); + }; + })(this); - exports.getActionInvokerIds = function(cb) { - return _this.ai.getModuleIds(cb); - }; /* Fetch all available actin invoker IDs for a user and @@ -477,48 +510,56 @@ Persistence @public getAvailableActionInvokerIds( *userId, cb* ) @param {function} cb - */ + */ + exports.getAvailableActionInvokerIds = (function(_this) { + return function(userId, cb) { + return _this.ai.getAvailableModuleIds(userId, cb); + }; + })(this); - exports.getAvailableActionInvokerIds = function(userId, cb) { - return _this.ai.getAvailableModuleIds(userId, cb); - }; /* Fetch all public action invoker IDs and hand them to cb(err, obj). @public getPublicActionInvokerIds( *cb* ) @param {function} cb - */ + */ + exports.getPublicActionInvokerIds = (function(_this) { + return function(cb) { + return _this.ai.getPublicModuleIds(cb); + }; + })(this); - exports.getPublicActionInvokerIds = function(cb) { - return _this.ai.getPublicModuleIds(cb); - }; /* Fetch all action invokers and hand them to cb(err, obj). @public getActionInvokers( *cb* ) @param {function} cb - */ + */ + exports.getActionInvokers = (function(_this) { + return function(cb) { + return _this.ai.getModules(cb); + }; + })(this); - exports.getActionInvokers = function(cb) { - return _this.ai.getModules(cb); - }; /* Fetch all action invokers and hand them to cb(err, obj). @public getActionInvokers( *cb* ) @param {function} cb - */ + */ + exports.deleteActionInvoker = (function(_this) { + return function(aiId) { + return _this.ai.deleteModule(aiId); + }; + })(this); - exports.deleteActionInvoker = function(aiId) { - return _this.ai.deleteModule(aiId); - }; /* Store user-specific action invoker parameters . @@ -527,12 +568,14 @@ Persistence @param {String} userId @param {String} aiId @param {String} data - */ + */ + exports.storeActionUserParams = (function(_this) { + return function(aiId, userId, data) { + return _this.ai.storeUserParameters(aiId, userId, data); + }; + })(this); - exports.storeActionUserParams = function(aiId, userId, data) { - return _this.ai.storeUserParameters(aiId, userId, data); - }; /* Query the DB for user-specific action module parameters, @@ -542,40 +585,46 @@ Persistence @param {String} userId @param {String} aiId @param {function} cb - */ + */ + exports.getActionUserParams = (function(_this) { + return function(aiId, userId, cb) { + return _this.ai.getUserParameters(aiId, userId, cb); + }; + })(this); - exports.getActionUserParams = function(aiId, userId, cb) { - return _this.ai.getUserParameters(aiId, userId, cb); - }; /* Fetch all action params IDs and hand them to cb(err, obj). @public getActionUserParamsIds( *cb* ) @param {function} cb - */ + */ + exports.getActionUserParamsIds = (function(_this) { + return function(cb) { + return _this.ai.getUserParametersIds(cb); + }; + })(this); - exports.getActionUserParamsIds = function(cb) { - return _this.ai.getUserParametersIds(cb); - }; /* Fetch all action modules and hand them to cb(err, obj). @public deleteActionUserParams( *cb* ) @param {function} cb - */ + */ + exports.deleteActionUserParams = (function(_this) { + return function(aiId, userId) { + return _this.ai.deleteUserParameters(aiId, userId); + }; + })(this); - exports.deleteActionUserParams = function(aiId, userId) { - return _this.ai.deleteUserParameters(aiId, userId); - }; /* - ## Event Pollers - */ + *# Event Pollers + */ /* @@ -585,37 +634,43 @@ Persistence @param {String} epId @param {String} userId @param {String} data - */ + */ + exports.storeEventPoller = (function(_this) { + return function(epId, userId, data) { + _this.ep.storeModule(epId, data); + return _this.ep.linkModule(epId, userId); + }; + })(this); - exports.storeEventPoller = function(epId, userId, data) { - _this.ep.storeModule(epId, data); - return _this.ep.linkModule(epId, userId); - }; /* Make an event poller public. @public publishEventPoller ( *epId* ) @param {String} epId - */ + */ + exports.publishEventPoller = (function(_this) { + return function(epId) { + return _this.ep.publish(epId); + }; + })(this); - exports.publishEventPoller = function(epId) { - return _this.ep.publish(epId); - }; /* Make an event poller private. @public unpublishEventPoller ( *epId* ) @param {String} epId - */ + */ + exports.unpublishEventPoller = (function(_this) { + return function(epId) { + return _this.ep.unpublish(epId); + }; + })(this); - exports.unpublishEventPoller = function(epId) { - return _this.ep.unpublish(epId); - }; /* Query the DB for an event poller and pass it to cb(err, obj). @@ -623,12 +678,14 @@ Persistence @public getEventPoller( *epId, cb* ) @param {String} epId @param {function} cb - */ + */ + exports.getEventPoller = (function(_this) { + return function(epId, cb) { + return _this.ep.getModule(epId, cb); + }; + })(this); - exports.getEventPoller = function(epId, cb) { - return _this.ep.getModule(epId, cb); - }; /* Query the DB for event poller required params and pass it to cb(err, obj). @@ -636,24 +693,28 @@ Persistence @public getEventPollerRequiredParams( *epId, cb* ) @param {String} epId @param {function} cb - */ + */ + exports.getEventPollerRequiredParams = (function(_this) { + return function(epId, cb) { + return _this.ep.getModuleParams(epId, cb); + }; + })(this); - exports.getEventPollerRequiredParams = function(epId, cb) { - return _this.ep.getModuleParams(epId, cb); - }; /* Fetch all event poller IDs and hand them to cb(err, obj). @public getEventPollerIds( *cb* ) @param {function} cb - */ + */ + exports.getEventPollerIds = (function(_this) { + return function(cb) { + return _this.ep.getModuleIds(cb); + }; + })(this); - exports.getEventPollerIds = function(cb) { - return _this.ep.getModuleIds(cb); - }; /* Fetch all available event poller IDs for a user and @@ -661,48 +722,56 @@ Persistence @public getAvailableEventPollerIds( *userId, cb* ) @param {function} cb - */ + */ + exports.getAvailableEventPollerIds = (function(_this) { + return function(userId, cb) { + return _this.ep.getAvailableModuleIds(userId, cb); + }; + })(this); - exports.getAvailableEventPollerIds = function(userId, cb) { - return _this.ep.getAvailableModuleIds(userId, cb); - }; /* Fetch all public event poller IDs and hand them to cb(err, obj). @public getPublicEventPollerIds( *cb* ) @param {function} cb - */ + */ + exports.getPublicEventPollerIds = (function(_this) { + return function(cb) { + return _this.ep.getPublicModuleIds(cb); + }; + })(this); - exports.getPublicEventPollerIds = function(cb) { - return _this.ep.getPublicModuleIds(cb); - }; /* Fetch all event pollers and hand them to cb(err, obj). @public getEventPollers( *cb* ) @param {function} cb - */ + */ + exports.getEventPollers = (function(_this) { + return function(cb) { + return _this.ep.getModules(cb); + }; + })(this); - exports.getEventPollers = function(cb) { - return _this.ep.getModules(cb); - }; /* Fetch all event pollers and hand them to cb(err, obj). @public getEventPollers( *cb* ) @param {function} cb - */ + */ + exports.deleteEventPoller = (function(_this) { + return function(epId) { + return _this.ep.deleteModule(epId); + }; + })(this); - exports.deleteEventPoller = function(epId) { - return _this.ep.deleteModule(epId); - }; /* Store user-specific event poller parameters . @@ -711,12 +780,14 @@ Persistence @param {String} userId @param {String} epId @param {String} data - */ + */ + exports.storeEventUserParams = (function(_this) { + return function(epId, userId, data) { + return _this.ep.storeUserParameters(epId, userId, data); + }; + })(this); - exports.storeEventUserParams = function(epId, userId, data) { - return _this.ep.storeUserParameters(epId, userId, data); - }; /* Query the DB for user-specific event module parameters, @@ -726,40 +797,46 @@ Persistence @param {String} userId @param {String} epId @param {function} cb - */ + */ + exports.getEventUserParams = (function(_this) { + return function(epId, userId, cb) { + return _this.ep.getUserParameters(epId, userId, cb); + }; + })(this); - exports.getEventUserParams = function(epId, userId, cb) { - return _this.ep.getUserParameters(epId, userId, cb); - }; /* Fetch all event params IDs and hand them to cb(err, obj). @public getEventUserParamsIds( *cb* ) @param {function} cb - */ + */ + exports.getEventUserParamsIds = (function(_this) { + return function(cb) { + return _this.ep.getUserParametersIds(cb); + }; + })(this); - exports.getEventUserParamsIds = function(cb) { - return _this.ep.getUserParametersIds(cb); - }; /* Fetch all event modules and hand them to cb(err, obj). @public deleteEventUserParams( *cb* ) @param {function} cb - */ + */ + exports.deleteEventUserParams = (function(_this) { + return function(epId, userId) { + return _this.ep.deleteUserParameters(epId, userId); + }; + })(this); - exports.deleteEventUserParams = function(epId, userId) { - return _this.ep.deleteUserParameters(epId, userId); - }; /* - ## Rules - */ + *# Rules + */ /* @@ -768,39 +845,45 @@ Persistence @public getRule( *ruleId, cb* ) @param {String} ruleId @param {function} cb - */ + */ + exports.getRule = (function(_this) { + return function(ruleId, cb) { + _this.log.info("DB | getRule: '" + ruleId + "'"); + return _this.db.get("rule:" + ruleId, cb); + }; + })(this); - exports.getRule = function(ruleId, cb) { - _this.log.info("DB | getRule: '" + ruleId + "'"); - return _this.db.get("rule:" + ruleId, cb); - }; /* Fetch all rules and pass them to cb(err, obj). @public getRules( *cb* ) @param {function} cb - */ + */ + exports.getRules = (function(_this) { + return function(cb) { + _this.log.info('DB | Fetching all Rules'); + return getSetRecords('rules', exports.getRule, cb); + }; + })(this); - exports.getRules = function(cb) { - _this.log.info('DB | Fetching all Rules'); - return getSetRecords('rules', exports.getRule, cb); - }; /* Fetch all rule IDs and hand it to cb(err, obj). @public getRuleIds( *cb* ) @param {function} cb - */ + */ + exports.getRuleIds = (function(_this) { + return function(cb) { + _this.log.info('DB | Fetching all Rule IDs'); + return _this.db.smembers('rules', cb); + }; + })(this); - exports.getRuleIds = function(cb) { - _this.log.info('DB | Fetching all Rule IDs'); - return _this.db.smembers('rules', cb); - }; /* Store a string representation of a rule in the DB. @@ -808,14 +891,16 @@ Persistence @public storeRule( *ruleId, data* ) @param {String} ruleId @param {String} data - */ + */ + exports.storeRule = (function(_this) { + return function(ruleId, data) { + _this.log.info("DB | storeRule: '" + ruleId + "'"); + _this.db.sadd('rules', "" + ruleId, replyHandler("storing rule key '" + ruleId + "'")); + return _this.db.set("rule:" + ruleId, data, replyHandler("storing rule '" + ruleId + "'")); + }; + })(this); - exports.storeRule = function(ruleId, data) { - _this.log.info("DB | storeRule: '" + ruleId + "'"); - _this.db.sadd('rules', "" + ruleId, replyHandler("storing rule key '" + ruleId + "'")); - return _this.db.set("rule:" + ruleId, data, replyHandler("storing rule '" + ruleId + "'")); - }; /* Delete a string representation of a rule. @@ -823,40 +908,42 @@ Persistence @public deleteRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ + exports.deleteRule = (function(_this) { + return function(ruleId) { + _this.log.info("DB | deleteRule: '" + ruleId + "'"); + _this.db.srem("rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "'")); + _this.db.del("rule:" + ruleId, replyHandler("Deleting rule '" + ruleId + "'")); + _this.db.smembers("rule:" + ruleId + ":users", function(err, obj) { + var delLinkedUserRule, id, _i, _len, _results; + delLinkedUserRule = function(userId) { + return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in linked user '" + userId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delLinkedUserRule(id)); + } + return _results; + }); + _this.db.del("rule:" + ruleId + ":users", replyHandler("Deleting rule '" + ruleId + "' users")); + _this.db.smembers("rule:" + ruleId + ":active-users", function(err, obj) { + var delActiveUserRule, id, _i, _len, _results; + delActiveUserRule = function(userId) { + return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in active user '" + userId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delActiveUserRule(id)); + } + return _results; + }); + return _this.db.del("rule:" + ruleId + ":active-users", replyHandler("Deleting rule '" + ruleId + "' active users")); + }; + })(this); - exports.deleteRule = function(ruleId) { - _this.log.info("DB | deleteRule: '" + ruleId + "'"); - _this.db.srem("rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "'")); - _this.db.del("rule:" + ruleId, replyHandler("Deleting rule '" + ruleId + "'")); - _this.db.smembers("rule:" + ruleId + ":users", function(err, obj) { - var delLinkedUserRule, id, _i, _len, _results; - delLinkedUserRule = function(userId) { - return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in linked user '" + userId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delLinkedUserRule(id)); - } - return _results; - }); - _this.db.del("rule:" + ruleId + ":users", replyHandler("Deleting rule '" + ruleId + "' users")); - _this.db.smembers("rule:" + ruleId + ":active-users", function(err, obj) { - var delActiveUserRule, id, _i, _len, _results; - delActiveUserRule = function(userId) { - return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("Deleting rule key '" + ruleId + "' in active user '" + userId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delActiveUserRule(id)); - } - return _results; - }); - return _this.db.del("rule:" + ruleId + ":active-users", replyHandler("Deleting rule '" + ruleId + "' active users")); - }; /* Associate a rule to a user. @@ -864,14 +951,16 @@ Persistence @public linkRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ + exports.linkRule = (function(_this) { + return function(ruleId, userId) { + _this.log.info("DB | linkRule: '" + ruleId + "' for user '" + userId + "'"); + _this.db.sadd("rule:" + ruleId + ":users", userId, replyHandler("storing user '" + userId + "' for rule key '" + ruleId + "'")); + return _this.db.sadd("user:" + userId + ":rules", ruleId, replyHandler("storing rule key '" + ruleId + "' for user '" + userId + "'")); + }; + })(this); - exports.linkRule = function(ruleId, userId) { - _this.log.info("DB | linkRule: '" + ruleId + "' for user '" + userId + "'"); - _this.db.sadd("rule:" + ruleId + ":users", userId, replyHandler("storing user '" + userId + "' for rule key '" + ruleId + "'")); - return _this.db.sadd("user:" + userId + ":rules", ruleId, replyHandler("storing rule key '" + ruleId + "' for user '" + userId + "'")); - }; /* Get rules linked to a user and hand it to cb(err, obj). @@ -879,13 +968,15 @@ Persistence @public getUserLinkRule( *userId, cb* ) @param {String} userId @param {function} cb - */ + */ + exports.getUserLinkedRules = (function(_this) { + return function(userId, cb) { + _this.log.info("DB | getUserLinkedRules: for user '" + userId + "'"); + return _this.db.smembers("user:" + userId + ":rules", cb); + }; + })(this); - exports.getUserLinkedRules = function(userId, cb) { - _this.log.info("DB | getUserLinkedRules: for user '" + userId + "'"); - return _this.db.smembers("user:" + userId + ":rules", cb); - }; /* Get users linked to a rule and hand it to cb(err, obj). @@ -893,13 +984,15 @@ Persistence @public getRuleLinkedUsers( *ruleId, cb* ) @param {String} ruleId @param {function} cb - */ + */ + exports.getRuleLinkedUsers = (function(_this) { + return function(ruleId, cb) { + _this.log.info("DB | getRuleLinkedUsers: for rule '" + ruleId + "'"); + return _this.db.smembers("rule:" + ruleId + ":users", cb); + }; + })(this); - exports.getRuleLinkedUsers = function(ruleId, cb) { - _this.log.info("DB | getRuleLinkedUsers: for rule '" + ruleId + "'"); - return _this.db.smembers("rule:" + ruleId + ":users", cb); - }; /* Delete an association of a rule to a user. @@ -907,14 +1000,16 @@ Persistence @public unlinkRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ + exports.unlinkRule = (function(_this) { + return function(ruleId, userId) { + _this.log.info("DB | unlinkRule: '" + ruleId + ":" + userId + "'"); + _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("removing user '" + userId + "' for rule key '" + ruleId + "'")); + return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("removing rule key '" + ruleId + "' for user '" + userId + "'")); + }; + })(this); - exports.unlinkRule = function(ruleId, userId) { - _this.log.info("DB | unlinkRule: '" + ruleId + ":" + userId + "'"); - _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("removing user '" + userId + "' for rule key '" + ruleId + "'")); - return _this.db.srem("user:" + userId + ":rules", ruleId, replyHandler("removing rule key '" + ruleId + "' for user '" + userId + "'")); - }; /* Activate a rule. @@ -922,14 +1017,16 @@ Persistence @public activateRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ + exports.activateRule = (function(_this) { + return function(ruleId, userId) { + _this.log.info("DB | activateRule: '" + ruleId + "' for '" + userId + "'"); + _this.db.sadd("rule:" + ruleId + ":active-users", userId, replyHandler("storing activated user '" + userId + "' in rule '" + ruleId + "'")); + return _this.db.sadd("user:" + userId + ":active-rules", ruleId, replyHandler("storing activated rule '" + ruleId + "' in user '" + userId + "'")); + }; + })(this); - exports.activateRule = function(ruleId, userId) { - _this.log.info("DB | activateRule: '" + ruleId + "' for '" + userId + "'"); - _this.db.sadd("rule:" + ruleId + ":active-users", userId, replyHandler("storing activated user '" + userId + "' in rule '" + ruleId + "'")); - return _this.db.sadd("user:" + userId + ":active-rules", ruleId, replyHandler("storing activated rule '" + ruleId + "' in user '" + userId + "'")); - }; /* Get rules activated for a user and hand it to cb(err, obj). @@ -937,13 +1034,15 @@ Persistence @public getUserLinkRule( *userId, cb* ) @param {String} userId @param {function} cb - */ + */ + exports.getUserActivatedRules = (function(_this) { + return function(userId, cb) { + _this.log.info("DB | getUserActivatedRules: for user '" + userId + "'"); + return _this.db.smembers("user:" + userId + ":active-rules", cb); + }; + })(this); - exports.getUserActivatedRules = function(userId, cb) { - _this.log.info("DB | getUserActivatedRules: for user '" + userId + "'"); - return _this.db.smembers("user:" + userId + ":active-rules", cb); - }; /* Get users activated for a rule and hand it to cb(err, obj). @@ -951,13 +1050,15 @@ Persistence @public getRuleActivatedUsers ( *ruleId, cb* ) @param {String} ruleId @param {function} cb - */ + */ + exports.getRuleActivatedUsers = (function(_this) { + return function(ruleId, cb) { + _this.log.info("DB | getRuleActivatedUsers: for rule '" + ruleId + "'"); + return _this.db.smembers("rule:" + ruleId + ":active-users", cb); + }; + })(this); - exports.getRuleActivatedUsers = function(ruleId, cb) { - _this.log.info("DB | getRuleActivatedUsers: for rule '" + ruleId + "'"); - return _this.db.smembers("rule:" + ruleId + ":active-users", cb); - }; /* Deactivate a rule. @@ -965,55 +1066,59 @@ Persistence @public deactivateRule( *ruleId, userId* ) @param {String} ruleId @param {String} userId - */ + */ + exports.deactivateRule = (function(_this) { + return function(ruleId, userId) { + _this.log.info("DB | deactivateRule: '" + ruleId + "' for '" + userId + "'"); + _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("removing activated user '" + userId + "' in rule '" + ruleId + "'")); + return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("removing activated rule '" + ruleId + "' in user '" + userId + "'")); + }; + })(this); - exports.deactivateRule = function(ruleId, userId) { - _this.log.info("DB | deactivateRule: '" + ruleId + "' for '" + userId + "'"); - _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("removing activated user '" + userId + "' in rule '" + ruleId + "'")); - return _this.db.srem("user:" + userId + ":active-rules", ruleId, replyHandler("removing activated rule '" + ruleId + "' in user '" + userId + "'")); - }; /* Fetch all active ruleIds and pass them to cb(err, obj). @public getAllActivatedRuleIds( *cb* ) @param {function} cb - */ + */ - - exports.getAllActivatedRuleIdsPerUser = function(cb) { - _this.log.info("DB | Fetching all active rules"); - return _this.db.smembers('users', function(err, obj) { - var fFetchActiveUserRules, result, semaphore, user, _i, _len, _results; - result = {}; - if (obj.length === 0) { - return cb(null, result); - } else { - semaphore = obj.length; - fFetchActiveUserRules = function(userId) { - return _this.db.smembers("user:" + user + ":active-rules", function(err, obj) { - if (obj.length > 0) { - result[userId] = obj; - } - if (--semaphore === 0) { - return cb(null, result); - } - }); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - user = obj[_i]; - _results.push(fFetchActiveUserRules(user)); + exports.getAllActivatedRuleIdsPerUser = (function(_this) { + return function(cb) { + _this.log.info("DB | Fetching all active rules"); + return _this.db.smembers('users', function(err, obj) { + var fFetchActiveUserRules, result, semaphore, user, _i, _len, _results; + result = {}; + if (obj.length === 0) { + return cb(null, result); + } else { + semaphore = obj.length; + fFetchActiveUserRules = function(userId) { + return _this.db.smembers("user:" + user + ":active-rules", function(err, obj) { + if (obj.length > 0) { + result[userId] = obj; + } + if (--semaphore === 0) { + return cb(null, result); + } + }); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + user = obj[_i]; + _results.push(fFetchActiveUserRules(user)); + } + return _results; } - return _results; - } - }); - }; + }); + }; + })(this); + /* - ## Users - */ + *# Users + */ /* @@ -1022,32 +1127,36 @@ Persistence @public storeUser( *objUser* ) @param {Object} objUser - */ + */ + exports.storeUser = (function(_this) { + return function(objUser) { + _this.log.info("DB | storeUser: '" + objUser.username + "'"); + if (objUser && objUser.username && objUser.password) { + _this.db.sadd('users', objUser.username, replyHandler("storing user key '" + objUser.username + "'")); + objUser.password = objUser.password; + return _this.db.hmset("user:" + objUser.username, objUser, replyHandler("storing user properties '" + objUser.username + "'")); + } else { + return _this.log.warn(new Error('DB | username or password was missing')); + } + }; + })(this); - exports.storeUser = function(objUser) { - _this.log.info("DB | storeUser: '" + objUser.username + "'"); - if (objUser && objUser.username && objUser.password) { - _this.db.sadd('users', objUser.username, replyHandler("storing user key '" + objUser.username + "'")); - objUser.password = objUser.password; - return _this.db.hmset("user:" + objUser.username, objUser, replyHandler("storing user properties '" + objUser.username + "'")); - } else { - return _this.log.warn(new Error('DB | username or password was missing')); - } - }; /* Fetch all user IDs and pass them to cb(err, obj). @public getUserIds( *cb* ) @param {function} cb - */ + */ + exports.getUserIds = (function(_this) { + return function(cb) { + _this.log.info("DB | getUserIds"); + return _this.db.smembers("users", cb); + }; + })(this); - exports.getUserIds = function(cb) { - _this.log.info("DB | getUserIds"); - return _this.db.smembers("users", cb); - }; /* Fetch a user by id and pass it to cb(err, obj). @@ -1055,66 +1164,70 @@ Persistence @public getUser( *userId, cb* ) @param {String} userId @param {function} cb - */ + */ + exports.getUser = (function(_this) { + return function(userId, cb) { + _this.log.info("DB | getUser: '" + userId + "'"); + return _this.db.hgetall("user:" + userId, cb); + }; + })(this); - exports.getUser = function(userId, cb) { - _this.log.info("DB | getUser: '" + userId + "'"); - return _this.db.hgetall("user:" + userId, cb); - }; /* Deletes a user and all his associated linked and active rules. @public deleteUser( *userId* ) @param {String} userId - */ + */ + exports.deleteUser = (function(_this) { + return function(userId) { + _this.log.info("DB | deleteUser: '" + userId + "'"); + _this.db.srem("users", userId, replyHandler("Deleting user key '" + userId + "'")); + _this.db.del("user:" + userId, replyHandler("Deleting user '" + userId + "'")); + _this.db.smembers("user:" + userId + ":rules", function(err, obj) { + var delLinkedRuleUser, id, _i, _len, _results; + delLinkedRuleUser = function(ruleId) { + return _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in linked rule '" + ruleId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delLinkedRuleUser(id)); + } + return _results; + }); + _this.db.del("user:" + userId + ":rules", replyHandler("Deleting user '" + userId + "' rules")); + _this.db.smembers("user:" + userId + ":active-rules", function(err, obj) { + var delActivatedRuleUser, id, _i, _len, _results; + delActivatedRuleUser = function(ruleId) { + return _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("Deleting user key '" + userId + "' in active rule '" + ruleId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delActivatedRuleUser(id)); + } + return _results; + }); + _this.db.del("user:" + userId + ":active-rules", replyHandler("Deleting user '" + userId + "' rules")); + _this.db.smembers("user:" + userId + ":roles", function(err, obj) { + var delRoleUser, id, _i, _len, _results; + delRoleUser = function(roleId) { + return _this.db.srem("role:" + roleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in role '" + roleId + "'")); + }; + _results = []; + for (_i = 0, _len = obj.length; _i < _len; _i++) { + id = obj[_i]; + _results.push(delRoleUser(id)); + } + return _results; + }); + return _this.db.del("user:" + userId + ":roles", replyHandler("Deleting user '" + userId + "' roles")); + }; + })(this); - exports.deleteUser = function(userId) { - _this.log.info("DB | deleteUser: '" + userId + "'"); - _this.db.srem("users", userId, replyHandler("Deleting user key '" + userId + "'")); - _this.db.del("user:" + userId, replyHandler("Deleting user '" + userId + "'")); - _this.db.smembers("user:" + userId + ":rules", function(err, obj) { - var delLinkedRuleUser, id, _i, _len, _results; - delLinkedRuleUser = function(ruleId) { - return _this.db.srem("rule:" + ruleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in linked rule '" + ruleId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delLinkedRuleUser(id)); - } - return _results; - }); - _this.db.del("user:" + userId + ":rules", replyHandler("Deleting user '" + userId + "' rules")); - _this.db.smembers("user:" + userId + ":active-rules", function(err, obj) { - var delActivatedRuleUser, id, _i, _len, _results; - delActivatedRuleUser = function(ruleId) { - return _this.db.srem("rule:" + ruleId + ":active-users", userId, replyHandler("Deleting user key '" + userId + "' in active rule '" + ruleId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delActivatedRuleUser(id)); - } - return _results; - }); - _this.db.del("user:" + userId + ":active-rules", replyHandler("Deleting user '" + userId + "' rules")); - _this.db.smembers("user:" + userId + ":roles", function(err, obj) { - var delRoleUser, id, _i, _len, _results; - delRoleUser = function(roleId) { - return _this.db.srem("role:" + roleId + ":users", userId, replyHandler("Deleting user key '" + userId + "' in role '" + roleId + "'")); - }; - _results = []; - for (_i = 0, _len = obj.length; _i < _len; _i++) { - id = obj[_i]; - _results.push(delRoleUser(id)); - } - return _results; - }); - return _this.db.del("user:" + userId + ":roles", replyHandler("Deleting user '" + userId + "' roles")); - }; /* Checks the credentials and on success returns the user object to the @@ -1126,34 +1239,36 @@ Persistence @param {String} userId @param {String} password @param {function} cb - */ + */ - - exports.loginUser = function(userId, password, cb) { - var fCheck; - _this.log.info("DB | User '" + userId + "' tries to log in"); - fCheck = function(pw) { - return function(err, obj) { - if (err) { - return cb(err, null); - } else if (obj && obj.password) { - if (pw === obj.password) { - _this.log.info("DB | User '" + obj.username + "' logged in!"); - return cb(null, obj); + exports.loginUser = (function(_this) { + return function(userId, password, cb) { + var fCheck; + _this.log.info("DB | User '" + userId + "' tries to log in"); + fCheck = function(pw) { + return function(err, obj) { + if (err) { + return cb(err, null); + } else if (obj && obj.password) { + if (pw === obj.password) { + _this.log.info("DB | User '" + obj.username + "' logged in!"); + return cb(null, obj); + } else { + return cb(new Error('Wrong credentials!'), null); + } } else { - return cb(new Error('Wrong credentials!'), null); + return cb(new Error('User not found!'), null); } - } else { - return cb(new Error('User not found!'), null); - } + }; }; + return _this.db.hgetall("user:" + userId, fCheck(password)); }; - return _this.db.hgetall("user:" + userId, fCheck(password)); - }; + })(this); + /* - ## User Roles - */ + *# User Roles + */ /* @@ -1162,15 +1277,17 @@ Persistence @public storeUserRole( *userId, role* ) @param {String} userId @param {String} role - */ + */ + exports.storeUserRole = (function(_this) { + return function(userId, role) { + _this.log.info("DB | storeUserRole: '" + userId + ":" + role + "'"); + _this.db.sadd('roles', role, replyHandler("adding role '" + role + "' to role index set")); + _this.db.sadd("user:" + userId + ":roles", role, replyHandler("adding role '" + role + "' to user '" + userId + "'")); + return _this.db.sadd("role:" + role + ":users", userId, replyHandler("adding user '" + userId + "' to role '" + role + "'")); + }; + })(this); - exports.storeUserRole = function(userId, role) { - _this.log.info("DB | storeUserRole: '" + userId + ":" + role + "'"); - _this.db.sadd('roles', role, replyHandler("adding role '" + role + "' to role index set")); - _this.db.sadd("user:" + userId + ":roles", role, replyHandler("adding role '" + role + "' to user '" + userId + "'")); - return _this.db.sadd("role:" + role + ":users", userId, replyHandler("adding user '" + userId + "' to role '" + role + "'")); - }; /* Fetch all roles of a user and pass them to cb(err, obj). @@ -1178,13 +1295,15 @@ Persistence @public getUserRoles( *userId* ) @param {String} userId @param {function} cb - */ + */ + exports.getUserRoles = (function(_this) { + return function(userId, cb) { + _this.log.info("DB | getUserRoles: '" + userId + "'"); + return _this.db.smembers("user:" + userId + ":roles", cb); + }; + })(this); - exports.getUserRoles = function(userId, cb) { - _this.log.info("DB | getUserRoles: '" + userId + "'"); - return _this.db.smembers("user:" + userId + ":roles", cb); - }; /* Fetch all users of a role and pass them to cb(err, obj). @@ -1192,13 +1311,15 @@ Persistence @public getUserRoles( *role* ) @param {String} role @param {function} cb - */ + */ + exports.getRoleUsers = (function(_this) { + return function(role, cb) { + _this.log.info("DB | getRoleUsers: '" + role + "'"); + return _this.db.smembers("role:" + role + ":users", cb); + }; + })(this); - exports.getRoleUsers = function(role, cb) { - _this.log.info("DB | getRoleUsers: '" + role + "'"); - return _this.db.smembers("role:" + role + ":users", cb); - }; /* Remove a role from a user. @@ -1206,25 +1327,28 @@ Persistence @public removeRoleFromUser( *role, userId* ) @param {String} role @param {String} userId - */ + */ + exports.removeUserRole = (function(_this) { + return function(userId, role) { + _this.log.info("DB | removeRoleFromUser: role '" + role + "', user '" + userId + "'"); + _this.db.srem("user:" + userId + ":roles", role, replyHandler("Removing role '" + role + "' from user '" + userId + "'")); + return _this.db.srem("role:" + role + ":users", userId, replyHandler("Removing user '" + userId + "' from role '" + role + "'")); + }; + })(this); - exports.removeUserRole = function(userId, role) { - _this.log.info("DB | removeRoleFromUser: role '" + role + "', user '" + userId + "'"); - _this.db.srem("user:" + userId + ":roles", role, replyHandler("Removing role '" + role + "' from user '" + userId + "'")); - return _this.db.srem("role:" + role + ":users", userId, replyHandler("Removing user '" + userId + "' from role '" + role + "'")); - }; /* Shuts down the db link. @public shutDown() - */ + */ - - exports.shutDown = function() { - var _ref; - return (_ref = _this.db) != null ? _ref.quit() : void 0; - }; + exports.shutDown = (function(_this) { + return function() { + var _ref; + return (_ref = _this.db) != null ? _ref.quit() : void 0; + }; + })(this); }).call(this); diff --git a/js-coffee/request-handler.js b/js-coffee/request-handler.js index 1779c88..5d5eac1 100644 --- a/js-coffee/request-handler.js +++ b/js-coffee/request-handler.js @@ -1,4 +1,5 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 + /* Request Handler @@ -7,12 +8,10 @@ Request Handler > the [HTTP Listener](http-listener.html). It will handle user requests for > pages as well as POST requests such as user login, module storing, event > invocation and also admin commands. -*/ - + */ (function() { - var crypto, db, dirHandlers, exports, fs, getHandlerPath, getRemoteScripts, getScript, getTemplate, mustache, path, qs, renderPage, - _this = this; + var crypto, db, dirHandlers, exports, fs, getHandlerPath, getRemoteScripts, getScript, getTemplate, mustache, path, qs, renderPage; db = require('./persistence'); @@ -28,29 +27,32 @@ Request Handler dirHandlers = path.resolve(__dirname, '..', 'webpages', 'handlers'); - exports = module.exports = function(args) { - var user, users, _i, _len; - _this.log = args.logger; - _this.userRequestHandler = args['request-service']; - _this.objAdminCmds = { - shutdown: function(obj, cb) { - var data; - data = { - code: 200, - message: 'Shutting down... BYE!' - }; - setTimeout(args['shutdown-function'], 500); - return cb(null, data); + exports = module.exports = (function(_this) { + return function(args) { + var user, users, _i, _len; + _this.log = args.logger; + _this.userRequestHandler = args['request-service']; + _this.objAdminCmds = { + shutdown: function(obj, cb) { + var data; + data = { + code: 200, + message: 'Shutting down... BYE!' + }; + setTimeout(args['shutdown-function'], 500); + return cb(null, data); + } + }; + db(args); + 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; }; - db(args); - 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); + /* Handles possible events that were posted to this server and pushes them into the @@ -62,8 +64,7 @@ Request Handler objects.* @public handleEvent( *req, resp* ) - */ - + */ exports.handleEvent = function(req, resp) { var body; @@ -94,6 +95,7 @@ Request Handler }); }; + /* Associates the user object with the session if login is successful. @@ -103,32 +105,34 @@ Request Handler 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; - obj = qs.parse(body); - return db.loginUser(obj.username, obj.password, function(err, usr) { - if (err) { - _this.log.warn("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!'); - } + exports.handleLogin = (function(_this) { + return 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); + return db.loginUser(obj.username, obj.password, function(err, usr) { + if (err) { + _this.log.warn("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!'); + } + }); + }); + }; + })(this); + /* A post request retrieved on this handler causes the user object to be @@ -140,8 +144,7 @@ Request Handler objects.* @public handleLogout( *req, resp* ) - */ - + */ exports.handleLogout = function(req, resp) { if (req.session) { @@ -150,25 +153,25 @@ Request Handler } }; + /* Resolves the path to a handler webpage. @private getHandlerPath( *name* ) @param {String} name - */ - + */ getHandlerPath = function(name) { return path.join(dirHandlers, name + '.html'); }; + /* Fetches a template. @private getTemplate( *name* ) @param {String} name - */ - + */ getTemplate = function(name) { var pth; @@ -176,13 +179,13 @@ Request Handler return fs.readFileSync(pth, 'utf8'); }; + /* Fetches a script. @private getScript( *name* ) @param {String} name - */ - + */ getScript = function(name) { var pth; @@ -190,13 +193,13 @@ Request Handler return fs.readFileSync(pth, 'utf8'); }; + /* Fetches remote scripts snippets. @private getRemoteScripts( *name* ) @param {String} name - */ - + */ getRemoteScripts = function(name) { var pth; @@ -204,6 +207,7 @@ Request Handler return fs.readFileSync(pth, 'utf8'); }; + /* Renders a page, with helps of mustache, depending on the user session and returns it. @@ -211,8 +215,7 @@ Request Handler @param {String} name @param {Object} sess @param {Object} msg - */ - + */ renderPage = function(name, req, resp, msg) { var code, content, data, err, menubar, page, pageElements, pathSkel, remote_scripts, script, skeleton; @@ -251,6 +254,7 @@ Request Handler return resp.send(code, mustache.render(page, data)); }; + /* Present the desired forge page to the user. @@ -260,8 +264,7 @@ Request Handler objects.* @public handleForge( *req, resp* ) - */ - + */ exports.handleForge = function(req, resp) { var page; @@ -272,6 +275,7 @@ Request Handler return renderPage(page, req, resp); }; + /* Handles the user command requests. @@ -281,27 +285,29 @@ Request Handler objects.* @public handleUser( *req, resp* ) - */ + */ - - exports.handleUserCommand = function(req, resp) { - var body; - if (req.session && req.session.user) { - body = ''; - req.on('data', function(data) { - return body += data; - }); - return req.on('end', function() { - var obj; - obj = qs.parse(body); - return _this.userRequestHandler(req.session.user, obj, function(obj) { - return resp.send(obj.code, obj); + exports.handleUserCommand = (function(_this) { + return function(req, resp) { + var body; + if (req.session && req.session.user) { + body = ''; + req.on('data', function(data) { + return body += data; }); - }); - } else { - return resp.send(401, 'Login first!'); - } - }; + return req.on('end', function() { + var obj; + obj = qs.parse(body); + return _this.userRequestHandler(req.session.user, obj, function(obj) { + return resp.send(obj.code, obj); + }); + }); + } else { + return resp.send(401, 'Login first!'); + } + }; + })(this); + /* Present the admin console to the user if he's allowed to see it. @@ -312,8 +318,7 @@ Request Handler objects.* @public handleForge( *req, resp* ) - */ - + */ exports.handleAdmin = function(req, resp) { var msg, page; @@ -328,6 +333,7 @@ Request Handler return renderPage(page, req, resp, msg); }; + /* Handles the admin command requests. @@ -337,31 +343,32 @@ Request Handler objects.* @public handleAdminCommand( *req, resp* ) - */ + */ - - exports.handleAdminCommand = function(req, resp) { - var body; - if (req.session && req.session.user && req.session.user.isAdmin === "true") { - body = ''; - req.on('data', function(data) { - return body += data; - }); - return req.on('end', function() { - var obj; - obj = qs.parse(body); - _this.log.info('RH | Received admin request: ' + obj.command); - if (obj.command && _this.objAdminCmds[obj.command]) { - return _this.objAdminCmds[obj.command](obj, function(err, obj) { - return resp.send(obj.code, obj); - }); - } else { - return resp.send(404, 'Command unknown!'); - } - }); - } else { - return resp.send(401, 'You need to be logged in as admin!'); - } - }; + exports.handleAdminCommand = (function(_this) { + return function(req, resp) { + var body; + if (req.session && req.session.user && req.session.user.isAdmin === "true") { + body = ''; + req.on('data', function(data) { + return body += data; + }); + return req.on('end', function() { + var obj; + obj = qs.parse(body); + _this.log.info('RH | Received admin request: ' + obj.command); + if (obj.command && _this.objAdminCmds[obj.command]) { + return _this.objAdminCmds[obj.command](obj, function(err, obj) { + return resp.send(obj.code, obj); + }); + } else { + return resp.send(404, 'Command unknown!'); + } + }); + } else { + return resp.send(401, 'You need to be logged in as admin!'); + } + }; + })(this); }).call(this); diff --git a/js-coffee/webapi-eca.js b/js-coffee/webapi-eca.js index 76f78a2..5286c7f 100644 --- a/js-coffee/webapi-eca.js +++ b/js-coffee/webapi-eca.js @@ -1,4 +1,5 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 + /* WebAPI-ECA Engine @@ -9,12 +10,10 @@ WebAPI-ECA Engine > node webapi-eca [opt] > > See below in the optimist CLI preparation for allowed optional parameters `[opt]`. -*/ - + */ (function() { - var argv, cm, conf, cp, db, engine, fs, http, init, logger, nameEP, opt, optimist, path, procCmds, shutDown, usage, - _this = this; + var argv, cm, conf, cp, db, engine, fs, http, init, logger, nameEP, opt, optimist, path, procCmds, shutDown, usage; logger = require('./logging'); @@ -40,10 +39,10 @@ WebAPI-ECA Engine procCmds = {}; + /* Let's prepare the optimist CLI optional arguments `[opt]`: - */ - + */ usage = 'This runs your webapi-based ECA engine'; @@ -93,113 +92,117 @@ WebAPI-ECA Engine process.exit(); } + /* This function is invoked right after the module is loaded and starts the server. @private init() - */ + */ - - init = function() { - var args, logconf; - conf(argv.c); - if (!conf.isReady()) { - console.error('FAIL: Config file not ready! Shutting down...'); - process.exit(); - } - logconf = conf.getLogConf(); - if (argv.m) { - logconf['mode'] = argv.m; - } - if (argv.i) { - logconf['io-level'] = argv.i; - } - if (argv.f) { - logconf['file-level'] = argv.f; - } - if (argv.p) { - logconf['file-path'] = argv.p; - } - if (argv.n) { - logconf['nolog'] = argv.n; - } - try { - fs.unlinkSync(path.resolve(__dirname, '..', 'logs', logconf['file-path'])); - } catch (_error) {} - _this.log = logger.getLogger(logconf); - _this.log.info('RS | STARTING SERVER'); - args = { - logger: _this.log, - logconf: logconf - }; - args['http-port'] = parseInt(argv.w || conf.getHttpPort()); - args['db-port'] = parseInt(argv.d || conf.getDbPort()); - _this.log.info('RS | Initialzing DB'); - db(args); - return db.isConnected(function(err) { - var cliArgs, poller; - if (err) { - _this.log.error('RS | No DB connection, shutting down system!'); - return shutDown(); - } else { - _this.log.info('RS | Initialzing engine'); - engine(args); - _this.log.info('RS | Forking a child process for the event poller'); - cliArgs = [args.logconf['mode'], args.logconf['io-level'], args.logconf['file-level'], args.logconf['file-path'], args.logconf['nolog']]; - poller = cp.fork(path.resolve(__dirname, nameEP), cliArgs); - _this.log.info('RS | Initialzing module manager'); - cm(args); - cm.addListener('init', function(evt) { - return poller.send({ - event: 'init', - data: evt - }); - }); - cm.addListener('newRule', function(evt) { - return poller.send({ - event: 'newRule', - data: evt - }); - }); - cm.addListener('init', function(evt) { - return engine.internalEvent('init', evt); - }); - cm.addListener('newRule', function(evt) { - return engine.internalEvent('newRule', evt); - }); - _this.log.info('RS | Initialzing http listener'); - args['request-service'] = cm.processRequest; - args['shutdown-function'] = shutDown; - return http(args); + init = (function(_this) { + return function() { + var args, logconf; + conf(argv.c); + if (!conf.isReady()) { + console.error('FAIL: Config file not ready! Shutting down...'); + process.exit(); } - }); - }; + logconf = conf.getLogConf(); + if (argv.m) { + logconf['mode'] = argv.m; + } + if (argv.i) { + logconf['io-level'] = argv.i; + } + if (argv.f) { + logconf['file-level'] = argv.f; + } + if (argv.p) { + logconf['file-path'] = argv.p; + } + if (argv.n) { + logconf['nolog'] = argv.n; + } + try { + fs.unlinkSync(path.resolve(__dirname, '..', 'logs', logconf['file-path'])); + } catch (_error) {} + _this.log = logger.getLogger(logconf); + _this.log.info('RS | STARTING SERVER'); + args = { + logger: _this.log, + logconf: logconf + }; + args['http-port'] = parseInt(argv.w || conf.getHttpPort()); + args['db-port'] = parseInt(argv.d || conf.getDbPort()); + _this.log.info('RS | Initialzing DB'); + db(args); + return db.isConnected(function(err) { + var cliArgs, poller; + if (err) { + _this.log.error('RS | No DB connection, shutting down system!'); + return shutDown(); + } else { + _this.log.info('RS | Initialzing engine'); + engine(args); + _this.log.info('RS | Forking a child process for the event poller'); + cliArgs = [args.logconf['mode'], args.logconf['io-level'], args.logconf['file-level'], args.logconf['file-path'], args.logconf['nolog']]; + poller = cp.fork(path.resolve(__dirname, nameEP), cliArgs); + _this.log.info('RS | Initialzing module manager'); + cm(args); + cm.addListener('init', function(evt) { + return poller.send({ + event: 'init', + data: evt + }); + }); + cm.addListener('newRule', function(evt) { + return poller.send({ + event: 'newRule', + data: evt + }); + }); + cm.addListener('init', function(evt) { + return engine.internalEvent('init', evt); + }); + cm.addListener('newRule', function(evt) { + return engine.internalEvent('newRule', evt); + }); + _this.log.info('RS | Initialzing http listener'); + args['request-service'] = cm.processRequest; + args['shutdown-function'] = shutDown; + return http(args); + } + }); + }; + })(this); + /* Shuts down the server. @private shutDown() - */ + */ + shutDown = (function(_this) { + return function() { + _this.log.warn('RS | Received shut down command!'); + if (db != null) { + db.shutDown(); + } + if (engine != null) { + engine.shutDown(); + } + return process.exit(); + }; + })(this); - shutDown = function() { - _this.log.warn('RS | Received shut down command!'); - if (db != null) { - db.shutDown(); - } - if (engine != null) { - engine.shutDown(); - } - return process.exit(); - }; /* - ## Process Commands + *# Process Commands When the server is run as a child process, this function handles messages from the parent process (e.g. the testing suite) - */ - + */ process.on('message', function(cmd) { return typeof procCmds[cmd] === "function" ? procCmds[cmd]() : void 0; diff --git a/testing/test_config.coffee b/testing/test_config.coffee index 144dd4e..f2caf0e 100644 --- a/testing/test_config.coffee +++ b/testing/test_config.coffee @@ -19,7 +19,7 @@ exports.testParameters = ( test ) => 'mode' 'io-level' 'file-level' - 'file-path' + # 'file-path' ] test.expect 3 + reqProp.length test.ok @conf.getHttpPort(), 'HTTP port does not exist!' diff --git a/testing/test_persistence.coffee b/testing/test_persistence.coffee index fc68859..130b380 100644 --- a/testing/test_persistence.coffee +++ b/testing/test_persistence.coffee @@ -3,7 +3,7 @@ exports.setUp = ( cb ) => @path = require 'path' logger = require @path.join '..', 'js-coffee', 'logging' @log = logger.getLogger - nolog: true + nolog: true @db = require @path.join '..', 'js-coffee', 'persistence' opts = logger: @log @@ -140,6 +140,7 @@ exports.EventQueue = ### exports.ActionInvoker = setUp: ( cb ) => + @userId = 'tester1' @action1id = 'test-action-invoker_1' @action2id = 'test-action-invoker_2' @action1 = @@ -158,13 +159,13 @@ exports.ActionInvoker = testCreateAndRead: ( test ) => test.expect 3 # store an entry to start with - @db.storeActionInvoker @action1id, @action1 + @db.storeActionInvoker @action1id, @userId, @action1 # test that the ID shows up in the set @db.getActionInvokerIds ( err , obj ) => test.ok @action1id in obj, 'Expected key not in action-invokers set' - + # the retrieved object really is the one we expected @db.getActionInvoker @action1id, ( err , obj ) => test.deepEqual obj, @action1, @@ -180,8 +181,8 @@ exports.ActionInvoker = test.expect 2 # store an entry to start with - @db.storeActionInvoker @action1id, @action1 - @db.storeActionInvoker @action1id, @action2 + @db.storeActionInvoker @action1id, @userId, @action1 + @db.storeActionInvoker @action1id, @userId, @action2 # the retrieved object really is the one we expected @db.getActionInvoker @action1id, ( err , obj ) => @@ -198,7 +199,7 @@ exports.ActionInvoker = test.expect 2 # store an entry to start with - @db.storeActionInvoker @action1id, @action1 + @db.storeActionInvoker @action1id, @userId, @action1 # Ensure the action invoker has been deleted @db.deleteActionInvoker @action1id @@ -227,8 +228,8 @@ exports.ActionInvoker = "Invoker #{ modname } does not equal the expected one" forkEnds() - @db.storeActionInvoker @action1id, @action1 - @db.storeActionInvoker @action2id, @action2 + @db.storeActionInvoker @action1id, @userId, @action1 + @db.storeActionInvoker @action2id, @userId, @action2 @db.getActionInvokerIds ( err, obj ) => test.ok @action1id in obj and @action2id in obj, 'Not all action invoker Ids in set' @@ -309,6 +310,7 @@ exports.ActionInvokerParams = ### exports.EventPoller = setUp: ( cb ) => + @userId = 'tester1' @event1id = 'test-event-poller_1' @event2id = 'test-event-poller_2' @event1 = @@ -327,7 +329,7 @@ exports.EventPoller = testCreateAndRead: ( test ) => test.expect 3 # store an entry to start with - @db.storeEventPoller @event1id, @event1 + @db.storeEventPoller @event1id, @userId, @event1 # test that the ID shows up in the set @db.getEventPollerIds ( err , obj ) => @@ -349,8 +351,8 @@ exports.EventPoller = test.expect 2 # store an entry to start with - @db.storeEventPoller @event1id, @event1 - @db.storeEventPoller @event1id, @event2 + @db.storeEventPoller @event1id, @userId, @event1 + @db.storeEventPoller @event1id, @userId, @event2 # the retrieved object really is the one we expected @db.getEventPoller @event1id, ( err , obj ) => @@ -367,7 +369,7 @@ exports.EventPoller = test.expect 2 # store an entry to start with - @db.storeEventPoller @event1id, @event1 + @db.storeEventPoller @event1id, @userId, @event1 # Ensure the event poller has been deleted @db.deleteEventPoller @event1id @@ -396,8 +398,8 @@ exports.EventPoller = "Invoker #{ modname } does not equal the expected one" forkEnds() - @db.storeEventPoller @event1id, @event1 - @db.storeEventPoller @event2id, @event2 + @db.storeEventPoller @event1id, @userId, @event1 + @db.storeEventPoller @event2id, @userId, @event2 @db.getEventPollerIds ( err, obj ) => test.ok @event1id in obj and @event2id in obj, 'Not all event poller Ids in set' diff --git a/webpages/handlers/js/admin.js b/webpages/handlers/js/admin.js index d133294..8d7b0aa 100644 --- a/webpages/handlers/js/admin.js +++ b/webpages/handlers/js/admin.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 (function() { var fOnLoad; diff --git a/webpages/handlers/js/error.js b/webpages/handlers/js/error.js index 2bb94fc..c97b3f0 100644 --- a/webpages/handlers/js/error.js +++ b/webpages/handlers/js/error.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 (function() { var fOnLoad; diff --git a/webpages/handlers/js/forge_action_invoker.js b/webpages/handlers/js/forge_action_invoker.js index 7eb1c05..9b1832e 100644 --- a/webpages/handlers/js/forge_action_invoker.js +++ b/webpages/handlers/js/forge_action_invoker.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 (function() { var fOnLoad; diff --git a/webpages/handlers/js/forge_event.js b/webpages/handlers/js/forge_event.js index 90e5936..4951d18 100644 --- a/webpages/handlers/js/forge_event.js +++ b/webpages/handlers/js/forge_event.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 (function() { var fOnLoad; diff --git a/webpages/handlers/js/forge_event_poller.js b/webpages/handlers/js/forge_event_poller.js index c971148..533d9ae 100644 --- a/webpages/handlers/js/forge_event_poller.js +++ b/webpages/handlers/js/forge_event_poller.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 (function() { var fOnLoad; diff --git a/webpages/handlers/js/forge_rule.js b/webpages/handlers/js/forge_rule.js index 57398f4..f43a0a0 100644 --- a/webpages/handlers/js/forge_rule.js +++ b/webpages/handlers/js/forge_rule.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 (function() { var fOnLoad; diff --git a/webpages/handlers/js/login.js b/webpages/handlers/js/login.js index 0f62b66..348fc68 100644 --- a/webpages/handlers/js/login.js +++ b/webpages/handlers/js/login.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.6.3 +// Generated by CoffeeScript 1.7.1 (function() { var fOnLoad;