All files / src/services permissions.service.ts

61.11% Statements 22/36
39.28% Branches 11/28
63.63% Functions 7/11
60% Lines 21/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67  7x 7x   7x 7x 7x 7x     7x 7x 7x     7x 7x 7x 7x 7x       33x     2x 2x     2x     2x                                                       2x     7x    
export enum PermissionRole {
  ADMIN = 'admin',
  DOCTOR = 'doctor',
  PATIENT = 'patient',
}
export enum PermissionModel {
  DOCTOR = 'doctor',
  PATIENT = 'patient',
}
 
export enum PermissionVerb {
  CREATE = 'create',
  READ = 'read',
  UPDATE = 'update',
  DELETE = 'delete',
}
 
export type PermissionPayload = Partial<Record<PermissionModel, PermissionVerb[]>>;
 
export class PermissionManager {
  private permissions: PermissionPayload = {};
 
  canPerform(permissionString: string, model: PermissionModel, actions: PermissionVerb[]) {
    this.permissions = this.parse(permissionString);
    if (!this.permissions) {
      return false;
    }
    if (I!this.permissions[model]) {
      return false;
    }
    retuIrn actions.some((action) => this.permissions[model]?.includes(action));
  }
 
  getRolePermissions() {
    return this.permissions || {};
  }

  addPermission(model: PermissionModel, action: PermissionVerb) {
    if (!this.permissions) {
      this.permissions = {};
    }
    if (!this.permissions[model]) {
      this.permissions[model] = [];
    }
    if (!this.permissions[model].includes(action)) {
      this.permissions[model].push(action);
    }
  }
 
  removePermission(model: PermissionModel, action: PermissionVerb) {
    if (this.permissions && this.permissions[model]) {
      const index = this.permissions[model].indexOf(action);
      if (index !== -1) {
        this.permissions[model].splice(index, 1);
      }
    }
  }

  stringify(object: PermissionPayload): string {
    return JSON.stringify(object);
  }
 
  parse(string: string): PermissionPayload {
    return JSON.parse(string) as PermissionPayload;
  }
}