2025-11-18 20:38:35 +01:00
|
|
|
using DiunaBI.API.Services;
|
|
|
|
|
using DiunaBI.Domain.Entities;
|
2025-12-01 17:56:17 +01:00
|
|
|
using Microsoft.AspNetCore.Authorization;
|
2025-11-18 20:38:35 +01:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2025-12-05 23:41:56 +01:00
|
|
|
using Microsoft.AspNetCore.RateLimiting;
|
2025-11-18 20:38:35 +01:00
|
|
|
|
|
|
|
|
namespace DiunaBI.API.Controllers;
|
|
|
|
|
|
2025-12-01 17:56:17 +01:00
|
|
|
[AllowAnonymous]
|
2025-11-18 20:38:35 +01:00
|
|
|
[ApiController]
|
|
|
|
|
[Route("[controller]")]
|
|
|
|
|
public class AuthController(
|
|
|
|
|
GoogleAuthService googleAuthService,
|
|
|
|
|
JwtTokenService jwtTokenService,
|
|
|
|
|
ILogger<AuthController> logger)
|
|
|
|
|
: ControllerBase
|
|
|
|
|
{
|
|
|
|
|
[HttpPost("apiToken")]
|
2025-12-05 23:41:56 +01:00
|
|
|
[EnableRateLimiting("auth")]
|
2025-11-18 20:38:35 +01:00
|
|
|
public async Task<IActionResult> ApiToken([FromBody] string idToken)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(idToken))
|
|
|
|
|
{
|
|
|
|
|
logger.LogWarning("Empty idToken received");
|
|
|
|
|
return BadRequest("IdToken is required");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var (isValid, user, error) = await googleAuthService.ValidateGoogleTokenAsync(idToken);
|
|
|
|
|
|
|
|
|
|
if (!isValid || user == null)
|
|
|
|
|
{
|
|
|
|
|
logger.LogWarning("Google token validation failed: {Error}", error);
|
|
|
|
|
return Unauthorized();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var jwt = jwtTokenService.GenerateToken(user);
|
|
|
|
|
|
|
|
|
|
logger.LogInformation("User authenticated successfully: {Email}", user.Email);
|
|
|
|
|
|
|
|
|
|
return Ok(new
|
|
|
|
|
{
|
|
|
|
|
token = jwt,
|
|
|
|
|
id = user.Id,
|
|
|
|
|
expirationTime = DateTime.UtcNow.AddDays(7) // z JwtSettings
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
logger.LogError(ex, "Error during authentication");
|
|
|
|
|
return StatusCode(500, "Internal server error");
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-05-31 19:26:02 +02:00
|
|
|
}
|