Hello, I have the following case.
My subject Post has the following date:
The update rules are:
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?
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