All files / src/services role.service.ts

20.69% Statements 18/87
0% Branches 0/52
7.69% Functions 1/13
18.82% Lines 16/85

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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 3291x 1x               1x 1x 1x                   1x                     1x     1x     17x   17x   17x   17x   17x   17x   17x   17x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import {bind, /* inject, */ BindingScope} from '@loopback/core';
import {
  DataObject,
  EntityNotFoundError,
  FilterBuilder,
  Options,
  repository,
  Where,
} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {isNull, omit} from 'lodash';
import {BaseService} from '.';
import {RoleRightsDto} from '../dtos';
import {RoleDto} from '../dtos/role.dto';
import {
  BaseResponses,
  Module,
  Role,
  RoleRights,
  RoleWithRelations,
} from '../models';
import {
  FeatureAccessRepository,
  FeatureRepository,
  ModuleRepository,
  RoleRepository,
  RoleRightsRepository,
  RoleViewRepository,
  UserRepository,
} from '../repositories';
import { RoleView } from '@logchain/models/views';
import { exist } from 'should';
import { LogChainConfigs } from '@logchain/configs';
 
@bind({scope: BindingScope.TRANSIENT})
export class RoleService extends BaseService<Role> {
  constructor(
    @repository(RoleRepository)
    public role_repo: RoleRepository,
    @repository(RoleViewRepository)
    public role_view_repo: RoleViewRepository,
    @repository(FeatureRepository)
    public feature_repo: FeatureRepository,
    @repository(ModuleRepository)
    public module_repo: ModuleRepository,
    @repository(RoleRightsRepository)
    public role_rights_repo: RoleRightsRepository,
    @repository(FeatureAccessRepository)
    public feature_access_repo: FeatureAccessRepository,
    @repository(UserRepository)
    public user_repo: UserRepository,
  ) {
    super();
  }
 
  /**
   * Create a new role
   * @param role
   */
  async create(
    role: RoleDto,
  ): Promise<{id: number | undefined; identifier?: string | undefined}> {
    const {role_details} = role;
    if (role_details?.length) {
      const feature_ids = role_details.map(detail => {
        return detail.feature_id;
      });
 
      await this.feature_repo.ensureRecordActive(feature_ids);
    }
 
    const new_role = await this.role_repo.create(omit(role, ['role_details']));
    // create role_details access
    if (role_details?.length) {
      await this._createNewRoleRights(role_details, new_role);
    }
 
    return new_role;
  }
 
  /**
   * Get array roles based on filter.
   * @param filter
   */
  async find(options?: Options): Promise<BaseResponses<RoleView>> {
    const filter_builder = new FilterBuilder<RoleView>();
    filter_builder.filter = this.filter_builder.filter;
    if (options?.is_private) {
      // count total users for private
      filter_builder.include({
        relation: 'users',
        scope: {
          fields: {
            role_id: true,
            status: true,
          },
        },
      });
    } else {
      // only get active roles for public
      this.ensureRightAccessRecord(filter_builder);
    }
 
    return this.role_view_repo.findWithPaging(filter_builder.build());
  }
 
  /**
   * Gets by id or identifier
   * @param id
   * @returns by id or identifier
   */
  async getByIdOrIdentifier(id: string | number): Promise<Role> {
    this.addWhereIdOrIdentifier(id);
    // add modifier
    super._addIncludeModifier(this.filter_builder);
 
    // count total users for private
    this.filter_builder.include({
      relation: 'users',
      scope: {
        fields: {
          role_id: true,
          status: true,
        },
      },
    });
 
    this.filter_builder.include({
      relation: 'role_rights',
      scope: {
        include: [
          {
            relation: 'feature',
            scope: {
              where: {
                status: true,
              },
            },
          },
        ],
      },
    });
 
    // find role.
    const role = await this.role_repo.findOne(this.filter_builder.build());
 
    if (!role) {
      throw new EntityNotFoundError(this.role_repo.entityClass, id);
    }
 
    return role;
  }
 
  /**
   * Get all the features active
   */
  async getFeatures() {
    const filterBuilder = new FilterBuilder<Module>();
    this.ensureRightAccessRecord();
    filterBuilder.include({
      relation: 'features',
    });
    return this.module_repo.findWithPaging(filterBuilder.build());
  }
 
  /**
   * Delete role by id or identifier
   * @param id The role id or identifier
   */
  async deleteByIdOrIdentifier(id: number | string) {
    this.addWhereIdOrIdentifier(id);
    const role = await this.role_repo.findOne(this.filter_builder.build());
 
    if (!role) {
      throw new EntityNotFoundError(this.role_repo.entityClass, id);
    }
 
    if (role.status) {
      throw new HttpErrors.BadRequest("Don't allow delete active role");
    }
 
    const {count: used_by_user} = await this.user_repo.count({
      role_id: role.id,
    });
 
    if (used_by_user) {
      throw new HttpErrors.BadRequest(
        `The role ${role.id} is used by another user.`,
      );
    }
 
    // delete role
    await this.role_repo.deleteAll(this.filter_builder.build().where);
 
    return role;
  }
 
  /**
   * Update role by id or identifier
   * @param id The id or identifier of role
   * @param role The new role info
   * @returns Promise<void>
   */
  async updateByIdOrIdentifier(id: string | number, role: RoleDto) {
    this.addWhereIdOrIdentifier(id);
 
    const current_role = await this.role_repo.findOne(
      this.filter_builder.build(),
    );
 
    const old_company_id = current_role?.company_id;
    const new_company_id = role.company_id;
 
    if (!current_role) {
      throw new EntityNotFoundError(this.role_repo.entityClass, id);
    }
 
    const {role_details} = role;
    if (role_details?.length) {
      const feature_ids = role_details.map(detail => {
        return detail.feature_id;
      });
 
      await this.feature_repo.ensureRecordActive(feature_ids);
 
      // remove all current roles rights
      await this.role_rights_repo.deleteAll({
        role_id: current_role.id,
      });
 
      await this._createNewRoleRights(role_details, current_role);
    }
 
    await this.role_repo.updateById(
      current_role.id,
      omit(role, ['role_details']),
    );
 
    // Process the role rights when switching from public to private
    if (old_company_id === 0 && new_company_id !== 0) {
      // If the role is being changed to private, remove all users from current role
      await this.user_repo.updateAll(
        { role_id: 0 },
        { role_id: current_role.id, company_id: { neq: new_company_id }},
      );
    }
 
    return current_role;
  }
 
  /**
   * Create new role rights for a given role
   * @param role_details The new role rights
   * @param current_role The current role
   */
  private async _createNewRoleRights(
    role_details: RoleRightsDto[],
    current_role: RoleWithRelations,
  ) {
    const bulk_data: DataObject<RoleRights>[] = [];
    role_details.forEach(detail => {
      bulk_data.push({
        feature_id: detail.feature_id,
        role_id: current_role.id,
        allow_create: detail.create,
        allow_retrieve: detail.retrieve,
        allow_update: detail.update,
        allow_delete: detail.delete,
        allow_validate: detail.validate,
        allow_override: detail.override,
      });
    });
 
    return this.role_rights_repo.createAll(bulk_data);
  }
 
  /**
   * Ensure get active record
   * @protected
   * @param filterBuilder The FilterBuilder
   * @param id The id or identifier
   */
  public ensureRightAccessRecord(filter_builder?: FilterBuilder): void {
    const _where: Where = {
      status: true,
      private: false,
    };
    if (this.current_user.id !== LogChainConfigs.LogChainRootAdminId) {
      _where.or = [
        {
          company_id: this.current_user?.company_id,
        },
        {
          company_id: null,
        },
        {
          company_id: 0,
        },
      ];
    }
    
    if (filter_builder) {
      filter_builder.impose(_where);
    } else {
      this.filter_builder.impose(_where);
    }
  }
 
  /**
   * Builds the query for role.
   * @param q The query string.
   */
  async buildSearchQuery(q?: string) {
    if (!q) {
      return;
    }
 
    const ilike_value = this.buildILikeValue(q);
    // FIlTER: name Should be a LIKE search
    this.filter_builder.impose({
      or: [
        {
          name: ilike_value,
        },
      ],
    });
  }
}