50 lines
1.8 KiB
C#
50 lines
1.8 KiB
C#
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());
|
||
|
|
if (user is null)
|
||
|
|
return ServiceResult.NotFound("User not found");
|
||
|
|
|
||
|
|
var roles = await _userManager.GetRolesAsync(user);
|
||
|
|
if (roles.Contains("Admin"))
|
||
|
|
{
|
||
|
|
var adminCount = await _repository.CountAdminUsersAsync(ct);
|
||
|
|
if (adminCount <= 1)
|
||
|
|
return ServiceResult.Failure("Cannot delete the last administrator. " +
|
||
|
|
"Promote another user to Admin first.", 400);
|
||
|
|
}
|
||
|
|
|
||
|
|
await _repository.RemoveUserDataAsync(command.UserId, ct);
|
||
|
|
|
||
|
|
var result = await _userManager.DeleteAsync(user);
|
||
|
|
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();
|
||
|
|
}
|
||
|
|
}
|