| | | 1 | | using CoWorkingApp.Core.Application.Abstracts; |
| | | 2 | | using CoWorkingApp.Core.Application.Contracts.Services; |
| | | 3 | | using CoWorkingApp.Core.Domain.DTOs; |
| | | 4 | | using Microsoft.AspNetCore.Authorization; |
| | | 5 | | using Microsoft.AspNetCore.Cors; |
| | | 6 | | using Microsoft.AspNetCore.Mvc; |
| | | 7 | | using Microsoft.IdentityModel.Tokens; |
| | | 8 | | using System.IdentityModel.Tokens.Jwt; |
| | | 9 | | using System.Security.Claims; |
| | | 10 | | using System.Text; |
| | | 11 | | |
| | | 12 | | namespace CoWorkingApp.API.Infrastructure.Presentation.Controllers |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Controlador para operaciones relacionadas con la autenticación de usuarios. |
| | | 16 | | /// </summary> |
| | | 17 | | [EnableCors("MyPolicy")] // Habilita CORS para este controlador específico |
| | | 18 | | [ApiController] |
| | | 19 | | [Route("[controller]s")] // Ruta del controlador, en plural por convención RESTful |
| | | 20 | | public class LoginUserController : ControllerBase |
| | | 21 | | { |
| | | 22 | | private readonly IUserService _service; |
| | | 23 | | private readonly IConfiguration _configuration; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Constructor de la clase LoginUserController. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <param name="service">Instancia del servicio de usuarios.</param> |
| | | 29 | | /// <param name="configuration">Instancia de IConfiguration para acceder a la configuración de la aplicación.</p |
| | 7 | 30 | | public LoginUserController(IUserService service, IConfiguration configuration) |
| | 7 | 31 | | { |
| | 7 | 32 | | _service = service ?? throw new ArgumentNullException(nameof(service)); |
| | 6 | 33 | | _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); |
| | 5 | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Método para realizar la autenticación de un usuario. |
| | | 38 | | /// </summary> |
| | | 39 | | /// <param name="user">Datos de usuario (correo y contraseña) para autenticación.</param> |
| | | 40 | | /// <returns>ActionResult con el token generado o un mensaje de error.</returns> |
| | | 41 | | [HttpPost] |
| | | 42 | | [AllowAnonymous] // Permite el acceso a este método sin autenticación |
| | | 43 | | [Route("validateuser")] |
| | | 44 | | public async Task<IActionResult> Login([FromBody] UserRequest user) |
| | 4 | 45 | | { |
| | | 46 | | try |
| | 4 | 47 | | { |
| | | 48 | | // Autenticar al usuario utilizando el servicio |
| | 4 | 49 | | var authenticatedUser = await _service.AuthenticateAsync(user); |
| | | 50 | | |
| | 3 | 51 | | if (!authenticatedUser.Success) |
| | 1 | 52 | | { |
| | | 53 | | // Usuario no autenticado, devuelve un Unauthorized con un mensaje de error |
| | 1 | 54 | | authenticatedUser.Message = "Invalid email or password"; |
| | 1 | 55 | | authenticatedUser.Errors.Add(authenticatedUser.Message); |
| | 1 | 56 | | return Unauthorized(authenticatedUser); |
| | | 57 | | } |
| | | 58 | | |
| | | 59 | | // Usuario autenticado, generamos un token JWT |
| | 2 | 60 | | var token = BuildToken(authenticatedUser); |
| | | 61 | | |
| | | 62 | | // Retorna el token en la respuesta |
| | 2 | 63 | | return Ok(new { Response = authenticatedUser, Token = token }); |
| | | 64 | | } |
| | 1 | 65 | | catch (Exception) |
| | 1 | 66 | | { |
| | | 67 | | // Manejar cualquier error y devolver un mensaje de error |
| | 1 | 68 | | var exception = new Exception("An unexpected error occurred while retrieving all entities"); |
| | 1 | 69 | | var response = ResponseMessage.HandleException<UserResponse>(exception); |
| | 1 | 70 | | return StatusCode(500, response); |
| | | 71 | | } |
| | 4 | 72 | | } |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Método para construir el token JWT. |
| | | 76 | | /// </summary> |
| | | 77 | | /// <param name="user">Usuario autenticado para el cual se genera el token.</param> |
| | | 78 | | /// <returns>JsonResult con el token generado.</returns> |
| | | 79 | | private JsonResult BuildToken(UserResponse user) |
| | 2 | 80 | | { |
| | | 81 | | // Obtener el origen del emisor y la audiencia desde la configuración |
| | 2 | 82 | | string issuer = _configuration["Auth:Jwt:Issuer"]; |
| | 2 | 83 | | string audience = _configuration["Auth:Jwt:Audience"]; |
| | | 84 | | |
| | | 85 | | // Datos a incluir en el token |
| | 2 | 86 | | var claims = new[] |
| | 2 | 87 | | { |
| | 2 | 88 | | new Claim(ClaimTypes.Name, user.Name), |
| | 2 | 89 | | new Claim(ClaimTypes.Name, user.LastName), |
| | 2 | 90 | | new Claim(ClaimTypes.Email, user.Email), |
| | 2 | 91 | | }; |
| | | 92 | | |
| | | 93 | | // Generar la clave secreta para firmar el token |
| | 2 | 94 | | string secretKey = _configuration["Auth:Jwt:SecretKey"]; |
| | 2 | 95 | | var key = Encoding.UTF8.GetBytes(secretKey); |
| | 2 | 96 | | var symmetricSecurityKey = new SymmetricSecurityKey(key); |
| | 2 | 97 | | var creds = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256); |
| | | 98 | | |
| | | 99 | | // Calcular el tiempo de validez del token |
| | 2 | 100 | | DateTime now = DateTime.Now; |
| | 2 | 101 | | double minutes = Convert.ToDouble(_configuration["Auth:Jwt:TokenExpirationInMinutes"]); |
| | 2 | 102 | | DateTime expiredDateTime = now.AddMinutes(minutes); |
| | | 103 | | |
| | | 104 | | // Generar el token JWT |
| | 2 | 105 | | var token = new JwtSecurityToken(issuer, |
| | 2 | 106 | | audience, |
| | 2 | 107 | | claims, |
| | 2 | 108 | | expires: expiredDateTime, |
| | 2 | 109 | | signingCredentials: creds |
| | 2 | 110 | | ); |
| | | 111 | | |
| | | 112 | | // Escribir el token como una cadena |
| | 2 | 113 | | var tokenSecurity = new JwtSecurityTokenHandler(); |
| | 2 | 114 | | var tokenString = tokenSecurity.WriteToken(token); |
| | | 115 | | |
| | | 116 | | // Retornar el token en un JsonResult |
| | 2 | 117 | | return new JsonResult(new { Token = tokenString }); |
| | 2 | 118 | | } |
| | | 119 | | } |
| | | 120 | | } |