Files
Heimdall/src/Heimdall.Application/Users/Commands/CreateUser/CreateUserHandler.cs
T
arnaud.dartois 622add46ad
Heimdall Gitea / Detect CI scope (pull_request) Successful in 6s
Heimdall Gitea / Build and tests (pull_request) Failing after 4m5s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 1s
refactor(identity): isolate ASP.NET Identity in Infrastructure
2026-11-04 11:37:53 +01:00

54 lines
2.1 KiB
C#

using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.CreateUser;
public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResult<UserResponse>>
{
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public CreateUserHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
}
public async Task<ServiceResult<UserResponse>> Handle(CreateUserCommand command, CancellationToken ct)
{
var existing = await _userManager.FindByEmailAsync(command.Email, ct).ConfigureAwait(false);
if (existing is not null)
return ServiceResult<UserResponse>.Conflict("Email already registered");
var user = new IdentityAccount
{
UserName = command.Email,
Email = command.Email,
DisplayName = command.DisplayName
};
var result = await _userManager.CreateAsync(user, command.Password, ct).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult<UserResponse>.Failure(
string.Join(", ", result.ErrorCodes));
var roles = command.Roles is { Count: > 0 } ? command.Roles : new List<string> { "Viewer" };
var assignment = await _userManager.AddToRolesAsync(user, roles, ct).ConfigureAwait(false);
if (!assignment.Succeeded)
{
await _userManager.DeleteAsync(user, ct).ConfigureAwait(false);
return ServiceResult<UserResponse>.Failure("Unable to assign requested account roles");
}
await _repository.AddAuditLogAsync(command.ActorId, "UserCreated", "User", user.Id.ToString(),
null, null, ct);
var response = await _repository.GetByIdAsync(user.Id, ct).ConfigureAwait(false);
return ServiceResult<UserResponse>.Success(response!);
}
}