diff --git a/lib/acl.js b/lib/acl.js index 9851717..4f46bbc 100644 --- a/lib/acl.js +++ b/lib/acl.js @@ -711,6 +711,74 @@ Acl.prototype.middleware = function(numPathComponents, userId, actions){ }; }; +Acl.prototype.customMiddleware = function (userId, actions, resource) { + contract(arguments) + .params('string|number|function', 'string|array','string|array') + .end() + + var acl = this + + function HttpError (errorCode, msg) { + this.errorCode = errorCode + this.message = msg + this.name = this.constructor.name + + Error.captureStackTrace(this, this.constructor) + this.constructor.prototype.__proto__ = Error.prototype + } + + return function (req, res, next) { + var _userId = userId, + _actions = actions, + _resource = resource, + url + // call function to fetch userId + if (typeof userId === 'function') { + _userId = userId(req, res) + } + if (!userId) { + if ((req.session) && (req.session.userId)) { + _userId = req.session.userId + }else if ((req.user) && (req.user.id)) { + _userId = req.user.id + }else { + next(new HttpError(401, 'User not authenticated')) + return + } + } + + // Issue #80 - Additional check + if (!_userId) { + next(new HttpError(401, 'User not authenticated')) + return + } + + if (!_actions) { + _actions = req.method.toLowerCase() + } + + acl.logger ? acl.logger.debug('Requesting ' + _actions + ' on ' + _resource + ' by user ' + _userId) : null + + acl.isAllowed(_userId, _resource, _actions, function (err, allowed) { + if (err) { + console.log(err) + next(new Error('Error checking permissions to access resource')) + }else if (allowed === false) { + if (acl.logger) { + acl.logger.debug('Not allowed ' + _actions + ' on ' + _resource + ' by user ' + _userId) + acl.allowedPermissions(_userId, _resource, function (err, obj) { + acl.logger.debug('Allowed permissions: ' + util.inspect(obj)) + }) + } + next(new HttpError(403, 'Insufficient permissions to access resource')) + }else { + acl.logger ? acl.logger.debug('Allowed ' + _actions + ' on ' + _resource + ' by user ' + _userId) : null + next() + } + }) + } +} + /** Error handler for the Express middleware