diff --git a/lib/event.js b/lib/event.js index 42dd046..a684816 100644 --- a/lib/event.js +++ b/lib/event.js @@ -2,7 +2,9 @@ * Dependencies */ -var mdoq = require('mdoq'); +var mdoq = require('mdoq') + , vm = require('vm') +; /** * Event handler middleware. @@ -68,6 +70,7 @@ function exec(src, data, req, original) { , errors = {} , serr = sanitize(src) , session = req.session + , ctx = {} ; // original fallback @@ -76,35 +79,39 @@ function exec(src, data, req, original) { // fail on sanitize err if(serr) return {message: serr}; - function error(key, val) { + ctx.error = function(key, val) { errors[key] = val || true; } - function cancel(msg, status) { + ctx.cancel = function(msg, status) { if (!req.isRoot) { state.status = status || 400; throw msg; } } - function hide(property) { + ctx.hide = function(property) { if (!req.isRoot) { delete data[property]; } } - function protect(property) { + ctx.protect = function(property) { if (!req.isRoot) { if(data[property]) data[property] = original[property] || undefined; } } - // wrap with a function - src = 'function(me) {' + src + '}'; + // import session and data + ctx.data = data; + ctx.session = session; + ctx.me = session; + + // wrap with a function and execute with data as the explicit context + src = '(function(me) { ' + src + ' }).call(data, session)'; try { - fn = eval('('+ src +')'); - fn.call(data, session); + vm.runInNewContext(src, ctx, 'event.vm'); } catch(e) { state.status = state.status || 500; if(typeof e == 'string') { @@ -127,7 +134,4 @@ function exec(src, data, req, original) { function sanitize(src) { // must have a body if(!src) return 'Handler must include a body.'; - - // must not contain any functions - //if(src.indexOf('function') > -1) return 'Must not contain any functions.'; }