All files / src/components/casbin/lib adapter.ts

13.04% Statements 3/23
0% Branches 0/2
0% Functions 0/10
13.04% Lines 3/23

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 68 69 70 71 72 73 74 75 76 77 78 791x   1x                 1x                                                                                                                                      
import {Adapter, Helper, Model} from 'casbin';
import {BaseEntity} from '../../../models';
import {BaseCrudRepository, RoleRightsRepository} from '../../../repositories';
import {Access, ID} from '../../../types';
 
interface RequestSubjectComp {
  persona_id: number;
  feature_id: number;
  role_id: number;
}
 
export class EnforcerAdapter<M extends BaseEntity> implements Adapter {
  private readonly ptype = 'p';
  private filtered = true;
  private is_role_rights = false;
  private readonly repo: BaseCrudRepository<M, ID>;
 
  constructor(repo: BaseCrudRepository<M, ID>) {
    this.is_role_rights = repo instanceof RoleRightsRepository;
    this.repo = repo;
  }
  savePolicy(model: Model): Promise<boolean> {
    throw new Error('Method not implemented.');
  }
  addPolicy(sec: string, ptype: string, rule: string[]): Promise<void> {
    throw new Error('Method not implemented.');
  }
  removePolicy(sec: string, ptype: string, rule: string[]): Promise<void> {
    throw new Error('Method not implemented.');
  }
  removeFilteredPolicy(
    sec: string,
    ptype: string,
    fieldIndex: number,
    ...fieldValues: string[]
  ): Promise<void> {
    throw new Error('Method not implemented.');
  }
 
  /**
   *
   * @param model
   */
  public async loadPolicy(model: Model): Promise<void> {
    const rules = await this.repo.find();
    this._loadPolicyLines(model, rules as (M & Access & RequestSubjectComp)[]);
  }
 
  private _loadPolicyLines(
    model: Model,
    rules: (M & Access & RequestSubjectComp)[],
  ): void {
    let fn = this._buildPolicyCompany;
    if (this.is_role_rights) {
      fn = this._buildPolicyUser;
    }
    rules.forEach(line => {
      const policy = fn.call(this, line);
      Helper.loadPolicyLine(policy.join(', '), model);
    });
  }
 
  private _buildPolicyCompany(line: M & Access & RequestSubjectComp) {
    return [this.ptype, line.persona_id, line.feature_id];
  }
 
  private _buildPolicyUser(line: M & Access & RequestSubjectComp) {
    const access = [
      line.allow_create,
      line.allow_retrieve,
      line.allow_update,
      line.allow_delete,
      line.allow_validate,
      line.allow_override,
    ];
    return [this.ptype, line.role_id, line.feature_id, ...access];
  }
}