| 123456789101112131415161718192021222324252627282930313233343536373839 |
- 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<LoginUserQuery, CustomerReadDTO>
- {
- private readonly UserManager<Customer> _customerManager;
- private readonly IAuthenticationService _authenticationService;
- private readonly IMapper _mapper;
- private readonly ICustomerService _customerService;
-
- public LoginUserHandler(UserManager<Customer> customerManager, IAuthenticationService authenticationService,
- IMapper mapper, ICustomerService customerService)
- {
- _customerManager = customerManager;
- _authenticationService = authenticationService;
- _mapper = mapper;
- _customerService = customerService;
- }
- public async Task<CustomerReadDTO> 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<CustomerReadDTO>(customer);
- customerReadDTO.Token = await _authenticationService.GenerateToken();
- customerReadDTO.Roles = (List<string>)await _customerManager.GetRolesAsync(customer);
- return customerReadDTO;
- }
- }
- }
|