Skip to content

Commit

Permalink
feat: can check can take additional params passed to rule eval
Browse files Browse the repository at this point in the history
E.g. `user.can('eat', apple, {extra: 'worm'})`
  • Loading branch information
mblarsen committed Oct 20, 2017
1 parent 22c134a commit 981b3f2
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ the mixin:
- `user` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `verb` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `subject` **([Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) \| [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) \| [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String))**
- `args` **...any** Any other param is passed into rule

Returns **any** Boolean

Expand Down
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,10 @@ class Acl {
* @param {Object} user
* @param {string} verb
* @param {Function|Object|string} subject
* @param {...*} args Any other param is passed into rule
* @return Boolean
*/
can(user, verb, subject) {
can(user, verb, subject, ...args) {
const subjectName = this.subjectMapper(subject)
let rules = this.policies.get(subjectName) || this.rules.get(subjectName)

Expand All @@ -118,7 +119,7 @@ class Acl {
}

if (typeof rules[verb] === 'function') {
return Boolean(rules[verb](user, subject, subjectName))
return Boolean(rules[verb](user, subject, subjectName, ...args))
}

if (this.strict && typeof rules[verb] === 'undefined') {
Expand Down
11 changes: 11 additions & 0 deletions test/Acl.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ describe('The basics', () => {
const user = new User()
expect(user.can('eat', new Apple())).toBe(true)
})

test('Can eat apples (params)', () => {
const acl = new Acl()
acl.mixin(User)
acl.rule(['eat'], Apple, function (user, apple, _, param) {
expect(param).toBe('worm')
return true
})
const user = new User()
expect(user.can('eat', new Apple(), 'worm')).toBe(true)
})
})

describe('Strict mode', () => {
Expand Down

0 comments on commit 981b3f2

Please sign in to comment.