'How to use ForcedSubject in CASL
I am following CASL's cookbook on implementing authorization for roles with predfined permissions (see here) and I am blocked when I try to check abilities for a user.
I do not understand how ForcedSubject is meant to be used. I do not which to use classes or interfaces to define my subjects so I therefore rely on strings. However, all my subjects do contain a id property and I want the ability to check permissions with conditionals on that ID. Bellow is a simplified version of what I implemented.
import { Ability, AbilityClass, ForcedSubject } from '@casl/ability';
type OrgActions =
| 'manage'
| 'invite-user';
type SubjectWithId = { id: string };
type MyAbilities =
| ['manage', 'all']
| [OrgActions, 'organization' | ForcedSubject<SubjectWithId>];
export type MyAbility = Ability<MyAbilities>;
export const MyAbility = Ability as AbilityClass<MyAbility>;
const builder = new AbilityBuilder(PlatformAbility)
builder.can('invite-user', 'organization', { id: 'abcd' })
const ability = builder.build()
ability.can('invite-user', 'organization') // No problem here
ability.can('invite-user', subject('organization', { id: 'abcd' }) // Typing Error!
Here is the typing error I get.
Argument of type '["invite-user", { id: string; } & ForcedSubject<"organization">]' is not assignable to parameter of type '[action: "manage", subject: "all", field?: string | undefined] | [action: OrgActions, subject: "organization" | ForcedSubject<SubjectWithId>, field?: string | undefined]'.
Type '["invite-user", { id: string; } & ForcedSubject<"organization">]' is not assignable to type '[action: OrgActions, subject: "organization" | ForcedSubject<SubjectWithId>, field?: string | undefined]'.
Type at position 1 in source is not compatible with type at position 1 in target.
Type '{ id: string; } & ForcedSubject<"organization">' is not assignable to type '"organization" | ForcedSubject<SubjectWithId>'.
Type '{ id: string; } & ForcedSubject<"organization">' is not assignable to type 'ForcedSubject<SubjectWithId>'.
Types of property '__caslSubjectType__' are incompatible.
Type 'string' is not assignable to type 'SubjectWithId'.ts(2345)
I do not understand how the ForceSubject type is supposed to be used if not with the subject helper like I did.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
