DD.WellWorkover.Cloud/AsbCloudInfrastructure/Repository/UserRoleRepository.cs

299 lines
9.7 KiB
C#
Raw Permalink Normal View History

using AsbCloudApp.Comparators;
using AsbCloudApp.Data;
using AsbCloudApp.Data.User;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudDb;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2024-08-19 10:01:07 +05:00
namespace AsbCloudInfrastructure.Repository;
public class UserRoleRepository : IUserRoleRepository
{
2024-08-19 10:01:07 +05:00
private readonly IAsbCloudDbContext dbContext;
private readonly IMemoryCache memoryCache;
2024-08-19 10:01:07 +05:00
public UserRoleRepository(IAsbCloudDbContext dbContext, IMemoryCache memoryCache)
{
2024-08-19 10:01:07 +05:00
this.dbContext = dbContext;
this.memoryCache = memoryCache;
}
2024-08-19 10:01:07 +05:00
public async Task<int> InsertAsync(UserRoleDto dto, CancellationToken token)
{
var entity = dto.Adapt<UserRole>();
var updatedEntity = dbContext.UserRoles.Add(entity);
await dbContext.SaveChangesAsync(token);
2024-08-19 10:01:07 +05:00
if (updatedEntity.IsKeySet)
{
2024-08-19 10:01:07 +05:00
dto.Id = updatedEntity.Entity.Id;
await UpdatePermissionsAsync(dto, token);
await UpdateIncludedRolesAsync(dto, token);
2024-08-19 10:01:07 +05:00
DropCacheUserRole();
return updatedEntity.Entity.Id;
}
2024-08-19 10:01:07 +05:00
return 0;
}
2024-08-19 10:01:07 +05:00
public Task<int> InsertRangeAsync(IEnumerable<UserRoleDto> newItems, CancellationToken token)
{
throw new NotImplementedException();
}
2024-08-19 10:01:07 +05:00
public async Task<IEnumerable<UserRoleDto>> GetAllAsync(CancellationToken token)
{
var entities = await GetCacheUserRoleAsync(token)
.ConfigureAwait(false);
2024-08-19 10:01:07 +05:00
return entities.Select(Convert);
}
2024-08-19 10:01:07 +05:00
public UserRoleDto? GetOrDefault(int id)
{
var entity = GetCacheUserRole().FirstOrDefault(x => x.Id == id);
if (entity is null)
return null;
return Convert(entity);
}
2022-10-27 14:18:59 +05:00
2024-08-19 10:01:07 +05:00
public async Task<UserRoleDto?> GetOrDefaultAsync(int id, CancellationToken token)
{
var entity = (await GetCacheUserRoleAsync(token)
.ConfigureAwait(false)).FirstOrDefault(r => r.Id == id);
if (entity is null)
return null;
return Convert(entity);
}
2022-10-27 14:18:59 +05:00
2024-08-19 10:01:07 +05:00
public async Task<IEnumerable<UserRoleDto>> GetByNamesAsync(IEnumerable<string> names, CancellationToken token)
{
if (names?.Any() != true)
return Enumerable.Empty<UserRoleDto>();
2022-10-27 14:18:59 +05:00
2024-08-19 10:01:07 +05:00
var entities = (await GetCacheUserRoleAsync(token))
.Where(r => names.Contains(r.Caption));
2024-08-19 10:01:07 +05:00
if (entities?.Count() != names.Count())
throw new ArgumentInvalidException(nameof(names), "Invalid role names");
2024-08-19 10:01:07 +05:00
return entities.Select(Convert);
}
2024-08-19 10:01:07 +05:00
public async Task<int> UpdateAsync(UserRoleDto dto, CancellationToken token)
{
await UpdatePermissionsAsync(dto, token);
await UpdateIncludedRolesAsync(dto, token);
var entity = Convert(dto);
var result = dbContext.UserRoles.Upsert(entity);
await dbContext.SaveChangesAsync(token);
DropCacheUserRole();
return result.Entity.Id;
}
2022-10-27 14:18:59 +05:00
2024-08-19 10:01:07 +05:00
public IEnumerable<UserRoleDto> GetNestedById(int id, int recursionLevel = 7)
{
var role = GetCacheUserRole()
.FirstOrDefault(r => r.Id == id);
if (role is null)
return Enumerable.Empty<UserRoleDto>();
2024-08-19 10:01:07 +05:00
var roles = new SortedSet<UserRoleDto>(ComparerIId.GetInstance()) { Convert(role) };
2024-08-19 10:01:07 +05:00
if (recursionLevel <= 0 || role.RelationUserRoleUserRoles?.Any() != true)
return roles;
2024-08-19 10:01:07 +05:00
foreach (var relation in role.RelationUserRoleUserRoles)
{
2024-08-19 10:01:07 +05:00
var nestedRoles = GetNestedById(relation.IdInclude, --recursionLevel);
if (nestedRoles?.Any() != true)
continue;
foreach (var nestedRole in nestedRoles)
roles.Add(nestedRole);
}
2024-08-19 10:01:07 +05:00
return roles;
}
public async Task<int> DeleteAsync(int id, CancellationToken token)
{
var entity = (await GetCacheUserRoleAsync(token)).FirstOrDefault(r => r.Id == id);
2024-08-19 10:01:07 +05:00
if (entity is not null)
{
2024-08-19 10:01:07 +05:00
var removeEntity = dbContext.UserRoles.Remove(entity);
await dbContext.SaveChangesAsync(token);
DropCacheUserRole();
return removeEntity.Entity.Id;
}
else return 0;
}
2024-08-19 10:01:07 +05:00
public bool HasPermission(IEnumerable<int> rolesIds, string permissionName)
{
var permissionInfo = GetCacheRelationUserRolePermissions()
.FirstOrDefault(p => p. Permission?.Name.ToLower() == permissionName.ToLower())
?.Permission;
2024-08-19 10:01:07 +05:00
if (permissionInfo is null)
return false;
2024-08-19 10:01:07 +05:00
if (rolesIds.Contains(1))
return true;
2022-10-27 15:44:04 +05:00
2024-08-19 10:01:07 +05:00
var idPermissionInfo = permissionInfo.Id;
var entities = GetCacheUserRole()
.Where(r => rolesIds.Contains(r.Id));
2024-08-19 10:01:07 +05:00
foreach (var role in entities)
if (HasPermission(role, idPermissionInfo))
return true;
2024-08-19 10:01:07 +05:00
return false;
}
2024-08-19 10:01:07 +05:00
private bool HasPermission(UserRole userRole, int idPermission, int recursionLevel = 7)
{
if (userRole.RelationUserRolePermissions.Any(p => p.IdPermission == idPermission))
return true;
2024-08-19 10:01:07 +05:00
if (recursionLevel <= 0 || userRole.RelationUserRoleUserRoles?.Any() != true)
return false;
2024-08-19 10:01:07 +05:00
foreach (var relation in userRole.RelationUserRoleUserRoles)
{
var entity = GetCacheUserRole()
.First(p => p.Id == relation.IdInclude);
if (HasPermission(entity, idPermission, --recursionLevel))
return true;
}
2024-08-19 10:01:07 +05:00
return false;
}
2024-08-19 10:01:07 +05:00
private IEnumerable<UserRoleDto> GetNestedByIds(IEnumerable<int> ids, int recursionLevel = 7)
{
var roles = new List<UserRoleDto>();
foreach (var id in ids)
roles.AddRange(GetNestedById(id, recursionLevel));
2024-08-19 10:01:07 +05:00
return roles;
}
2024-08-19 10:01:07 +05:00
private async Task UpdateIncludedRolesAsync(UserRoleDto dto, CancellationToken token)
{
if (!dto.Roles.Any())
return;
2024-08-19 10:01:07 +05:00
var idsIncludeRole = GetNestedByIds(dto.Roles.Select(x => x.Id)).Select(x => x.Id);
2024-08-19 10:01:07 +05:00
if (idsIncludeRole.Any(x => x == dto.Id))
throw new ArgumentInvalidException(nameof(dto), "Invalid include role (self reference)");
2024-08-19 10:01:07 +05:00
var removeRelationsQuery = dbContext.RelationUserRoleUserRoles
.Where(r => r.Id == dto.Id);
2024-08-19 10:01:07 +05:00
dbContext.RelationUserRoleUserRoles.RemoveRange(removeRelationsQuery);
var newRelations = dto.Roles.Select(r => new RelationUserRoleUserRole
{
Id = dto.Id,
IdInclude = r.Id,
});
dbContext.RelationUserRoleUserRoles.AddRange(newRelations);
await dbContext.SaveChangesAsync(token);
DropCacheRelationUserRoleUserRole();
}
2024-08-19 10:01:07 +05:00
private async Task UpdatePermissionsAsync(UserRoleDto dto, CancellationToken token)
{
if (dto?.Permissions is null)
return;
2024-08-19 10:01:07 +05:00
var relations = await dbContext.RelationUserRolePermissions
.Where(r => r.IdUserRole == dto.Id)
.ToListAsync(token)
.ConfigureAwait(false);
dbContext.RelationUserRolePermissions.RemoveRange(relations);
2024-08-19 10:01:07 +05:00
if (dto.Permissions.Any())
{
var newRelations = dto.Permissions.Select(p => new RelationUserRolePermission
{
2024-08-19 10:01:07 +05:00
IdPermission = p.Id,
IdUserRole = dto.Id,
});
await dbContext.RelationUserRolePermissions.AddRangeAsync(newRelations, token);
await dbContext.SaveChangesAsync(token);
}
2024-08-19 10:01:07 +05:00
DropCacheRelationUserRolePermissions();
}
2024-08-19 10:01:07 +05:00
private Task<IEnumerable<UserRole>> GetCacheUserRoleAsync(CancellationToken token)
=> memoryCache.GetOrCreateBasicAsync(dbContext.Set<UserRole>()
.Include(r => r.RelationUserRolePermissions)
.Include(r => r.RelationUserRoleUserRoles)
.Include(r => r.RelationUsersUserRoles), token);
2024-08-19 10:01:07 +05:00
private IEnumerable<UserRole> GetCacheUserRole()
=> memoryCache.GetOrCreateBasic(dbContext.Set<UserRole>()
.Include(r => r.RelationUserRolePermissions)
.Include(r => r.RelationUserRoleUserRoles)
.Include(r => r.RelationUsersUserRoles));
2024-08-19 10:01:07 +05:00
private void DropCacheUserRole()
=> memoryCache.DropBasic<UserRole>();
2024-08-19 10:01:07 +05:00
private void DropCacheRelationUserRoleUserRole()
=> memoryCache.DropBasic<RelationUserUserRole>();
2024-08-19 10:01:07 +05:00
private IEnumerable<RelationUserRolePermission> GetCacheRelationUserRolePermissions()
=> memoryCache.GetOrCreateBasic(dbContext.Set<RelationUserRolePermission>()
.Include(r => r.UserRole)
.Include(r => r.Permission));
2024-08-19 10:01:07 +05:00
private void DropCacheRelationUserRolePermissions()
=> memoryCache.DropBasic<RelationUserRolePermission>();
2024-08-19 10:01:07 +05:00
private UserRoleDto Convert(UserRole entity)
{
var dto = entity.Adapt<UserRoleDto>();
if (entity.RelationUserRolePermissions?.Any() == true)
{
2024-08-19 10:01:07 +05:00
dto.Permissions = GetCacheRelationUserRolePermissions()
.Where(r => entity.Id == r.IdUserRole)
.Select(r => Convert(r.Permission));
}
2024-08-19 10:01:07 +05:00
if (entity.RelationUserRoleUserRoles?.Any() == true)
{
2024-08-19 10:01:07 +05:00
var rolesCache = GetCacheUserRole();
dto.Roles = entity.RelationUserRoleUserRoles
.Select(rel => Convert(rolesCache
.First(r => r.Id == rel.IdInclude)))
.ToArray();
}
2024-08-19 10:01:07 +05:00
return dto;
}
2024-08-19 10:01:07 +05:00
private static PermissionDto Convert(Permission entity)
{
var dto = entity.Adapt<PermissionDto>();
return dto;
}
2024-08-19 10:01:07 +05:00
private static UserRole Convert(UserRoleDto dto)
{
var entity = dto.Adapt<UserRole>();
return entity;
}
}