"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RbacService = void 0; const common_1 = require("@nestjs/common"); const typeorm_1 = require("@nestjs/typeorm"); const typeorm_2 = require("typeorm"); const entities_1 = require("../entities"); let RbacService = class RbacService { constructor(roleRepository, permissionRepository, userRoleRepository, rolePermissionRepository) { this.roleRepository = roleRepository; this.permissionRepository = permissionRepository; this.userRoleRepository = userRoleRepository; this.rolePermissionRepository = rolePermissionRepository; } async createRole(dto, tenantId) { const existing = await this.roleRepository.findOne({ where: { code: dto.code, tenant_id: tenantId }, }); if (existing) { throw new common_1.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); if (dto.permissions?.length) { await this.setRolePermissions(role.id, dto.permissions, tenantId); } return role; } async updateRole(roleId, dto, tenantId) { const role = await this.roleRepository.findOne({ where: { id: roleId, tenant_id: tenantId }, }); if (!role) { throw new common_1.NotFoundException('Role no encontrado'); } if (role.is_system) { throw new common_1.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); if (dto.permissions) { await this.setRolePermissions(roleId, dto.permissions, tenantId); } return role; } async deleteRole(roleId, tenantId) { const role = await this.roleRepository.findOne({ where: { id: roleId, tenant_id: tenantId }, }); if (!role) { throw new common_1.NotFoundException('Role no encontrado'); } if (role.is_system) { throw new common_1.ForbiddenException('No se puede eliminar un role de sistema'); } const usersWithRole = await this.userRoleRepository.count({ where: { role_id: roleId }, }); if (usersWithRole > 0) { throw new common_1.ConflictException(`Role está asignado a ${usersWithRole} usuario(s). Desasigne primero.`); } await this.rolePermissionRepository.delete({ role_id: roleId }); await this.roleRepository.delete({ id: roleId }); } async findAllRoles(tenantId) { return this.roleRepository.find({ where: { tenant_id: tenantId, is_active: true }, order: { is_system: 'DESC', name: 'ASC' }, }); } async findRoleById(roleId, tenantId) { const role = await this.roleRepository.findOne({ where: { id: roleId, tenant_id: tenantId }, }); if (!role) { throw new common_1.NotFoundException('Role no encontrado'); } return role; } async getRoleWithPermissions(roleId, tenantId) { const role = await this.findRoleById(roleId, tenantId); const permissions = await this.getRolePermissions(roleId); return { role, permissions }; } async findAllPermissions() { return this.permissionRepository.find({ order: { category: 'ASC', code: 'ASC' }, }); } async findPermissionsByCategory(category) { return this.permissionRepository.find({ where: { category }, order: { code: 'ASC' }, }); } async getRolePermissions(roleId) { const rolePermissions = await this.rolePermissionRepository.find({ where: { role_id: roleId }, }); if (!rolePermissions.length) { return []; } const permissionIds = rolePermissions.map((rp) => rp.permission_id); return this.permissionRepository.find({ where: { id: (0, typeorm_2.In)(permissionIds) }, order: { category: 'ASC', code: 'ASC' }, }); } async setRolePermissions(roleId, permissionCodes, tenantId) { const role = await this.findRoleById(roleId, tenantId); if (role.is_system) { throw new common_1.ForbiddenException('No se pueden modificar permisos de un role de sistema'); } const permissions = await this.permissionRepository.find({ where: { code: (0, typeorm_2.In)(permissionCodes) }, }); await this.rolePermissionRepository.delete({ role_id: roleId }); if (permissions.length) { const rolePermissions = permissions.map((p) => ({ role_id: roleId, permission_id: p.id, })); await this.rolePermissionRepository.save(rolePermissions); } } async assignRoleToUser(dto, tenantId, assignedBy) { await this.findRoleById(dto.roleId, tenantId); const existing = await this.userRoleRepository.findOne({ where: { user_id: dto.userId, role_id: dto.roleId, tenant_id: tenantId, }, }); if (existing) { throw new common_1.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, roleId, tenantId) { const result = await this.userRoleRepository.delete({ user_id: userId, role_id: roleId, tenant_id: tenantId, }); if (result.affected === 0) { throw new common_1.NotFoundException('Asignación de role no encontrada'); } } async getUserRoles(userId, tenantId) { 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: (0, typeorm_2.In)(roleIds), is_active: true }, }); } async getUserPermissions(userId, tenantId) { 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: (0, typeorm_2.In)(roleIds) }, }); if (!rolePermissions.length) { return []; } const permissionIds = [...new Set(rolePermissions.map((rp) => rp.permission_id))]; return this.permissionRepository.find({ where: { id: (0, typeorm_2.In)(permissionIds) }, }); } async userHasPermission(userId, tenantId, permissionCode) { const permissions = await this.getUserPermissions(userId, tenantId); return permissions.some((p) => p.code === permissionCode); } async userHasAnyPermission(userId, tenantId, permissionCodes) { const permissions = await this.getUserPermissions(userId, tenantId); return permissions.some((p) => permissionCodes.includes(p.code)); } async userHasAllPermissions(userId, tenantId, permissionCodes) { const permissions = await this.getUserPermissions(userId, tenantId); const userPermissionCodes = permissions.map((p) => p.code); return permissionCodes.every((code) => userPermissionCodes.includes(code)); } async userHasRole(userId, tenantId, roleCode) { const roles = await this.getUserRoles(userId, tenantId); return roles.some((r) => r.code === roleCode); } }; exports.RbacService = RbacService; exports.RbacService = RbacService = __decorate([ (0, common_1.Injectable)(), __param(0, (0, typeorm_1.InjectRepository)(entities_1.Role)), __param(1, (0, typeorm_1.InjectRepository)(entities_1.Permission)), __param(2, (0, typeorm_1.InjectRepository)(entities_1.UserRole)), __param(3, (0, typeorm_1.InjectRepository)(entities_1.RolePermission)), __metadata("design:paramtypes", [typeorm_2.Repository, typeorm_2.Repository, typeorm_2.Repository, typeorm_2.Repository]) ], RbacService); //# sourceMappingURL=rbac.service.js.map