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

Combined abilities not working as expected #123

Closed
silvanaweb opened this issue Oct 25, 2018 · 2 comments
Closed

Combined abilities not working as expected #123

silvanaweb opened this issue Oct 25, 2018 · 2 comments
Labels

Comments

@silvanaweb
Copy link

Hello, I have the following case.

My subject Post has the following date:

  • address: {postCode: string, street: string }
  • personalInfo: { ownerId: string, otherInfo: string}

The update rules are:

  • 'address' can be updated by all
  • 'personalInfo' can be updated only by the user that has created the Post

When I define my ability I do:

const ability = AbilityBuilder.define((can: any) => {
        can("update", "Post", ["personalInfo"], { "personalInfo.ownerId":user.id });
        can("update", "Post", ["address"]);
    });

I am using this ability inside my Mongoose query :

const doc = Post.accessibleBy(ability, 'update)...

The expected result is that if another user try to update personalInfo , it should be not allowed to do it.
The actual result is that all can update every field.

Am I doing anything wrong?

@stalniy
Copy link
Owner

stalniy commented Oct 26, 2018

The issue is that you define abilities which intersects. One says everybody can update Post another one says only owners can do that. Post.accessibleBy doesn't filter results on field basis but instead on subject basis.

So, how can you do what you want to do:

const post = await Post.accessibleBy(ability, 'update')...

if (ability.can('update', post, 'personalInfo')) {
   ...
}

if (ability.can('update', post, 'address')) {
   ...
}

Alternatively, you can extract updatable fields based on ability:

const pick = require('lodash/pick')

const post = await Post.accessibleBy(ability, 'update')...
const fields = post.accessibleFieldsBy(ability, 'update')
const attrsToUpdate = pick(req.body, fields)

post.set(attrsToUpdate)
await post.save()

@stalniy
Copy link
Owner

stalniy commented Oct 26, 2018

You can read about this in this section: https://github.com/stalniy/casl/tree/master/packages/casl-mongoose#permitted-fields-plugin

Note: permittedFieldsBy is deprecated, it was renamed to accessibleFieldsBy for consistency. I didn't have time to update docs. Plan to do this in few weeks

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