getjerry / nest-casl

Casl integration for NestJS
MIT License
225 stars 29 forks source link

Injected AccessService is missing permissions (`hasAbility` case) #905

Open graddaniel opened 6 months ago

graddaniel commented 6 months ago

I'm trying to evaluate the permissions in a function using hasAbility method exposed by AccessService. Unfortunately it throws an error ().

I import CaslModule via CaslModule.forFeature({ permissions }).

After a bit of debugging, I've found out, that the AbilityFactory of the AccessService injected to my service is missing the featureOptions, which should contain the permissions. Additionally I see that two AccessService instances are created - one with empty CASL_FEATURE_OPTIONS and one with the permissions passed through forFeature. I've managed to make it work by tinkering a bit, and uncommenting this line of code: https://github.com/getjerry/nest-casl/blob/fcc317d3a1ca3c9851aa20bfa42400d5669d9604/src/casl.module.ts#L35 and commenting out the transpiled equivalend of (I believe) this one: https://github.com/getjerry/nest-casl/blob/fcc317d3a1ca3c9851aa20bfa42400d5669d9604/src/casl.module.ts#L23 effectively replacing the exported AccessService instances, to inject the configured one.

I don't think this is the correct approach.

This is how my service's code looks like (partially):

export class MyService {
  private readonly logger = new Logger(MyService.name);

  constructor(
    @InjectModel(Lender.name) private readonly model: LenderModel,
  ) {
    super(model);
  }

  public async canBeDeleted(myEntity: MyEntity): Promise<{ authorized: boolean }> {
    return {
      authorized: this.accessService.hasAbility(
        this.getCurrentUser(),
        Actions.delete,
        myEntity,
      ),
    };
  }
}

and the module:

@Module({
  imports: [
    // @ts-ignore
    CaslModule.forFeature({ permissions, test: "123" })
  ],
  providers: [MyService],
})
export class MyModule {}

How should I set up CaslModule to make it inject a configured AccessService into my service?