App login is working
All checks were successful
Build Docker Images / test (push) Successful in 1m37s
Build Docker Images / build-and-push (push) Successful in 1m52s

This commit is contained in:
Michał Zieliński
2025-11-09 19:39:52 +01:00
parent 95438efcbd
commit f7b9009215
14 changed files with 466 additions and 227 deletions

View File

@@ -1,60 +1,51 @@
using Google.Apis.Auth;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using DiunaBI.API.Services;
using DiunaBI.Domain.Entities;
using DiunaBI.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
namespace DiunaBI.API.Controllers;
[ApiController]
[Route("api/[controller]")]
// [Authorize]
public class AuthController : Controller
public class AuthController(
GoogleAuthService googleAuthService,
JwtTokenService jwtTokenService,
ILogger<AuthController> logger)
: ControllerBase
{
private readonly AppDbContext _db;
private readonly IConfiguration _configuration;
public AuthController(
AppDbContext db, IConfiguration configuration)
{ _db = db; _configuration = configuration; }
[HttpPost]
[Route("apiToken")]
public async Task<IActionResult> ApiToken([FromBody] string credential)
[HttpPost("apiToken")]
public async Task<IActionResult> ApiToken([FromBody] string idToken)
{
var settings = new GoogleJsonWebSignature.ValidationSettings
try
{
Audience = new List<string> { _configuration.GetValue<string>("GoogleClientId")! }
};
var payload = await GoogleJsonWebSignature.ValidateAsync(credential, settings);
var user = _db.Users.AsNoTracking().FirstOrDefault(x => x.Email == payload.Email);
return user != null ? (IActionResult)Ok(JwtGenerator(user)) : Unauthorized();
}
private dynamic JwtGenerator(User user)
{
var key = Encoding.ASCII.GetBytes(_configuration.GetValue<string>("Secret")!);
var expirationTime = DateTime.UtcNow.AddMinutes(5);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
if (string.IsNullOrEmpty(idToken))
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti,
Guid.NewGuid().ToString())
}),
Expires = expirationTime,
SigningCredentials = new SigningCredentials
(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var stringToken = tokenHandler.WriteToken(token);
return new { token = stringToken, id = user.Id, expirationTime };
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");
}
}
}