How to use CASL Prisma to implement field access restrictions?

113 Views Asked by At

I try to implement field level access restriction using CASL.

I get this code from CASL documentation. I can get the entity level access, but not able to access the field level restriction.

Sample code is below.

Ability factory is below:

type AppAbility = PureAbility<
  [
    string,
    Subjects<{
      User: User;
      Post: Post;
    }>,
  ],
  PrismaQuery
>;

const { can, cannot, build } = new AbilityBuilder<AppAbility>(
  createPrismaAbility,
);
cannot('update', 'Post');
cannot('read', 'Post', { authorId: { not: 1 } });
can('delete', 'Post').because('No access to delete a Post!!!');
can('update', 'Post').because('No access to update a Post!!!');
can('create', 'Post').because('No access to create a Post!!!');
//cannot('read', 'Post', { title: { startsWith: 'W' } });

export const ability = build();

Service is below:

async findAll() {
    try {
      this.Database.post.findMany({
        where: {
          AND: [accessibleBy(ability).Post, { id: 1 }],
        },
      });
      return this.Database.post.findMany();
    } catch (error) {
      if (error instanceof ForbiddenError) {
        throw new ForbiddenException(error.message);
      }
    }
  }

0

There are 0 best solutions below