Last active
September 10, 2021 06:30
-
-
Save minhntm/119f498827c8209f2ec5a38f2f0efc25 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Ability } from "@casl/ability"; | |
export enum PermissionAction { | |
CREATE = "create", | |
READ = "read", | |
UPDATE = "update", | |
DELETE = "delete", | |
} | |
export type PermissionObjectType = any; | |
export type AppAbility = Ability<[PermissionAction, PermissionObjectType]>; | |
interface CaslPermission { | |
action: PermissionAction; | |
// In our database, Invoice, Project... are called "object" | |
// but in CASL they are called "subject" | |
subject: string; | |
} | |
@Injectable() | |
export class CaslAbilityFactory { | |
constructor(private authoService: AuthzService) {} | |
async createForUser(user: User): Promise<AppAbility> { | |
const dbPermissions: Permission[] = await this.authoService.findAllPermissionsOfUser(user); | |
const caslPermissions: CaslPermission[] = dbPermissions.map(p => ({ | |
action: p.action, | |
subject: p.permissionObject.name, | |
})); | |
return new Ability<[PermissionAction, PermissionObjectType]>(caslPermissions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment