Files
Heimdall/src/Heimdall.Application/Users/Commands/DeleteUser/DeleteUserHandler.cs
T

50 lines
1.9 KiB
C#
Raw Normal View History

using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
namespace Heimdall.Application.Users.Commands.DeleteUser;
public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IUserRepository _repository;
public DeleteUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
}
public async Task<ServiceResult> Handle(DeleteUserCommand command, CancellationToken ct)
{
if (command.UserId == command.CurrentUserId)
return ServiceResult.Failure("You cannot delete your own account.", 400);
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
if (user is null)
return ServiceResult.NotFound("User not found");
var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
if (roles.Contains("Admin"))
{
var adminCount = await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false);
if (adminCount <= 1)
return ServiceResult.Failure("Cannot delete the last administrator. " +
"Promote another user to Admin first.", 400);
}
await _repository.RemoveUserDataAsync(command.UserId, ct).ConfigureAwait(false);
var result = await _userManager.DeleteAsync(user).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
await _repository.AddAuditLogAsync(command.CurrentUserId, "UserDeleted", "User",
command.UserId.ToString(), null, null, ct);
return ServiceResult.Success();
}
}