Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added customMiddleware #239

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions lib/acl.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down