All files / src/tools/auth0/handlers roles.ts

89.15% Statements 74/83
75% Branches 36/48
83.33% Functions 20/24
89.87% Lines 71/79

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 2221x 1x 1x     1x                                             1x       139x               2x 2x   2x   2x             2x       2x       2x   2x 2x                   1x       1x       1x       1x   1x 1x                           1x 1x     1x 1x   1x 1x   1x   1x 1x     1x 1x     1x       1x       1x   1x 1x                   11x         11x       11x 11x 8x 7x         7x 155x 155x 155x 155x     7x   8x 8x   3x 2x   1x         1x 3x   3x   3x   3x             3x     3x         3x 9x 9x   1x 1x   2x 2x   1x 1x   5x            
import DefaultHandler, { order } from './default';
import { calculateChanges } from '../../calculateChanges';
import log from '../../../logger';
import { Asset, Assets, CalculatedChanges } from '../../../types';
 
export const schema = {
  type: 'array',
  items: {
    type: 'object',
    properties: {
      name: { type: 'string' },
      id: { type: 'string' },
      description: { type: 'string' },
      permissions: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            permission_name: { type: 'string' },
            resource_server_identifier: { type: 'string' },
          },
        },
      },
    },
    required: ['name'],
  },
};
 
export default class RolesHandler extends DefaultHandler {
  existing: Asset[];
 
  constructor(config: DefaultHandler) {
    super({
      ...config,
      type: 'roles',
      id: 'id',
    });
  }
 
  async createRole(data): Promise<Asset> {
    const role = { ...data };
    delete role.permissions;
 
    const created = await this.client.roles.create(role);
 
    Iif (typeof data.permissions !== 'undefined' && data.permissions.length > 0) {
      await this.client.roles.permissions.create(
        { id: created.id },
        { permissions: data.permissions }
      );
    }
 
    return created;
  }
 
  async createRoles(creates: CalculatedChanges['create']): Promise<void> {
    await this.client.pool
      .addEachTask({
        data: creates || [],
        generator: (item) =>
          this.createRole(item)
            .then((data) => {
              this.didCreate(data);
              this.created += 1;
            })
            .catch((err) => {
              throw new Error(`Problem creating ${this.type} ${this.objString(item)}\n${err}`);
            }),
      })
      .promise();
  }
 
  async deleteRole(data) {
    await this.client.roles.delete({ id: data.id });
  }
 
  async deleteRoles(dels: CalculatedChanges['del']): Promise<void> {
    Eif (
      this.config('AUTH0_ALLOW_DELETE') === 'true' ||
      this.config('AUTH0_ALLOW_DELETE') === true
    ) {
      await this.client.pool
        .addEachTask({
          data: dels || [],
          generator: (item) =>
            this.deleteRole(item)
              .then(() => {
                this.didDelete(item);
                this.deleted += 1;
              })
              .catch((err) => {
                throw new Error(`Problem deleting ${this.type} ${this.objString(item)}\n${err}`);
              }),
        })
        .promise();
    } else {
      log.warn(`Detected the following roles should be deleted. Doing so may be destructive.\nYou can enable deletes by setting 'AUTH0_ALLOW_DELETE' to true in the config
      \n${dels.map((i) => this.objString(i)).join('\n')}`);
    }
  }
 
  async updateRole(data, roles) {
    const existingRole = await roles.find(
      (roleDataForUpdate) => roleDataForUpdate.name === data.name
    );
 
    const params = { id: data.id };
    const newPermissions = data.permissions;
 
    delete data.permissions;
    delete data.id;
 
    await this.client.roles.update(params, data);
 
    Eif (typeof existingRole.permissions !== 'undefined' && existingRole.permissions.length > 0) {
      await this.client.roles.permissions.delete(params, { permissions: existingRole.permissions });
    }
 
    Eif (typeof newPermissions !== 'undefined' && newPermissions.length > 0) {
      await this.client.roles.permissions.create(params, { permissions: newPermissions });
    }
 
    return params;
  }
 
  async updateRoles(updates: CalculatedChanges['update'], roles) {
    await this.client.pool
      .addEachTask({
        data: updates || [],
        generator: (item) =>
          this.updateRole(item, roles)
            .then((data) => {
              this.didUpdate(data);
              this.updated += 1;
            })
            .catch((err) => {
              throw new Error(`Problem updating ${this.type} ${this.objString(item)}\n${err}`);
            }),
      })
      .promise();
  }
 
  async getType() {
    Iif (this.existing) {
      return this.existing;
    }
 
    // in case client version does not support roles
    Iif (!this.client.roles || typeof this.client.roles.getAll !== 'function') {
      return [];
    }
 
    try {
      const roles = await this.client.roles.getAll({ paginate: true, include_totals: true });
      for (let index = 0; index < roles.length; index++) {
        const permissions = await this.client.roles.permissions.getAll({
          paginate: true,
          include_totals: true,
          id: roles[index].id,
        });
        const strippedPerms = await Promise.all(
          permissions.map(async (permission) => {
            delete permission.resource_server_name;
            delete permission.description;
            return permission;
          })
        );
        roles[index].permissions = strippedPerms;
      }
      this.existing = roles;
      return this.existing;
    } catch (err) {
      if (err.statusCode === 404 || err.statusCode === 501) {
        return [];
      }
      throw err;
    }
  }
 
  @order('60')
  async processChanges(assets: Assets): Promise<void> {
    const { roles } = assets;
    // Do nothing if not set
    Iif (!roles) return;
    // Gets roles from destination tenant
    const existing = await this.getType();
 
    const changes = calculateChanges({
      handler: this,
      assets: roles,
      existing,
      identifiers: this.identifiers,
      allowDelete: !!this.config('AUTH0_ALLOW_DELETE'),
    });
    log.debug(
      `Start processChanges for roles [delete:${changes.del.length}] [update:${changes.update.length}], [create:${changes.create.length}]`
    );
    const myChanges = [
      { del: changes.del },
      { create: changes.create },
      { update: changes.update },
    ];
    await Promise.all(
      myChanges.map(async (change) => {
        switch (true) {
          case change.del && change.del.length > 0:
            Eif (change.del) await this.deleteRoles(change.del);
            break;
          case change.create && change.create.length > 0:
            await this.createRoles(changes.create); //TODO: fix this tho change.create
            break;
          case change.update && change.update.length > 0:
            Eif (change.update) await this.updateRoles(change.update, existing);
            break;
          default:
            break;
        }
      })
    );
  }
}