|
| 1 | +import { AbilityBuilder } from '@casl/ability'; |
| 2 | +import { createPrismaAbility } from '@casl/prisma'; |
| 3 | +import { LoggingService } from '@douglasneuroinformatics/libnest'; |
| 4 | +import { Injectable } from '@nestjs/common'; |
| 5 | +import type { TokenPayload } from '@opendatacapture/schemas/auth'; |
| 6 | + |
| 7 | +import { createAppAbility, detectAppSubject } from './ability.utils'; |
| 8 | + |
| 9 | +import type { AppAbility, Permission } from './auth.types'; |
| 10 | + |
| 11 | +@Injectable() |
| 12 | +export class AbilityFactory { |
| 13 | + constructor(private readonly loggingService: LoggingService) {} |
| 14 | + |
| 15 | + createForPayload(payload: Omit<TokenPayload, 'permissions'>): AppAbility { |
| 16 | + this.loggingService.verbose({ |
| 17 | + message: 'Creating Ability From Payload', |
| 18 | + payload |
| 19 | + }); |
| 20 | + const ability = new AbilityBuilder<AppAbility>(createPrismaAbility); |
| 21 | + const groupIds = payload.groups.map((group) => group.id); |
| 22 | + switch (payload.basePermissionLevel) { |
| 23 | + case 'ADMIN': |
| 24 | + ability.can('manage', 'all'); |
| 25 | + break; |
| 26 | + case 'GROUP_MANAGER': |
| 27 | + ability.can('manage', 'Assignment', { groupId: { in: groupIds } }); |
| 28 | + ability.can('manage', 'Group', { id: { in: groupIds } }); |
| 29 | + ability.can('read', 'Instrument'); |
| 30 | + ability.can('create', 'InstrumentRecord'); |
| 31 | + ability.can('read', 'InstrumentRecord', { groupId: { in: groupIds } }); |
| 32 | + ability.can('create', 'Session'); |
| 33 | + ability.can('read', 'Session', { groupId: { in: groupIds } }); |
| 34 | + ability.can('create', 'Subject'); |
| 35 | + ability.can('read', 'Subject', { groupIds: { hasSome: groupIds } }); |
| 36 | + ability.can('read', 'User', { groupIds: { hasSome: groupIds } }); |
| 37 | + break; |
| 38 | + case 'STANDARD': |
| 39 | + ability.can('read', 'Group', { id: { in: groupIds } }); |
| 40 | + ability.can('read', 'Instrument'); |
| 41 | + ability.can('create', 'InstrumentRecord'); |
| 42 | + ability.can('read', 'Session', { groupId: { in: groupIds } }); |
| 43 | + ability.can('create', 'Session'); |
| 44 | + ability.can('create', 'Subject'); |
| 45 | + ability.can('read', 'Subject', { groupIds: { hasSome: groupIds } }); |
| 46 | + break; |
| 47 | + } |
| 48 | + payload.additionalPermissions?.forEach(({ action, subject }) => { |
| 49 | + ability.can(action, subject); |
| 50 | + }); |
| 51 | + return ability.build({ |
| 52 | + detectSubjectType: detectAppSubject |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + createForPermissions(permissions: Permission[]): AppAbility { |
| 57 | + this.loggingService.verbose({ |
| 58 | + message: 'Creating Ability From Permissions', |
| 59 | + permissions |
| 60 | + }); |
| 61 | + return createAppAbility(permissions); |
| 62 | + } |
| 63 | +} |
0 commit comments