# All files / modules/rbac/services rbac.service.ts

80.37% Statements 86/107
76.19% Branches 16/21
68.96% Functions 20/29
81.72% Lines 76/93

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
    329
    330
    331
    332
    333
    334
    3355x

    5x
    5x
    5x

    5x

    26x

    26x

    26x

    26x

    2x

    2x
    1x

    1x

    1x

    1x
    1x

    1x

    3x

    3x
    1x

    2x
    1x

    1x
    1x

    1x

    1x

    1x

    4x

    4x
    1x

    3x
    1x

    2x

    2x
    1x

    1x

    1x

    1x

    6x

    6x
    2x

    4x

    1x

    1x

    1x

    1x

    1x

    1x
    1x

    1x

    3x

    2x

    2x
    1x

    1x

    1x

    2x

    2x
    1x

    8x

    8x
    3x

    5x

    5x

    4x

    4x
    1x

    3x

    3x

    3x

    3x

    3x

    2x
    2x

    2x
    2x

     import {
      Injectable,
      NotFoundException,
      ConflictException,
      ForbiddenException,
    } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository, In } from 'typeorm';
    import { Role, Permission, UserRole, RolePermission } from '../entities';
    import { CreateRoleDto, UpdateRoleDto, AssignRoleDto } from '../dto';

    @Injectable()
    export class RbacService {
      constructor(
        @InjectRepository(Role)
        private readonly roleRepository: Repository<Role>,
        @InjectRepository(Permission)
        private readonly permissionRepository: Repository<Permission>,
        @InjectRepository(UserRole)
        private readonly userRoleRepository: Repository<UserRole>,
        @InjectRepository(RolePermission)
        private readonly rolePermissionRepository: Repository<RolePermission>,
      ) {}

      // ==================== Roles ====================

      async createRole(dto: CreateRoleDto, tenantId: string): Promise<Role> {
        // Check if code already exists for tenant
        const existing = await this.roleRepository.findOne({
          where: { code: dto.code, tenant_id: tenantId },
        });

        if (existing) {
          throw new ConflictException(`Role con código '${dto.code}' ya existe`);
        }

        const role = this.roleRepository.create({
          tenant_id: tenantId,
          name: dto.name,
          code: dto.code,
          description: dto.description || null,
          is_system: false,
          is_active: true,
        });

        await this.roleRepository.save(role);

        // Assign permissions if provided
        if (dto.permissions?.length) {
          await this.setRolePermissions(role.id, dto.permissions, tenantId);
        }

        return role;
      }

      async updateRole(
        roleId: string,
        dto: UpdateRoleDto,
        tenantId: string,
      ): Promise<Role> {
        const role = await this.roleRepository.findOne({
          where: { id: roleId, tenant_id: tenantId },
        });

        if (!role) {
          throw new NotFoundException('Role no encontrado');
        }

        if (role.is_system) {
          throw new ForbiddenException('No se puede modificar un role de sistema');
        }

        if (dto.name) role.name = dto.name;
        if (dto.description !== undefined) role.description = dto.description;

        await this.roleRepository.save(role);

        // Update permissions if provided
        Iif (dto.permissions) {
          await this.setRolePermissions(roleId, dto.permissions, tenantId);
        }

        return role;
      }

      async deleteRole(roleId: string, tenantId: string): Promise<void> {
        const role = await this.roleRepository.findOne({
          where: { id: roleId, tenant_id: tenantId },
        });

        if (!role) {
          throw new NotFoundException('Role no encontrado');
        }

        if (role.is_system) {
          throw new ForbiddenException('No se puede eliminar un role de sistema');
        }

        // Check if role is assigned to users
        const usersWithRole = await this.userRoleRepository.count({
          where: { role_id: roleId },
        });

        if (usersWithRole > 0) {
          throw new ConflictException(
            `Role está asignado a ${usersWithRole} usuario(s). Desasigne primero.`,
          );
        }

        // Delete role permissions
        await this.rolePermissionRepository.delete({ role_id: roleId });

        // Delete role
        await this.roleRepository.delete({ id: roleId });
      }

      async findAllRoles(tenantId: string): Promise<Role[]> {
        return this.roleRepository.find({
          where: { tenant_id: tenantId, is_active: true },
          order: { is_system: 'DESC', name: 'ASC' },
        });
      }

      async findRoleById(roleId: string, tenantId: string): Promise<Role> {
        const role = await this.roleRepository.findOne({
          where: { id: roleId, tenant_id: tenantId },
        });

        if (!role) {
          throw new NotFoundException('Role no encontrado');
        }

        return role;
      }

      async getRoleWithPermissions(
        roleId: string,
        tenantId: string,
      ): Promise<{ role: Role; permissions: Permission[] }> {
        const role = await this.findRoleById(roleId, tenantId);
        const permissions = await this.getRolePermissions(roleId);

        return { role, permissions };
      }

      // ==================== Permissions ====================

      async findAllPermissions(): Promise<Permission[]> {
        return this.permissionRepository.find({
          order: { category: 'ASC', code: 'ASC' },
        });
      }

      async findPermissionsByCategory(category: string): Promise<Permission[]> {
        return this.permissionRepository.find({
          where: { category },
          order: { code: 'ASC' },
        });
      }

      async getRolePermissions(roleId: string): Promise<Permission[]> {
        const rolePermissions = await this.rolePermissionRepository.find({
          where: { role_id: roleId },
        });

        Iif (!rolePermissions.length) {
          return [];
        }

        const permissionIds = rolePermissions.map((rp) => rp.permission_id);

        return this.permissionRepository.find({
          where: { id: In(permissionIds) },
          order: { category: 'ASC', code: 'ASC' },
        });
      }

      async setRolePermissions(
        roleId: string,
        permissionCodes: string[],
        tenantId: string,
      ): Promise<void> {
        // Verify role exists and belongs to tenant
        const role = await this.findRoleById(roleId, tenantId);

        Iif (role.is_system) {
          throw new ForbiddenException('No se pueden modificar permisos de un role de sistema');
        }

        // Get permission IDs from codes
        const permissions = await this.permissionRepository.find({
          where: { code: In(permissionCodes) },
        });

        // Delete existing role permissions
        await this.rolePermissionRepository.delete({ role_id: roleId });

        // Create new role permissions
        if (permissions.length) {
          const rolePermissions = permissions.map((p) => ({
            role_id: roleId,
            permission_id: p.id,
          }));

          await this.rolePermissionRepository.save(rolePermissions);
        }
      }

      // ==================== User Roles ====================

      async assignRoleToUser(
        dto: AssignRoleDto,
        tenantId: string,
        assignedBy: string,
      ): Promise<UserRole> {
        // Verify role exists
        await this.findRoleById(dto.roleId, tenantId);

        // Check if already assigned
        const existing = await this.userRoleRepository.findOne({
          where: {
            user_id: dto.userId,
            role_id: dto.roleId,
            tenant_id: tenantId,
          },
        });

        if (existing) {
          throw new ConflictException('Usuario ya tiene este role asignado');
        }

        const userRole = this.userRoleRepository.create({
          user_id: dto.userId,
          role_id: dto.roleId,
          tenant_id: tenantId,
          assigned_by: assignedBy,
        });

        return this.userRoleRepository.save(userRole);
      }

      async removeRoleFromUser(
        userId: string,
        roleId: string,
        tenantId: string,
      ): Promise<void> {
        const result = await this.userRoleRepository.delete({
          user_id: userId,
          role_id: roleId,
          tenant_id: tenantId,
        });

        if (result.affected === 0) {
          throw new NotFoundException('Asignación de role no encontrada');
        }
      }

      async getUserRoles(userId: string, tenantId: string): Promise<Role[]> {
        const userRoles = await this.userRoleRepository.find({
          where: { user_id: userId, tenant_id: tenantId },
        });

        if (!userRoles.length) {
          return [];
        }

        const roleIds = userRoles.map((ur) => ur.role_id);

        return this.roleRepository.find({
          where: { id: In(roleIds), is_active: true },
        });
      }

      async getUserPermissions(userId: string, tenantId: string): Promise<Permission[]> {
        const roles = await this.getUserRoles(userId, tenantId);

        if (!roles.length) {
          return [];
        }

        const roleIds = roles.map((r) => r.id);

        const rolePermissions = await this.rolePermissionRepository.find({
          where: { role_id: In(roleIds) },
        });

        Iif (!rolePermissions.length) {
          return [];
        }

        const permissionIds = [...new Set(rolePermissions.map((rp) => rp.permission_id))];

        return this.permissionRepository.find({
          where: { id: In(permissionIds) },
        });
      }

      async userHasPermission(
        userId: string,
        tenantId: string,
        permissionCode: string,
      ): Promise<boolean> {
        const permissions = await this.getUserPermissions(userId, tenantId);
        return permissions.some((p) => p.code === permissionCode);
      }

      async userHasAnyPermission(
        userId: string,
        tenantId: string,
        permissionCodes: string[],
      ): Promise<boolean> {
        const permissions = await this.getUserPermissions(userId, tenantId);
        return permissions.some((p) => permissionCodes.includes(p.code));
      }

      async userHasAllPermissions(
        userId: string,
        tenantId: string,
        permissionCodes: string[],
      ): Promise<boolean> {
        const permissions = await this.getUserPermissions(userId, tenantId);
        const userPermissionCodes = permissions.map((p) => p.code);
        return permissionCodes.every((code) => userPermissionCodes.includes(code));
      }

      async userHasRole(
        userId: string,
        tenantId: string,
        roleCode: string,
      ): Promise<boolean> {
        const roles = await this.getUserRoles(userId, tenantId);
        return roles.some((r) => r.code === roleCode);
      }
    }