using AutoMapper; using Diligent.WebAPI.Business.Interfaces; using Diligent.WebAPI.Data.Entities; using Diligent.WebAPI.Host.DTOs.Customer; using Diligent.WebAPI.Host.Mediator.Authentication.Commands; using MediatR; using Microsoft.AspNetCore.Identity; namespace Diligent.WebAPI.Host.Mediator.Authentication.Handlers { public class RegisterUserHandler : IRequestHandler { private readonly UserManager _customerManager; private readonly IAuthenticationService _authenticationService; private readonly IMapper _mapper; public RegisterUserHandler(UserManager customerManager,IAuthenticationService authenticationService, IMapper mapper) { _customerManager = customerManager; _authenticationService = authenticationService; _mapper = mapper; } public async Task Handle(RegisterUserCommand request, CancellationToken cancellationToken) { var customerCreateDTO = request.CustomerCreateDTO; Customer customer = new() { FirstName = customerCreateDTO.FirstName, LastName = customerCreateDTO.LastName, Email = customerCreateDTO.Email, UserName = customerCreateDTO.Username }; var result = await _customerManager.CreateAsync(customer, customerCreateDTO.Password); await _customerManager.AddToRoleAsync(customer, "Support"); await _authenticationService.ValidateCustomer(customer.UserName, customerCreateDTO.Password); var customerReadDTO = _mapper.Map(customer); customerReadDTO.Token = await _authenticationService.GenerateToken(); customerReadDTO.Roles = (List)await _customerManager.GetRolesAsync(customer); return customerReadDTO; } } }