| | | 1 | | using FAU.Logica.DTOs; |
| | | 2 | | using FAU.Logica.Services; |
| | | 3 | | using Microsoft.AspNetCore.Authorization; |
| | | 4 | | using Microsoft.AspNetCore.Http; |
| | | 5 | | using Microsoft.AspNetCore.Mvc; |
| | | 6 | | |
| | | 7 | | namespace FAU.API.Controllers; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Controlador de autenticación |
| | | 11 | | /// </summary> |
| | | 12 | | [ApiController] |
| | | 13 | | [Route("api/[controller]")] |
| | | 14 | | [Produces("application/json")] |
| | | 15 | | public class AuthController : ControllerBase |
| | | 16 | | { |
| | | 17 | | private readonly IAuthService _authService; |
| | | 18 | | private readonly IUsuarioService _usuarioService; |
| | | 19 | | private readonly ILogger<AuthController> _logger; |
| | | 20 | | |
| | 5 | 21 | | public AuthController( |
| | 5 | 22 | | IAuthService authService, |
| | 5 | 23 | | IUsuarioService usuarioService, |
| | 5 | 24 | | ILogger<AuthController> logger) |
| | | 25 | | { |
| | 5 | 26 | | _authService = authService; |
| | 5 | 27 | | _usuarioService = usuarioService; |
| | 5 | 28 | | _logger = logger; |
| | 5 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Login de usuario - Endpoint principal de autenticación |
| | | 33 | | /// POST /api/auth/login |
| | | 34 | | /// </summary> |
| | | 35 | | [HttpPost("login")] |
| | | 36 | | [AllowAnonymous] |
| | | 37 | | [ProducesResponseType(typeof(ApiResponse<LoginResponse>), StatusCodes.Status200OK)] |
| | | 38 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status401Unauthorized)] |
| | | 39 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 40 | | public async Task<IActionResult> Login([FromBody] LoginRequest request) |
| | | 41 | | { |
| | | 42 | | try |
| | | 43 | | { |
| | 3 | 44 | | var (success, token, error) = await _authService.LoginAsync(request.Username, request.Password); |
| | | 45 | | |
| | 2 | 46 | | if (!success) |
| | | 47 | | { |
| | 1 | 48 | | return Unauthorized(ApiResponse<string>.ErrorResult(error ?? "Credenciales inválidas")); |
| | | 49 | | } |
| | | 50 | | |
| | 1 | 51 | | var usuario = await _usuarioService.GetByUsernameWithRolesAsync(request.Username); |
| | | 52 | | |
| | 1 | 53 | | var response = new LoginResponse |
| | 1 | 54 | | { |
| | 1 | 55 | | Success = true, |
| | 1 | 56 | | Token = token, |
| | 1 | 57 | | Usuario = usuario != null ? new UsuarioDto |
| | 1 | 58 | | { |
| | 1 | 59 | | Id = usuario.Id, |
| | 1 | 60 | | Username = usuario.Username, |
| | 1 | 61 | | Estado = usuario.Estado, |
| | 1 | 62 | | PersonaId = usuario.PersonaId, |
| | 1 | 63 | | Persona = usuario.Persona != null ? new PersonaDto |
| | 1 | 64 | | { |
| | 1 | 65 | | Id = usuario.Persona.Id, |
| | 1 | 66 | | Cedula = usuario.Persona.Cedula, |
| | 1 | 67 | | Nombre = usuario.Persona.PrimerNombre, |
| | 1 | 68 | | Apellido = usuario.Persona.PrimerApellido, |
| | 1 | 69 | | Email = usuario.Persona.Email, |
| | 1 | 70 | | Telefono = usuario.Persona.Telefono |
| | 1 | 71 | | } : null, |
| | 1 | 72 | | Roles = usuario.Roles.Select(r => new RolDto |
| | 1 | 73 | | { |
| | 1 | 74 | | Id = r.Id, |
| | 1 | 75 | | Nombre = r.Nombre, |
| | 1 | 76 | | Descripcion = r.Descripcion |
| | 1 | 77 | | }).ToList() |
| | 1 | 78 | | } : null |
| | 1 | 79 | | }; |
| | | 80 | | |
| | 1 | 81 | | return Ok(ApiResponse<LoginResponse>.SuccessResult(response, "Login exitoso")); |
| | | 82 | | } |
| | 1 | 83 | | catch (Exception ex) |
| | | 84 | | { |
| | 1 | 85 | | _logger.LogError(ex, "Error en login"); |
| | 1 | 86 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 87 | | } |
| | 3 | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Registro de nuevo usuario. Requiere autenticación con rol Administrador. |
| | | 92 | | /// POST /api/auth/register |
| | | 93 | | /// </summary> |
| | | 94 | | [HttpPost("register")] |
| | | 95 | | [Authorize(Roles = "Administrador")] |
| | | 96 | | [ProducesResponseType(typeof(ApiResponse<UsuarioDto>), StatusCodes.Status200OK)] |
| | | 97 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 98 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 99 | | public async Task<IActionResult> Register([FromBody] RegisterRequest request) |
| | | 100 | | { |
| | | 101 | | try |
| | | 102 | | { |
| | 2 | 103 | | var (success, usuario, error) = await _authService.RegisterAsync( |
| | 2 | 104 | | request.Username, |
| | 2 | 105 | | request.Password, |
| | 2 | 106 | | request.PersonaId); |
| | | 107 | | |
| | 2 | 108 | | if (!success) |
| | | 109 | | { |
| | 1 | 110 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al registrar usuario")); |
| | | 111 | | } |
| | | 112 | | |
| | 1 | 113 | | var usuarioDto = new UsuarioDto |
| | 1 | 114 | | { |
| | 1 | 115 | | Id = usuario!.Id, |
| | 1 | 116 | | Username = usuario.Username, |
| | 1 | 117 | | Estado = usuario.Estado, |
| | 1 | 118 | | PersonaId = usuario.PersonaId |
| | 1 | 119 | | }; |
| | | 120 | | |
| | 1 | 121 | | return Ok(ApiResponse<UsuarioDto>.SuccessResult(usuarioDto, "Usuario registrado exitosamente")); |
| | | 122 | | } |
| | 0 | 123 | | catch (Exception ex) |
| | | 124 | | { |
| | 0 | 125 | | _logger.LogError(ex, "Error en registro"); |
| | 0 | 126 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 127 | | } |
| | 2 | 128 | | } |
| | | 129 | | } |