2026-07-22 19:43:13 +00:00
|
|
|
using Heimdall.Application.Common;
|
|
|
|
|
using Heimdall.Application.Common.Persistence;
|
|
|
|
|
using Heimdall.Application.DTOs;
|
|
|
|
|
using Heimdall.Domain.Entities;
|
|
|
|
|
using MediatR;
|
|
|
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Application.Users.Commands.CreateUser;
|
|
|
|
|
|
|
|
|
|
public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResult<UserResponse>>
|
|
|
|
|
{
|
|
|
|
|
private readonly UserManager<AppUser> _userManager;
|
|
|
|
|
private readonly IUserRepository _repository;
|
|
|
|
|
|
|
|
|
|
public CreateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
|
|
|
|
{
|
|
|
|
|
_userManager = userManager;
|
|
|
|
|
_repository = repository;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<ServiceResult<UserResponse>> Handle(CreateUserCommand command, CancellationToken ct)
|
|
|
|
|
{
|
2026-07-27 18:59:12 +00:00
|
|
|
var existing = await _userManager.FindByEmailAsync(command.Email).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
if (existing is not null)
|
|
|
|
|
return ServiceResult<UserResponse>.Conflict("Email already registered");
|
|
|
|
|
|
|
|
|
|
var user = new AppUser
|
|
|
|
|
{
|
|
|
|
|
UserName = command.Email,
|
|
|
|
|
Email = command.Email,
|
|
|
|
|
DisplayName = command.DisplayName
|
|
|
|
|
};
|
|
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
var result = await _userManager.CreateAsync(user, command.Password).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
if (!result.Succeeded)
|
|
|
|
|
return ServiceResult<UserResponse>.Failure(
|
|
|
|
|
string.Join(", ", result.Errors.Select(e => e.Description)));
|
|
|
|
|
|
|
|
|
|
var roles = command.Roles is { Count: > 0 } ? command.Roles : new List<string> { "Viewer" };
|
2026-11-04 10:26:07 +01:00
|
|
|
var assignment = await _userManager.AddToRolesAsync(user, roles).ConfigureAwait(false);
|
|
|
|
|
if (!assignment.Succeeded)
|
|
|
|
|
{
|
|
|
|
|
await _userManager.DeleteAsync(user).ConfigureAwait(false);
|
|
|
|
|
return ServiceResult<UserResponse>.Failure("Unable to assign requested account roles");
|
|
|
|
|
}
|
2026-07-22 19:43:13 +00:00
|
|
|
|
2026-11-04 10:26:07 +01:00
|
|
|
await _repository.AddAuditLogAsync(command.ActorId, "UserCreated", "User", user.Id.ToString(),
|
2026-07-22 19:43:13 +00:00
|
|
|
null, null, ct);
|
|
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
var response = await _repository.GetByIdAsync(user.Id, ct).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
return ServiceResult<UserResponse>.Success(response!);
|
|
|
|
|
}
|
|
|
|
|
}
|