When not providing any rule for a given subject in CASL checking an ability for this subject always returns false.
E.g.
import { Ability } from '@casl/ability';
const ability = new Ability({
action: "read", subject: "FirstSubject",
// no rule for SecondSubject
});
ability.can("read", "FirstSubject"); // true
ability.can("write", "FirstSubject"); // false
ability.can("read", "SecondSubject"); // false <-- These two lines should
ability.can("write", "SecondSubject"); // false <-- return `true`
Is it possible to change this behavior in a way that the ability returns true for subjects that do not have any rules?
In my use case I have a very large amount of subjects and new ones can be added dynamically.
It would be difficult to always having to add { action: "manage", subject: "NewSubject"} whenever a new subject is added.
I would rather like to only add rules for subjects where something is actually restricted.
According to a chat with the author of CASL it is not possible to achieve this.
here is a way to do that:
import {Ability} from '@casl/ability';
class AppAbility extends Ability {
relevantRuleFor (action, subject, field, allowNotDefinedRule) {
const rule = super.relevantRuleFor(action, subject, field);
if (!rule && allowNotDefinedRule) {
return {inverted: false};
}
return rule;
}
}
export const ability = new AppAbility([]);
Then you can use it like that:
ability.can('read', 'Post', undefined, true);
Pls note, that you componont will not work correct because in the sorces it has this code that has private modificator:
private _canRender () {
const props = this.props;
const subject = props.of || props.a || props.an || props.this || props.on;
const can = props.not ? 'cannot' : 'can';
return props.ability[can](props.I || props.do, subject, props.field);
}
In that case you need to create your own component.