diff --git a/AsbCloudInfrastructure/Services/UserRoleService.cs b/AsbCloudInfrastructure/Services/UserRoleService.cs index dc9226be..f34d7a95 100644 --- a/AsbCloudInfrastructure/Services/UserRoleService.cs +++ b/AsbCloudInfrastructure/Services/UserRoleService.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -14,6 +15,7 @@ namespace AsbCloudInfrastructure.Services private readonly CacheTable cacheUserRoles; private readonly CacheTable cachePermissions; private readonly CacheTable cacheUserRolesPermissions; + private int counter = 0; public UserRoleService(IAsbCloudDbContext context, CacheDb cacheDb) : base(context) { @@ -37,11 +39,16 @@ namespace AsbCloudInfrastructure.Services { var roleDto = await base.GetAsync(id,token); - return roleDto is null ? null : FillUserRoleWithPermissions(roleDto); + return roleDto is null + ? null + : FillUserRoleWithPermissions(roleDto); } public override async Task InsertAsync(UserRoleDto dto, CancellationToken token = default) { + + dto.PermissionIds = GetAncestorsPermissionIds(dto, ref counter); + var newRoleId = await base.InsertAsync(dto, token); if (dto.PermissionIds == default) @@ -90,5 +97,30 @@ namespace AsbCloudInfrastructure.Services return roleDto; } + + private IEnumerable GetAncestorsPermissionIds(UserRoleDto userRoleDto, ref int counter) + { + var idParent = userRoleDto.IdParent; + var resultPermissionsIds = userRoleDto.PermissionIds ?? new List(); + + if (idParent == default) + return resultPermissionsIds; + + if (counter > 10) + { + Trace.WriteLine($"User role with id: {userRoleDto.Id} has more than 10 nested parents"); + return resultPermissionsIds; + } + + var parentRole = cacheUserRoles.FirstOrDefault(r => r.Id == idParent) + .Adapt(); + var parentRolePermissionsIds = cacheUserRolesPermissions.Where(p => + p.IdUserRole == parentRole.Id).Select(perm => perm.IdPermission); + parentRole.PermissionIds = resultPermissionsIds.Union(parentRolePermissionsIds); + + counter++; + + return GetAncestorsPermissionIds(parentRole, ref counter); + } } } \ No newline at end of file