|
| 1 | +import type { PureAbility } from '@casl/ability' |
| 2 | +import { AbilityBuilder } from '@casl/ability' |
| 3 | +import type { PrismaQuery, Subjects } from '@casl/prisma' |
| 4 | +import { createPrismaAbility } from '@casl/prisma' |
| 5 | +import { Injectable } from '@nestjs/common' |
| 6 | +import type { Project, Environment, User, ProjectMembers } from '@prisma/client' |
| 7 | + |
| 8 | +export type AppAbility = PureAbility< |
| 9 | + [string, Subjects<{ Project: Project, Environment: Environment, User: User, ProjectMembers: ProjectMembers }>], |
| 10 | + PrismaQuery |
| 11 | +> |
| 12 | + |
| 13 | +@Injectable() |
| 14 | +export class CaslAbilityFactory { |
| 15 | + createForUser(user: any) { |
| 16 | + const { can, build } = new AbilityBuilder<AppAbility>( |
| 17 | + createPrismaAbility, |
| 18 | + ) |
| 19 | + |
| 20 | + // If user is not authenticated or doesn't have an ID |
| 21 | + if (!user || !user.sub) { |
| 22 | + return build() |
| 23 | + } |
| 24 | + |
| 25 | + const userId = user.sub |
| 26 | + |
| 27 | + // A user can read projects they are a member of (via ProjectMembers) |
| 28 | + can('read', 'Project', { |
| 29 | + members: { |
| 30 | + some: { |
| 31 | + userId, |
| 32 | + }, |
| 33 | + }, |
| 34 | + }) |
| 35 | + |
| 36 | + // A project owner can manage everything |
| 37 | + can('manage', 'Project', { |
| 38 | + ownerId: userId, |
| 39 | + }) |
| 40 | + |
| 41 | + // A user can update an environment if the project is not locked |
| 42 | + // and they are a member of the project |
| 43 | + can('update', 'Environment', { |
| 44 | + project: { |
| 45 | + is: { |
| 46 | + locked: false, |
| 47 | + members: { |
| 48 | + some: { |
| 49 | + userId, |
| 50 | + }, |
| 51 | + }, |
| 52 | + }, |
| 53 | + }, |
| 54 | + }) |
| 55 | + |
| 56 | + return build() |
| 57 | + } |
| 58 | +} |
0 commit comments