Casl: Combined abilities not working as expected

Created on 25 Oct 2018  路  2Comments  路  Source: stalniy/casl

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?

question

All 2 comments

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()

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

Was this page helpful?
0 / 5 - 0 ratings