2026-07-22 19:43:13 +00:00
|
|
|
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);
|
|
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
if (user is null)
|
|
|
|
|
return ServiceResult.NotFound("User not found");
|
|
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
if (roles.Contains("Admin"))
|
|
|
|
|
{
|
2026-07-27 18:59:12 +00:00
|
|
|
var adminCount = await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
if (adminCount <= 1)
|
|
|
|
|
return ServiceResult.Failure("Cannot delete the last administrator. " +
|
|
|
|
|
"Promote another user to Admin first.", 400);
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
await _repository.RemoveUserDataAsync(command.UserId, ct).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
var result = await _userManager.DeleteAsync(user).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
}
|