Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 14m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 4m27s
Heimdall Gitea / Build and scan agent image (push) Successful in 15m42s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m27s
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
51 lines
1.9 KiB
C#
51 lines
1.9 KiB
C#
using Heimdall.Application.Common;
|
|
using Heimdall.Application.Common.Persistence;
|
|
using Heimdall.Domain.Entities;
|
|
using MediatR;
|
|
using Heimdall.Application.Services;
|
|
|
|
namespace Heimdall.Application.Users.Commands.DeleteUser;
|
|
|
|
public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResult>
|
|
{
|
|
private readonly IIdentityAccountService _userManager;
|
|
private readonly IUserRepository _repository;
|
|
|
|
public DeleteUserHandler(IIdentityAccountService 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, ct).ConfigureAwait(false);
|
|
if (user is null)
|
|
return ServiceResult.NotFound("User not found");
|
|
|
|
var roles = await _userManager.GetRolesAsync(user, ct).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, ct).ConfigureAwait(false);
|
|
if (!result.Succeeded)
|
|
return ServiceResult.Failure(
|
|
string.Join(", ", result.ErrorCodes));
|
|
|
|
await _repository.AddAuditLogAsync(command.CurrentUserId, "UserDeleted", "User",
|
|
command.UserId.ToString(), null, null, ct);
|
|
|
|
return ServiceResult.Success();
|
|
}
|
|
}
|