DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/UserRoleService.cs
2021-11-26 17:05:41 +05:00

75 lines
2.4 KiB
C#

using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Mapster;
namespace AsbCloudInfrastructure.Services
{
public class UserRoleService : CrudServiceBase<UserRoleDto, UserRole>
{
private readonly CacheTable<UserRole> cacheUserRoles;
private int counter = 0;
public UserRoleService(IAsbCloudDbContext context, CacheDb cacheDb) : base(context)
{
cacheUserRoles = cacheDb.GetCachedTable<UserRole>((AsbCloudDbContext)context);
}
public override async Task<PaginationContainer<UserRoleDto>> GetPageAsync(int skip = 0,
int take = 32, CancellationToken token = default)
{
var rolesDtos = await base.GetPageAsync(skip, take,token);
return rolesDtos;
}
public override async Task<int> InsertAsync(UserRoleDto dto, CancellationToken token = default)
{
dto.Permissions = GetAncestorsPermissions(dto, ref counter);
return await base.InsertAsync(dto, token);
}
private long GetAncestorsPermissions(UserRoleDto currentRoleDto, ref int counter)
{
if (currentRoleDto.IdParent == default)
return currentRoleDto.Permissions;
if (counter > 10)
{
Trace.WriteLine($"User role with id: {currentRoleDto.Id} has more than 10 parents");
return currentRoleDto.Permissions;
}
var parentRole = cacheUserRoles.FirstOrDefault(r => r.Id == currentRoleDto.IdParent)
.Adapt<UserRoleDto>();
parentRole.Permissions = MakeBitwiseOr(currentRoleDto.Permissions, parentRole.Permissions);
counter++;
return GetAncestorsPermissions(parentRole, ref counter);
}
private static long MakeBitwiseOr(long currentNum, long parentNum)
{
var parentBytes = BitConverter.GetBytes(parentNum);
var parentBits = new BitArray(parentBytes);
var currentBytes = BitConverter.GetBytes(currentNum);
var currentBits = new BitArray(currentBytes);
var resultBits = currentBits.Or(parentBits);
var resultBytes = new byte[8];
resultBits.CopyTo(resultBytes, 0);
return BitConverter.ToInt64(resultBytes);
}
}
}