Files
Heimdall/src/Heimdall.Application/Users/Commands/CreateUser/CreateUserHandler.cs
T

48 lines
1.7 KiB
C#
Raw Normal View History

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)
{
var existing = await _userManager.FindByEmailAsync(command.Email);
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
};
var result = await _userManager.CreateAsync(user, command.Password);
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" };
await _userManager.AddToRolesAsync(user, roles);
await _repository.AddAuditLogAsync(null, "UserCreated", "User", user.Id.ToString(),
null, null, ct);
var response = await _repository.GetByIdAsync(user.Id, ct);
return ServiceResult<UserResponse>.Success(response!);
}
}