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

Custom subjectName function does not work with instance check #6

Closed
claustres opened this issue Aug 1, 2017 · 2 comments
Closed

Custom subjectName function does not work with instance check #6

claustres opened this issue Aug 1, 2017 · 2 comments
Labels

Comments

@claustres
Copy link

Observed behaviour

Checking permission on creating a specific instance fails although the ability to create any object on the subject has been declared:

const { rules, can } = AbilityBuilder.extract()
can('create', 'users')
let ability = new Ability(rules, { subjectName: resource => resource.type })
// This logs false while it should log true
console.log(ability.can('create', {type : 'users'}))

Expected behaviour

Because creating any object on subject 'users' is allowed it should be allowed whatever the given instance to check.

Suspected faulty code

Ability.can() call the custom function to retrieve the subjectName (https://github.com/stalniy/casl/blob/master/src/ability.js#L91) but then perform an internal call to rulesFor() with the subjectName instead of the subject itself, leading to a bug when the custom function is called again (https://github.com/stalniy/casl/blob/master/src/ability.js#L108)

@stalniy
Copy link
Owner

stalniy commented Aug 1, 2017

Thanks for the issue but it's currently expected behavior. subjectName function should properly work for cases when resource is undefined, null or string.

You can check built-in implementation for details:
https://github.com/stalniy/casl/blob/master/src/ability.js#L4

So, you need to convert your function to this:

let ability = new Ability(rules, { subjectName: resource => resource && typeof resource === 'object' ? resource.type : resource })

@claustres
Copy link
Author

Works fine now, thanks. I suggest to add a reminder in the doc explaining this behaviour is actually mandatory. At a first glance I believed it was specific to your examples.

stalniy added a commit that referenced this issue Aug 2, 2017
…ed one

Also updates documentation related to `subjectName` option

Relates to #6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants