getjerry / nest-casl

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

Bug when using a condition on read permission #866

Closed softimiz closed 8 months ago

softimiz commented 8 months ago

Hey @liquidautumn,

Thanks for your work on this lib!

I get the following error when trying to restrict a Get User/:id route access to let the user access only his infos. FYI, restriction works fine if using a patch/put route.

Could it be caused by an empty request.body from a Get request?

"message": "Cannot convert undefined or null to object", "stack": at AccessService.isThereAnyFieldRestriction (C:\dev\engine-api\node_modules\nest-casl\src\access.service.ts:140:46) at AccessService.canActivateAbility (C:\dev\engine-api\node_modules\nest-casl\src\access.service.ts:119:42)

Permission file:

export const userPermissions: Permissions<Role, Subjects, Actions> = {
    user({ user, can, cannot }) {
        can(Actions.read, User, { id: user.id }); // This case is causing the exception
        can(Actions.update, User, { id: user.id }); // This case works fine
        cannot(Actions.delete, User);
    },

    sentry({ extend, can }) {
        extend(Role.User);
        can(Actions.delete, User);
    },
};

Hook file

@Injectable()
export class UserSubjectHook implements SubjectBeforeFilterHook<User, Request> {
    constructor(readonly userService: UserService) {}

    async run({ params }: Request): Promise<User> {
        return this.userService.getById(params.id);
    }
}

Problematic Controller route:

    @Get(':id')
    @UseAbility(Actions.read, User, UserSubjectHook)
    @UsePipes(ParseUUIDPipe)
    async getOne(@Param('id') id: string) {
        const entity = await this.userService.getById(id);

        const getUserResponse: GetUserResponse = {
            id: entity.id,
            email: entity.email,
            roles: entity.roles,
        };

        return getUserResponse;
    }
liquidautumn commented 8 months ago

@softimiz I ran few test cases and couldn't see this error, it seems there is more to it. Could you please provide quick reproduction?

liquidautumn commented 8 months ago

@softimiz fixed in 1.9.3

softimiz commented 8 months ago

Thank you very much @liquidautumn 😄 Sorry I wasn't able to give you a reproduction sandbox in time. Your dedication truly makes a difference for the community.