permissions.model.ts 2.36 KB
/**
 * Created by tuukka on 22/09/18.
 */


class PermissionFields {
  USER = false;
  INFO = false;
  ADMIN = false;
}

export class Permissions {
  static referencePermission = new Permissions();



  VIPLIST: PermissionFields = new PermissionFields();
  BILLING: PermissionFields = new PermissionFields();
  SITE: PermissionFields = new PermissionFields();
  SHOP: PermissionFields = new PermissionFields();
  POLL: PermissionFields = new PermissionFields();
  INVITE: PermissionFields = new PermissionFields();
  MAP: PermissionFields = new PermissionFields();
  COMPO: PermissionFields = new PermissionFields();
  FOOD: PermissionFields = new PermissionFields();
  USER: PermissionFields = new PermissionFields();
  TOURNAMENT: PermissionFields = new PermissionFields();
  CREDIT: PermissionFields = new PermissionFields();
  LECTURE: PermissionFields = new PermissionFields();

  constructor() {
  }



  /**
   *
   * Returns function, which will check user permissions against desired roles.
   *
   * Returned function can be used as a permission checked.
   *
   *
   * @param requiredPermissions Permissions which are allowed. Example: {VIPLIST: 'ADMIN', BILLING: 'INFO'}
   * @constructor
   */
  static GeneratePermissionFunction(allowedPermissions: any): ((permissions: Permissions) => boolean) {

    // no defines, always true
    if (!allowedPermissions) {
      return function (permissions: Permissions): boolean {
        return true;
      };
    }

    // Check if all permissions exists
    // Think this as a runtime typecheck
    for (const target in allowedPermissions) {

      if (!allowedPermissions.hasOwnProperty(target)) {
        continue;
      }

      if (!(target in Permissions.referencePermission)) {
        throw Error('Invalid permission key ' + target);
      }

      switch (allowedPermissions[target]) {
        default:
          throw Error('Invalid permission role ' + allowedPermissions[target]);
        case 'ADMIN':
        case 'INFO':
        case 'USER':
      }
    }


    return function (permissions: Permissions): boolean {

      // Go trought allowed permissions. If permissions contains allowed permission, return true.
      for (const target in allowedPermissions) {
        if (permissions[target][allowedPermissions[target]]) {
          return true;
        }
      }

      // no permission found, return false
      return false;
    };
  }
}