Advertisement
ynhhoJ

index.ts

May 5th, 2021
1,036
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Roles from './roles';
  2.  
  3. interface RolesData {
  4.   name: string;
  5.   permissions?: Array<string>;
  6. }
  7.  
  8. class RBAC {
  9.   private roles: Array<Roles>;
  10.  
  11.   constructor() {
  12.     this.roles = [];
  13.   }
  14.  
  15.   blockPermission(name: string): void {
  16.  
  17.   }
  18.  
  19.   can(roleName: string, permission: string): boolean {
  20.     const roleResult = this.getRole(roleName);
  21.  
  22.     return !!roleResult?.permissions.find((role) => role === permission);
  23.   }
  24.  
  25.   createRole(name: string, permission: Array<string> = []): Roles {
  26.     const role = new Roles(name, permission);
  27.  
  28.     this.roles.push(role);
  29.  
  30.     return role;
  31.   }
  32.  
  33.   createRoles(rolesData: RolesData[]): void {
  34.     rolesData.forEach((role) => {
  35.       this.createRole(role.name, role.permissions);
  36.     });
  37.   }
  38.  
  39.   getRole(name: string): Roles | undefined {
  40.     return this.roles.find((role) => role.name === name);
  41.   }
  42.  
  43.   getRoles(): Array<string> {
  44.     const roles: Array<string> = [];
  45.  
  46.     this.roles.forEach((role) => {
  47.       roles.push(role.name);
  48.     });
  49.  
  50.     return roles;
  51.   }
  52.  
  53.   hasPermission(permission: string): boolean {
  54.     return this.roles.some((role) => role.permissions.find((access) => access === permission));
  55.   }
  56.  
  57.   hasRole(name: string): boolean {
  58.     return !!this.getRole(name);
  59.   }
  60.  
  61.   removeRole(name: string): void {
  62.     this.roles = this.roles.filter((role) => role.name !== name);
  63.   }
  64. }
  65.  
  66. export default RBAC;
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement