Api/Brizco.Repository/Handlers/Complexes/UpdateComplexUserCommandHan...

67 lines
2.8 KiB
C#

namespace Brizco.Repository.Handlers.Complexes;
public class UpdateComplexUserCommandHandler(
IRepositoryWrapper repositoryWrapper,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
: IRequestHandler<UpdateComplexUserCommand, bool>
{
public async Task<bool> Handle(UpdateComplexUserCommand request, CancellationToken cancellationToken)
{
try
{
await repositoryWrapper.BeginTransaction(cancellationToken);
var complexUser = await repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == request.UserId && c.ComplexId == request.ComplexId , cancellationToken);
if (complexUser == null)
throw new AppException("ComplexUser not found", ApiResultStatusCode.NotFound);
var complexUserRoles = await repositoryWrapper.SetRepository<ComplexUserRole>()
.TableNoTracking
.Where(cur => cur.ComplexUserId == complexUser.Id)
.ToListAsync(cancellationToken);
var user = await userManager.FindByIdAsync(complexUser.UserId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
foreach (var userRole in complexUserRoles.ToList())
{
if(request.RoleIds.Contains(userRole.RoleId))
{
complexUserRoles.Remove(userRole);
request.RoleIds.Remove(userRole.RoleId);
}
}
foreach (var userRole in complexUserRoles)
{
repositoryWrapper.SetRepository<ComplexUserRole>().Delete(userRole);
var role = await roleManager.FindByIdAsync(userRole.RoleId.ToString());
var result = await userManager.RemoveFromRoleAsync(user, role.Name);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors));
}
foreach (var roleId in request.RoleIds)
{
var role = await roleManager.FindByIdAsync(roleId.ToString());
var result = await userManager.AddToRoleAsync(user, role.Name);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors));
var userRole = complexUser.AddRole(role.Id);
repositoryWrapper.SetRepository<ComplexUserRole>().Add(userRole);
}
await repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.CommitAsync(cancellationToken);
return true;
}
catch (Exception)
{
await repositoryWrapper.RollBackAsync(cancellationToken);
throw;
}
}
}