using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace BCards.Web.Middleware
{
///
/// Middleware para garantir que páginas que exibem conteúdo dependente de autenticação
/// tenham os headers de cache corretos para evitar problemas de cache do menu
///
public class AuthCacheMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public AuthCacheMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
await _next(context);
// Aplicar headers apenas para páginas HTML (não APIs, imagens, etc)
if (context.Response.ContentType?.StartsWith("text/html") == true)
{
var path = context.Request.Path.Value?.ToLower() ?? string.Empty;
// Páginas que sempre mostram menu com estado de autenticação
bool isPageWithAuthMenu = path == "/" ||
path.StartsWith("/home") ||
path == "/pricing" ||
path.StartsWith("/planos") ||
path.StartsWith("/admin") ||
path.StartsWith("/payment") ||
path.StartsWith("/subscription");
if (isPageWithAuthMenu)
{
// Se usuário está logado, garantir que não use cache
if (context.User?.Identity?.IsAuthenticated == true)
{
// Só adicionar se não foi definido explicitamente pelo controller
if (!context.Response.Headers.ContainsKey("Cache-Control"))
{
context.Response.Headers["Cache-Control"] = "no-cache, must-revalidate";
context.Response.Headers["Vary"] = "Cookie";
_logger.LogDebug("AuthCache: Applied no-cache for authenticated user on {Path}", path);
}
}
else
{
// Para usuários não logados, garantir Vary: Cookie para cache adequado
if (!context.Response.Headers.ContainsKey("Vary") ||
!context.Response.Headers["Vary"].ToString().Contains("Cookie"))
{
var existingVary = context.Response.Headers["Vary"].ToString();
var newVary = string.IsNullOrEmpty(existingVary) ? "Cookie" : $"{existingVary}, Cookie";
context.Response.Headers["Vary"] = newVary;
_logger.LogDebug("AuthCache: Added Vary: Cookie for anonymous user on {Path}", path);
}
}
}
}
}
}
}