using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using SIGCM.Application.DTOs; using SIGCM.Application.Interfaces; namespace SIGCM.API.Controllers; [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { private readonly IAuthService _authService; public AuthController(IAuthService authService) { _authService = authService; } // Inicio de sesión tradicional [HttpPost("login")] public async Task Login(LoginDto dto) { var result = await _authService.LoginAsync(dto.Username, dto.Password); if (!result.Success) return Unauthorized(new { message = result.ErrorMessage }); return Ok(result); } // Registro de nuevos usuarios [HttpPost("register")] public async Task Register(RegisterDto dto) { var result = await _authService.RegisterAsync(dto.Username, dto.Email, dto.Password); if (!result.Success) return BadRequest(new { message = result.ErrorMessage }); return Ok(result); } // Inicio de sesión con Google [HttpPost("google-login")] public async Task GoogleLogin([FromBody] string idToken) { var result = await _authService.GoogleLoginAsync(idToken); if (!result.Success) return Unauthorized(new { message = result.ErrorMessage }); return Ok(result); } // Flujo MFA: Obtener secreto (QR) [Authorize] [HttpGet("mfa/setup")] public async Task SetupMfa() { var userId = int.Parse(User.FindFirst("Id")?.Value!); var secret = await _authService.GenerateMfaSecretAsync(userId); return Ok(new { secret, qrCodeUri = $"otpauth://totp/SIGCM:{User.Identity?.Name}?secret={secret}&issuer=SIGCM" }); } // Flujo MFA: Verificar y activar [Authorize] [HttpPost("mfa/verify")] public async Task VerifyMfa([FromBody] string code) { var userId = int.Parse(User.FindFirst("Id")?.Value!); var valid = await _authService.VerifyMfaCodeAsync(userId, code); if (!valid) return BadRequest(new { message = "Código inválido" }); await _authService.EnableMfaAsync(userId, true); return Ok(new { success = true }); } } public class RegisterDto { public string Username { get; set; } = ""; public string Email { get; set; } = ""; public string Password { get; set; } = ""; }