Shows a connection-lost indicator when the SignalR connection closes.

This commit is contained in:
BinaryAlley committed 2026-11-07 17:03:55 +02:00
1 parent 0abf8d4aea
commit e2c705d822
44 files changed
+1254 -78

No files matched your search

@@ -1,10 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Responses.Authorization;
using Microsoft.AspNetCore.Http;
using Polly.CircuitBreaker;
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
@@ -66,6 +70,38 @@ public class AuthorizationService : IAuthorizationService
string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId))
return new GetAuthorizationResponse(Guid.Empty, string.Empty, []);
return await _apiHttpClient.GetAsync<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken);
try
{
return await _apiHttpClient.GetAsync<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken);
}
catch (Exception exception)
{
HttpContext? httpContext = _httpContextAccessor.HttpContext;
if (httpContext is null || httpContext.RequestAborted.IsCancellationRequested)
throw;
if (!IsApiOutage(exception))
throw;
bool isPageNavigation = (httpContext.Request.Headers.Accept.Count == 0 && httpContext.Request.Headers.Range.Count == 0)
|| httpContext.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
if (!isPageNavigation)
throw;
// The page is still rendered while the API is unreachable, with no role and no permissions, and the request is marked so
// that the page reports the failure to the user. API requests keep propagating the failure as a JSON error.
httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
return new GetAuthorizationResponse(Guid.Empty, string.Empty, []);
}
}
/// <summary>
/// Determines whether the exception means that the API could not answer, as opposed to an authorization answer from the API.
/// </summary>
/// <param name="exception">The exception thrown by the API call.</param>
/// <returns><see langword="true"/> for a connection, timeout, circuit breaker or server failure; otherwise <see langword="false"/>.</returns>
private static bool IsApiOutage(Exception exception)
{
return exception is HttpRequestException or BrokenCircuitException or TaskCanceledException
|| (exception is ApiException apiException && (int)apiException.HttpStatusCode >= 500);
}
}
@@ -1,9 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Polly.CircuitBreaker;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
@@ -32,15 +37,51 @@ public class InitializationHandler : AuthorizationHandler<InitializationRequirem
/// <param name="initializationRequirement">The initialization requirement to be evaluated.</param>
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, InitializationRequirement initializationRequirement)
{
InitializationResponse result = await _apiHttpClient.GetAsync<InitializationResponse>("initialization/").ConfigureAwait(false);
HttpContext? httpContext = authorizationHandlerContext.Resource as HttpContext;
if (result.IsInitialized)
try
{
// admin account was registered, remove this requirement from the session
httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
InitializationResponse result = await _apiHttpClient.GetAsync<InitializationResponse>("initialization/").ConfigureAwait(false);
HttpContext? httpContext = authorizationHandlerContext.Resource as HttpContext;
if (result.IsInitialized)
{
// admin account was registered, remove this requirement from the session
httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
authorizationHandlerContext.Succeed(initializationRequirement);
}
else // store in session that super admin setup is needed
httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true");
}
catch (Exception exception)
{
HttpContext? httpContext = GetPageNavigationDuringApiOutage(authorizationHandlerContext, exception);
if (httpContext is null)
throw;
// The initialization state cannot be read while the API is unreachable, but the requested page is still rendered, and
// the failure is reported to the user there. The data calls of the page keep failing on their own.
httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
authorizationHandlerContext.Succeed(initializationRequirement);
}
else // store in session that super admin setup is needed
httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true");
}
/// <summary>
/// Gets the current HTTP context when the provided exception is an API outage on a page navigation, and <see langword="null"/> otherwise.
/// </summary>
/// <param name="authorizationHandlerContext">The authorization context whose resource holds the HTTP context.</param>
/// <param name="exception">The exception thrown by the initialization check against the API.</param>
/// <returns>The HTTP context of the page navigation, or <see langword="null"/> when the exception must propagate.</returns>
private static HttpContext? GetPageNavigationDuringApiOutage(AuthorizationHandlerContext authorizationHandlerContext, Exception exception)
{
if (authorizationHandlerContext.Resource is not HttpContext httpContext)
return null;
if (httpContext.RequestAborted.IsCancellationRequested)
return null;
if (exception is not ApiException and not HttpRequestException and not BrokenCircuitException and not TaskCanceledException)
return null;
if (exception is ApiException apiException && (int)apiException.HttpStatusCode < 500)
return null;
bool isPageNavigation = (httpContext.Request.Headers.Accept.Count == 0 && httpContext.Request.Headers.Range.Count == 0)
|| httpContext.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
return isPageNavigation ? httpContext : null;
}
}
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -13,14 +15,17 @@ namespace Lumina.Presentation.Web.Common.Authorization;
public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
{
private readonly IAuthorizationService _authorizationService;
private readonly IHttpContextAccessor _httpContextAccessor;
/// <summary>
/// Initializes a new instance of the <see cref="PermissionAuthorizationHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization checks against the remote API.</param>
public PermissionAuthorizationHandler(IAuthorizationService authorizationService)
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
public PermissionAuthorizationHandler(IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor)
{
_authorizationService = authorizationService;
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
@@ -44,5 +49,13 @@ public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionReq
return;
}
}
// The authorization service marks a page navigation when the API could not answer. The page itself is still rendered, with
// no permission granted, and it reports the failure to the user; the API remains the enforcement point for every data call.
// Endpoint routing passes the Endpoint, not the HttpContext, as the authorization resource, so the current request is read
// from the accessor instead. Only an authenticated user is allowed through, because the outage is not a reason to expose a
// page to an anonymous visitor.
HttpContext? httpContext = _httpContextAccessor.HttpContext;
if (httpContext?.User.Identity?.IsAuthenticated == true && httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true)
authorizationHandlerContext.Succeed(permissionRequirement);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authorization;
using System.Linq;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -13,14 +14,17 @@ namespace Lumina.Presentation.Web.Common.Authorization;
public class RoleAuthorizationHandler : AuthorizationHandler<RoleRequirement>
{
private readonly IAuthorizationService _authorizationService;
private readonly IHttpContextAccessor _httpContextAccessor;
/// <summary>
/// Initializes a new instance of the <see cref="RoleAuthorizationHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization checks against the remote API.</param>
public RoleAuthorizationHandler(IAuthorizationService authorizationService)
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
public RoleAuthorizationHandler(IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor)
{
_authorizationService = authorizationService;
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
@@ -38,5 +42,13 @@ public class RoleAuthorizationHandler : AuthorizationHandler<RoleRequirement>
return;
}
}
// The authorization service marks a page navigation when the API could not answer. The page itself is still rendered, with
// no role granted, and it reports the failure to the user; the API remains the enforcement point for every data call.
// Endpoint routing passes the Endpoint, not the HttpContext, as the authorization resource, so the current request is read
// from the accessor instead. Only an authenticated user is allowed through, because the outage is not a reason to expose a
// page to an anonymous visitor.
HttpContext? httpContext = _httpContextAccessor.HttpContext;
if (httpContext?.User.Identity?.IsAuthenticated == true && httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true)
authorizationHandlerContext.Succeed(roleRequirement);
}
}