using AutoMapper; using Diligent.WebAPI.Business.Interfaces; using Diligent.WebAPI.Data.Entities; using Diligent.WebAPI.Host.DTOs.Customer; using Diligent.WebAPI.Host.Mediator.Authentication.Queries; using MediatR; using Microsoft.AspNetCore.Identity; namespace Diligent.WebAPI.Host.Mediator.Authentication.Handlers { public class LoginUserHandler : IRequestHandler { private readonly UserManager _customerManager; private readonly IAuthenticationService _authenticationService; private readonly IMapper _mapper; private readonly ICustomerService _customerService; public LoginUserHandler(UserManager customerManager, IAuthenticationService authenticationService, IMapper mapper, ICustomerService customerService) { _customerManager = customerManager; _authenticationService = authenticationService; _mapper = mapper; _customerService = customerService; } public async Task Handle(LoginUserQuery request, CancellationToken cancellationToken) { var customerLoginDTO = request.CustomerLoginDTO; if (!await _authenticationService.ValidateCustomer(customerLoginDTO.Username, customerLoginDTO.Password)) throw new BadHttpRequestException("Authentication failed.Wrong Username or password"); Customer customer = await _customerService.GetCustomer(customerLoginDTO.Username); var customerReadDTO = _mapper.Map(customer); customerReadDTO.Token = await _authenticationService.GenerateToken(); customerReadDTO.Roles = (List)await _customerManager.GetRolesAsync(customer); return customerReadDTO; } } }