You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LoginUserHandler.cs 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using AutoMapper;
  2. using Diligent.WebAPI.Business.Interfaces;
  3. using Diligent.WebAPI.Data.Entities;
  4. using Diligent.WebAPI.Host.DTOs.Customer;
  5. using Diligent.WebAPI.Host.Mediator.Authentication.Queries;
  6. using MediatR;
  7. using Microsoft.AspNetCore.Identity;
  8. namespace Diligent.WebAPI.Host.Mediator.Authentication.Handlers
  9. {
  10. public class LoginUserHandler : IRequestHandler<LoginUserQuery, CustomerReadDTO>
  11. {
  12. private readonly UserManager<Customer> _customerManager;
  13. private readonly IAuthenticationService _authenticationService;
  14. private readonly IMapper _mapper;
  15. private readonly ICustomerService _customerService;
  16. public LoginUserHandler(UserManager<Customer> customerManager, IAuthenticationService authenticationService,
  17. IMapper mapper, ICustomerService customerService)
  18. {
  19. _customerManager = customerManager;
  20. _authenticationService = authenticationService;
  21. _mapper = mapper;
  22. _customerService = customerService;
  23. }
  24. public async Task<CustomerReadDTO> Handle(LoginUserQuery request, CancellationToken cancellationToken)
  25. {
  26. var customerLoginDTO = request.CustomerLoginDTO;
  27. if (!await _authenticationService.ValidateCustomer(customerLoginDTO.Username, customerLoginDTO.Password))
  28. throw new BadHttpRequestException("Authentication failed.Wrong Username or password");
  29. Customer customer = await _customerService.GetCustomer(customerLoginDTO.Username);
  30. var customerReadDTO = _mapper.Map<CustomerReadDTO>(customer);
  31. customerReadDTO.Token = await _authenticationService.GenerateToken();
  32. customerReadDTO.Roles = (List<string>)await _customerManager.GetRolesAsync(customer);
  33. return customerReadDTO;
  34. }
  35. }
  36. }