QrRapido/Middleware/LastLoginUpdateMiddleware.cs
Ricardo Carneiro 2ccd35bb7d
Some checks failed
Deploy QR Rapido / test (push) Successful in 4m58s
Deploy QR Rapido / build-and-push (push) Failing after 1m39s
Deploy QR Rapido / deploy-staging (push) Has been skipped
Deploy QR Rapido / deploy-production (push) Has been skipped
first commit
2025-07-28 11:46:48 -03:00

48 lines
1.8 KiB
C#

using QRRapidoApp.Services;
using System.Security.Claims;
namespace QRRapidoApp.Middleware
{
public class LastLoginUpdateMiddleware
{
private readonly RequestDelegate _next;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<LastLoginUpdateMiddleware> _logger;
public LastLoginUpdateMiddleware(RequestDelegate next, IServiceScopeFactory scopeFactory, ILogger<LastLoginUpdateMiddleware> logger)
{
_next = next;
_scopeFactory = scopeFactory;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
// Only update login for authenticated users on first request of session
if (context.User.Identity?.IsAuthenticated == true)
{
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!string.IsNullOrEmpty(userId) && !context.Session.GetString("LoginUpdated")?.Equals("true") == true)
{
try
{
using var scope = _scopeFactory.CreateScope();
var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
await userService.UpdateLastLoginAsync(userId);
context.Session.SetString("LoginUpdated", "true");
_logger.LogInformation($"Updated last login for user {userId}");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error updating last login for user {userId}: {ex.Message}");
}
}
}
await _next(context);
}
}
}