mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #278 from BinaryAlley/feature/global-server-unreachable-handling
Shows a global server unreachable banner and handles failed navigation gracefully
This commit is contained in:
45 files changed
+1312
-82
No files matched your search
@@ -19,6 +19,11 @@ jobs:
|
||||
uses: actions/setup-dotnet@v1
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
- name: Raise file watcher limits
|
||||
# The test hosts create a Razor file watcher per static asset, and the default limit of 128 inotify instances
|
||||
# is reached when several hosts run in parallel.
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo sysctl -w fs.inotify.max_user_instances=1024 fs.inotify.max_user_watches=524288
|
||||
- name: Restore Six Labors license
|
||||
shell: bash
|
||||
run: printf '%s\n' "${{ secrets.SIXLABORS_LICENSE_KEY }}" > src/Lumina.Domain/sixlabors.lic
|
||||
|
||||
@@ -84,7 +84,9 @@ The manifest is a small JSON object:
|
||||
|
||||
### Templates
|
||||
|
||||
Templates use a small, Mustache-style syntax: `{{name}}` prints a value, escaped; `{{{name}}}` or `{{&name}}` prints it raw; `{{#name}}...{{/name}}` repeats or shows a section; `{{^name}}...{{/name}}` shows a section when a value is absent. A theme provides a layout that wraps every page, a navigation menu, an optional 404 page, page templates for the pages it wants to restyle, and optionally templates for the file system browser component.
|
||||
Templates use a small, Mustache-style syntax: `{{name}}` prints a value, escaped; `{{{name}}}` or `{{&name}}` prints it raw; `{{#name}}...{{/name}}` repeats or shows a section; `{{^name}}...{{/name}}` shows a section when a value is absent. A theme provides a layout that wraps every page, a navigation menu, a server unreachable banner, an optional 404 page, page templates for the pages it wants to restyle, and optionally templates for the file system browser component.
|
||||
|
||||
The server unreachable banner is the strip that appears at the bottom of the window while Lumina cannot reach its server. A theme renders it from its own `shared/server-unreachable-banner` template, or from the built-in fallback when it does not provide one, and the layout places it through the `serverUnreachableBanner` field. The theme owns the markup, the placement, the position, the size, the background and everything else about the banner; it only has to keep the `data-server-unreachable-banner` hook on its root element and hide and show that element with the `is-visible` class. The [theming guide](../../technical/theming/Theming.md) describes the message field, the fallback markup and the rest of the contract.
|
||||
|
||||
A page is matched to a template by a key that mirrors the page's path, so the books page looks for `templates/library/written-content-library/book-library/books/index.html`, or a template at a parent scope when the exact one is missing. When a theme has no template for a page, the application renders that page itself with its own built-in view, so a theme never has to cover everything.
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ The header menu rearranges itself depending on who you are. Everyone sees a site
|
||||
|
||||
The home page is your catalogue: a grid of the libraries you are allowed to see, each shown as a card with its cover when it has one. Selecting a card opens that library's browsing page. Some library types do not have a browsing page yet, and their cards appear as plain panels rather than links.
|
||||
|
||||
When the server cannot be reached, Lumina keeps the page you asked for and shows a red banner along the bottom. The banner belongs to the active theme, so its position, size and look can differ between themes.
|
||||
|
||||
## Your account
|
||||
|
||||
Accounts are local to your Lumina server. From the account section you can:
|
||||
|
||||
@@ -13,6 +13,7 @@ The web client of Lumina is a themed shell: every page is rendered inside the te
|
||||
- [Safety Limits](#safety-limits)
|
||||
- [Template Resolution](#template-resolution)
|
||||
- [The Layout Template (shared/layout)](#the-layout-template-sharedlayout)
|
||||
- [The Server Unreachable Banner](#the-server-unreachable-banner)
|
||||
- [The Audio Player Bar](#the-audio-player-bar)
|
||||
- [The VU Meter](#the-vu-meter)
|
||||
- [Play Affordances on the Music Pages](#play-affordances-on-the-music-pages)
|
||||
@@ -170,6 +171,7 @@ Known page keys:
|
||||
| --- | --- |
|
||||
| `shared/layout` | The layout that wraps the shell of every page. |
|
||||
| `shared/nav-menu` | The navigation menu of the theme. |
|
||||
| `shared/server-unreachable-banner` | The banner shown while the server is unreachable. |
|
||||
| `shared/not-found` | The 404 page. |
|
||||
| `shared/audio-player` | The audio player bar shell. |
|
||||
| `shared/audio-player/queue-item` | The queue item of the audio player bar. |
|
||||
@@ -196,6 +198,7 @@ Every page is rendered inside the layout template. The layout receives a model w
|
||||
| `nav` | The fully rendered navigation menu HTML. |
|
||||
| `content` | The fully rendered content section of the page. |
|
||||
| `audioPlayer` | The rendered audio player when the user is authenticated, empty otherwise. |
|
||||
| `serverUnreachableBanner` | The rendered server unreachable banner, placed by the layout. |
|
||||
| `appScripts` | The global scripts of the application. |
|
||||
| `scripts` | The rendered script section of the page. |
|
||||
| `mainStyle` | An inline style for the main content area, `bottom: 0px;` when the user is not authenticated and empty otherwise. |
|
||||
@@ -213,6 +216,7 @@ The layout template of the bundled theme shows the intended shape:
|
||||
<link rel="stylesheet" href="{{assetBase}}/site.css">
|
||||
</head>
|
||||
<body>
|
||||
{{&serverUnreachableBanner}}
|
||||
<div id="page">
|
||||
<header>
|
||||
{{&nav}}
|
||||
@@ -239,6 +243,44 @@ The layout template of the bundled theme shows the intended shape:
|
||||
|
||||
The rendered page content, navigation and scripts are inserted unescaped with `{{&...}}`, because they are trusted application HTML. The layout is best effort: when the theme cannot be loaded or rendered, the application falls back to its built-in layout, so a broken theme never takes the whole site down.
|
||||
|
||||
### The Server Unreachable Banner
|
||||
|
||||
The server unreachable banner is a theme component, rendered from the `shared/server-unreachable-banner` template and placed by the layout through its `serverUnreachableBanner` field:
|
||||
|
||||
```html
|
||||
<body>
|
||||
{{&serverUnreachableBanner}}
|
||||
...
|
||||
</body>
|
||||
```
|
||||
|
||||
The template receives this model:
|
||||
|
||||
| Field | Content |
|
||||
| --- | --- |
|
||||
| `message` | The localized message that tells the user that the server is unreachable. |
|
||||
|
||||
The fallback template shows the shape a theme should keep:
|
||||
|
||||
```html
|
||||
<div id="server-unreachable-banner" class="server-unreachable-banner" data-server-unreachable-banner role="status" aria-live="polite" aria-atomic="true">
|
||||
<span class="server-unreachable-banner-text">{{message}}</span>
|
||||
</div>
|
||||
```
|
||||
|
||||
The application fallback stylesheet gives the text a slow opacity pulse through the `server-unreachable-banner-text` class, and disables it when the user asks for reduced motion. A theme can keep that class and animation, override the animation, or render its own wrapper and animate it instead.
|
||||
|
||||
The root element of the template must carry the `data-server-unreachable-banner` hook. It should be hidden while the `is-visible` class is absent and shown while that class is present; the global script only adds and removes that class. The theme owns the markup, the placement in the layout, the position, the size, the background, including background images and extra child elements, and every other visual aspect.
|
||||
|
||||
When the theme does not provide the template, the application renders its own fallback markup with the `server-unreachable-banner` class. The application fallback stylesheet hides it by default and fixes it to the bottom edge of the viewport, full width, with a red background and white text, and it does not block pointer interaction with the page. A theme that uses the fallback class can restyle it directly or through these custom properties:
|
||||
|
||||
| Custom property | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `--server-unreachable-background-color` | `#c62828` | The background color of the banner. |
|
||||
| `--server-unreachable-text-color` | `#ffffff` | The text color of the banner. |
|
||||
|
||||
The banner is shown while the application health probe cannot reach the API, while an API call of the page fails before the server answers (a network failure or a timeout, reported through the `api` source of the global script), and while a SignalR connection of the page is lost. A successful health probe only clears the probe source and the API-call source, so a disconnected SignalR hub keeps the banner visible until that connection reconnects. Because the element is part of the layout, it stays in the page across the AJAX navigation that swaps the content section.
|
||||
|
||||
### The Audio Player Bar
|
||||
|
||||
Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar starts hidden, and the global audio player script shows it when playback starts, expands it and hides it again. The markup comes from the `shared/audio-player` template of the active theme; when the theme does not provide that template, the application renders its own fallback markup, so the player always has a bar to bind to.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
/// <param name="Nav">The rendered navigation menu of the page.</param>
|
||||
/// <param name="Content">The rendered content section of the page.</param>
|
||||
/// <param name="AudioPlayer">The rendered audio player, when the current user is authenticated.</param>
|
||||
/// <param name="ServerUnreachableBanner">The rendered server unreachable banner, placed by the layout.</param>
|
||||
/// <param name="AppScripts">The application global scripts, such as its client libraries and configuration.</param>
|
||||
/// <param name="Scripts">The rendered script section of the page.</param>
|
||||
/// <param name="MainStyle">The inline style of the main content area, used to fill the viewport when the user is not authenticated.</param>
|
||||
@@ -24,6 +25,7 @@ public sealed record ThemeLayoutModelDto(
|
||||
string Nav,
|
||||
string Content,
|
||||
string AudioPlayer,
|
||||
string ServerUnreachableBanner,
|
||||
string AppScripts,
|
||||
string Scripts,
|
||||
string MainStyle
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the model available to the themed server unreachable banner template.
|
||||
/// </summary>
|
||||
/// <param name="Message">The localized message that tells the user that the server is unreachable.</param>
|
||||
[DebuggerDisplay("Message: {Message}")]
|
||||
public sealed record ThemeServerUnreachableBannerDto(
|
||||
string Message
|
||||
);
|
||||
@@ -9,6 +9,11 @@ public static class HttpContextItemKeys
|
||||
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
|
||||
public const string LAST_DISPLAYED_VIEW = "LastViewUrl";
|
||||
|
||||
/// <summary>
|
||||
/// Marks a rendered page whose authorization could not reach the API, so that the page reports the failure to the user.
|
||||
/// </summary>
|
||||
public const string SERVER_UNREACHABLE = "ServerUnreachable";
|
||||
|
||||
/// <summary>
|
||||
/// The <c>Cache-Control</c> value chosen by the endpoint, restored when the response starts.
|
||||
/// </summary>
|
||||
|
||||
@@ -6,12 +6,16 @@ using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Polly.CircuitBreaker;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Middlewares;
|
||||
@@ -67,12 +71,31 @@ public class ExceptionHandlingMiddleware
|
||||
context.Abort();
|
||||
return;
|
||||
}
|
||||
// return a JSON result with the error details
|
||||
await WriteJsonResponseAsync(context, new
|
||||
// A page navigation is answered with an HTML error page at the same address, so the browser never leaves the page the user
|
||||
// asked for and never shows raw JSON. A JSON caller still receives the JSON error, and any other caller, like a media request,
|
||||
// receives a bare status code, because neither an HTML page nor a JSON body is a representation such a caller can consume.
|
||||
if (IsJsonRequest(context))
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
serverUnreachable = IsApiOutage(ex),
|
||||
errorMessage = _stringLocalizer["InternalServerError"].Value
|
||||
});
|
||||
else if (IsExplicitNavigationRequest(context))
|
||||
await WriteHtmlErrorResponseAsync(context, (int)HttpStatusCode.InternalServerError, _stringLocalizer["InternalServerError"].Value).ConfigureAwait(false);
|
||||
else if (IsNavigationRequest(context))
|
||||
{
|
||||
success = false,
|
||||
errorMessage = ex.Message
|
||||
});
|
||||
// A caller that states no preference is not necessarily a browser, so it keeps the historical JSON envelope instead of
|
||||
// receiving an HTML page it cannot consume.
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
serverUnreachable = IsApiOutage(ex),
|
||||
errorMessage = _stringLocalizer["InternalServerError"].Value
|
||||
});
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.InternalServerError).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,21 +192,74 @@ public class ExceptionHandlingMiddleware
|
||||
/// </summary>
|
||||
private async Task HandleGenericApiErrorAsync(HttpContext context, ApiException apiException)
|
||||
{
|
||||
// JSON callers and page navigations get the localized error message; any other caller, like an audio request, is answered with
|
||||
// a bare status code, because a JSON body is not a representation such a caller can consume.
|
||||
if (IsJsonRequest(context) || IsNavigationRequest(context))
|
||||
// JSON callers get the localized error message, page navigations get an HTML error page at the same address, so the browser never
|
||||
// leaves the page the user asked for and never shows raw JSON, and any other caller, like an audio request, is answered with a
|
||||
// bare status code, because neither a JSON body nor an HTML page is a representation such a caller can consume.
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
serverUnreachable = (int)apiException.HttpStatusCode >= 500,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else if (IsNavigationRequest(context))
|
||||
{
|
||||
bool isServerError = (int)apiException.HttpStatusCode >= 500;
|
||||
string message = isServerError ? _stringLocalizer["InternalServerError"].Value : BuildErrorMessage(apiException);
|
||||
await WriteHtmlErrorResponseAsync(context, (int)apiException.HttpStatusCode, message).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)apiException.HttpStatusCode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the exception means that the server could not answer, as opposed to an answer the server produced.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception thrown while handling the request.</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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a standalone HTML error page to the client, keeping the browser on the requested address.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <param name="statusCode">The status code to answer with.</param>
|
||||
/// <param name="message">The localized message to show on the page.</param>
|
||||
private async Task WriteHtmlErrorResponseAsync(HttpContext context, int statusCode, string message)
|
||||
{
|
||||
context.Response.StatusCode = statusCode;
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
string encodedMessage = HtmlEncoder.Default.Encode(message);
|
||||
string encodedTitle = HtmlEncoder.Default.Encode(_stringLocalizer["Error"].Value);
|
||||
string language = CultureInfo.CurrentUICulture.Name;
|
||||
await context.Response.WriteAsync($$"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="{{language}}">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{{encodedTitle}}</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; margin: 2rem; }
|
||||
h1 { color: #c62828; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{{encodedTitle}}</h1>
|
||||
<p>{{encodedMessage}}</p>
|
||||
</body>
|
||||
</html>
|
||||
""").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles unauthorized exceptions.
|
||||
/// </summary>
|
||||
@@ -283,6 +359,22 @@ public class ExceptionHandlingMiddleware
|
||||
|| string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current request explicitly identifies itself as a browser navigation, rather than merely stating no preference.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A caller that sends no <c>Accept</c> header at all may be a script, a probe, or an API client, so it is not safe to answer it with
|
||||
/// an HTML page. Only a request that asks for HTML or carries the browser navigation headers is treated as a page here.
|
||||
/// </remarks>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <returns><see langword="true"/> when the request is explicitly a browser navigation, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsExplicitNavigationRequest(HttpContext context)
|
||||
{
|
||||
return context.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| string.Equals(context.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a JSON response to the client.
|
||||
/// </summary>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>إعادة المحاولة</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>الخادم غير قابل للوصول</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>توسيع المشغل أو طيه</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Wiederholen</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Der Server ist nicht erreichbar</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Player ein- oder ausklappen</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Retry</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Server is unreachable</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Expand or collapse player</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Reintentar</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>El servidor no está disponible</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Expandir o contraer el reproductor</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Réessayer</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Le serveur est injoignable</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Développer ou réduire le lecteur</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Riprova</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Il server non è raggiungibile</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Espandi o comprimi il lettore</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>再試行</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>サーバーに接続できません</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>プレーヤーを展開または折りたたむ</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Retry</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Server is unreachable</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Expand or collapse player</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Reîncercare</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Serverul nu este disponibil</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Extinde sau restrânge playerul</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Повторити</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Сервер недоступний</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Розгорнути або згорнути плеєр</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>重试</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>服务器不可访问</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>展开或折叠播放器</value>
|
||||
</data>
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -17,6 +19,13 @@ public class ThemeLayoutRenderer
|
||||
// the page keys mirror the paths of the corresponding Razor views under Core/Views, so that theme templates can override them at the page, section or default scope
|
||||
private const string LAYOUT_PAGE_KEY = "shared/layout";
|
||||
private const string NAV_PAGE_KEY = "shared/nav-menu";
|
||||
private const string SERVER_UNREACHABLE_BANNER_PAGE_KEY = "shared/server-unreachable-banner";
|
||||
|
||||
// The banner template is static for a theme, so it is cached, including the negative result of a theme that does not
|
||||
// provide one, so a missing template does not cost an API round trip and a 404 log on every page render.
|
||||
private static readonly ConcurrentDictionary<string, (string Template, DateTime ExpiresOnUtc)> s_bannerTemplateCache = [];
|
||||
private static readonly TimeSpan s_bannerTemplateCacheDuration = TimeSpan.FromMinutes(5);
|
||||
private static readonly TimeSpan s_missingBannerTemplateCacheDuration = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly ThemeService _themeService;
|
||||
private readonly ThemeTemplateEngine _templateEngine;
|
||||
@@ -24,6 +33,7 @@ public class ThemeLayoutRenderer
|
||||
private readonly ThemeNavBuilder _navBuilder;
|
||||
private readonly ThemeAudioPlayerRenderer _audioPlayerRenderer;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly IStringLocalizer _layoutLocalizer;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeLayoutRenderer"/> class.
|
||||
@@ -34,7 +44,8 @@ public class ThemeLayoutRenderer
|
||||
/// <param name="navBuilder">The builder used to produce the navigation menu model.</param>
|
||||
/// <param name="audioPlayerRenderer">The renderer used to produce the themed audio player bar.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
|
||||
public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, ThemeAudioPlayerRenderer audioPlayerRenderer, IHttpContextAccessor httpContextAccessor)
|
||||
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the layout resources.</param>
|
||||
public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, ThemeAudioPlayerRenderer audioPlayerRenderer, IHttpContextAccessor httpContextAccessor, IStringLocalizerFactory stringLocalizerFactory)
|
||||
{
|
||||
_themeService = themeService;
|
||||
_templateEngine = templateEngine;
|
||||
@@ -42,6 +53,7 @@ public class ThemeLayoutRenderer
|
||||
_navBuilder = navBuilder;
|
||||
_audioPlayerRenderer = audioPlayerRenderer;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_layoutLocalizer = stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -62,6 +74,7 @@ public class ThemeLayoutRenderer
|
||||
string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken);
|
||||
string nav = await RenderNavAsync(themeId, cancellationToken);
|
||||
string audioPlayer = isAuthenticated ? await RenderAudioPlayerAsync(themeId, cancellationToken) : string.Empty;
|
||||
string serverUnreachableBanner = await RenderServerUnreachableBannerAsync(themeId, cancellationToken);
|
||||
string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken);
|
||||
|
||||
ThemeLayoutModelDto layoutModel = new(
|
||||
@@ -71,6 +84,7 @@ public class ThemeLayoutRenderer
|
||||
nav,
|
||||
page.Content,
|
||||
audioPlayer,
|
||||
serverUnreachableBanner,
|
||||
appScripts,
|
||||
page.Script,
|
||||
isAuthenticated ? string.Empty : "bottom: 0px;");
|
||||
@@ -139,4 +153,51 @@ public class ThemeLayoutRenderer
|
||||
|
||||
return await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders the server unreachable banner of the active theme, falling back to the application Razor markup when the theme does not provide a template.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The manifest id of the theme the layout was resolved with, so that the banner always matches the shell.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The rendered server unreachable banner HTML.</returns>
|
||||
private async Task<string> RenderServerUnreachableBannerAsync(string themeId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (s_bannerTemplateCache.TryGetValue(themeId, out (string Template, DateTime ExpiresOnUtc) cached) && cached.ExpiresOnUtc > DateTime.UtcNow)
|
||||
return await RenderBannerTemplateAsync(cached.Template, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
string template = string.Empty;
|
||||
try
|
||||
{
|
||||
ThemeRenderDocumentDto bannerDocument = await _themeService.GetRenderDocumentAsync(SERVER_UNREACHABLE_BANNER_PAGE_KEY, themeId, cancellationToken);
|
||||
template = bannerDocument.Template;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// The banner is best effort: when the theme template cannot be loaded or rendered, the application Razor fallback is rendered instead.
|
||||
}
|
||||
s_bannerTemplateCache[themeId] = (template, DateTime.UtcNow + (string.IsNullOrEmpty(template) ? s_missingBannerTemplateCacheDuration : s_bannerTemplateCacheDuration));
|
||||
return await RenderBannerTemplateAsync(template, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a banner template, or the application fallback when the theme does not provide one.
|
||||
/// </summary>
|
||||
/// <param name="template">The raw banner template source, or an empty string when the theme does not provide one.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The rendered server unreachable banner HTML.</returns>
|
||||
private async Task<string> RenderBannerTemplateAsync(string template, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(template))
|
||||
return await _viewRenderer.RenderPartialAsync("_ServerUnreachableBanner", cancellationToken);
|
||||
|
||||
ThemeServerUnreachableBannerDto bannerModel = new(_layoutLocalizer["ServerUnreachable"].Value);
|
||||
Result<ThemePageRenderResultDto> renderResult = _templateEngine.RenderPage(template, bannerModel);
|
||||
return renderResult.IsSuccess
|
||||
? renderResult.Value.Content
|
||||
: await _viewRenderer.RenderPartialAsync("_ServerUnreachableBanner", cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -737,10 +737,15 @@ It keeps the DOM contract the client script binds to, without any images or colo
|
||||
schedulerHubConnection.on('ScheduledJobExecutionCompletedAsync', execution => {
|
||||
loadJobsAsync();
|
||||
});
|
||||
schedulerHubConnection.onreconnecting(() => window.serverConnectionStatus.markUnreachable('scheduledJobsHub'));
|
||||
schedulerHubConnection.onreconnected(() => window.serverConnectionStatus.markReachable('scheduledJobsHub'));
|
||||
schedulerHubConnection.onclose(() => window.serverConnectionStatus.markUnreachable('scheduledJobsHub'));
|
||||
|
||||
try {
|
||||
await schedulerHubConnection.start();
|
||||
window.serverConnectionStatus.markReachable('scheduledJobsHub');
|
||||
} catch (error) {
|
||||
window.serverConnectionStatus.markUnreachable('scheduledJobsHub');
|
||||
console.error('Failed to connect to the scheduled jobs hub:', error);
|
||||
}
|
||||
}
|
||||
@@ -805,7 +810,7 @@ It keeps the DOM contract the client script binds to, without any images or colo
|
||||
updateTimespanButton.removeEventListener('click', updateTimeSpanAsync);
|
||||
addJobButton.removeEventListener('click', addJobAsync);
|
||||
if (schedulerHubConnection)
|
||||
schedulerHubConnection.stop();
|
||||
schedulerHubConnection.stop().finally(() => window.serverConnectionStatus.markReachable('scheduledJobsHub'));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -529,12 +529,15 @@
|
||||
// Handle all SignalR stuff.
|
||||
function setupSignalRHandlers() {
|
||||
const onReconnecting = error => {
|
||||
console.log(error ? `SignalR reconnected with error: ${error}` : "SignalR reconnecting...");
|
||||
window.serverConnectionStatus.markUnreachable('scanProgressHub');
|
||||
console.log(error ? `SignalR reconnecting with error: ${error}` : "SignalR reconnecting...");
|
||||
};
|
||||
const onReconnected = connectionId => {
|
||||
window.serverConnectionStatus.markReachable('scanProgressHub');
|
||||
console.log('SignalR reconnected:', connectionId);
|
||||
};
|
||||
const onClose = error => {
|
||||
window.serverConnectionStatus.markUnreachable('scanProgressHub');
|
||||
console.log(error ? `SignalR connection closed with error: ${error}` : "SignalR connection closed");
|
||||
};
|
||||
// Progress update handler.
|
||||
@@ -678,8 +681,9 @@
|
||||
// Register cleanup for these listeners.
|
||||
cleanupFunctions.push(() => {
|
||||
// Proper connection stop.
|
||||
if (signalRConnection.state === 'Connected')
|
||||
signalRConnection.stop().then(() => console.log('SignalR connection stopped'));
|
||||
window.serverConnectionStatus.markReachable('scanProgressHub');
|
||||
if (signalRConnection.state !== 'Disconnected')
|
||||
signalRConnection.stop().finally(() => window.serverConnectionStatus.markReachable('scanProgressHub'));
|
||||
|
||||
btnScanAllLibraries.removeEventListener('click', handleScanAllLibrariesClick);
|
||||
btnCancelLibrariesScan.removeEventListener('click', handleCancelLibrariesScanClick);
|
||||
@@ -702,11 +706,18 @@
|
||||
isInitialized = true;
|
||||
try {
|
||||
await loadLibrariesAsync();
|
||||
await signalRConnection.start();
|
||||
try {
|
||||
await signalRConnection.start();
|
||||
window.serverConnectionStatus.markReachable('scanProgressHub');
|
||||
} catch (err) {
|
||||
window.serverConnectionStatus.markUnreachable('scanProgressHub');
|
||||
console.error('SignalR connection failed:', err);
|
||||
return;
|
||||
}
|
||||
setupSignalRHandlers();
|
||||
await getRunningLibraryScansAsync();
|
||||
} catch (err) {
|
||||
console.error('SignalR connection failed:', err);
|
||||
console.error('Failed to initialize the libraries page:', err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,38 @@
|
||||
@using Lumina.Presentation.Web.Common.DTO.Common
|
||||
@using Lumina.Presentation.Web.Common.Services
|
||||
@using Microsoft.Extensions.Localization
|
||||
|
||||
@model ErrorViewDto
|
||||
@inject IStringLocalizerFactory _stringLocalizerFactory
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "Error";
|
||||
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
var localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
<h1 class="text-danger">Error.</h1>
|
||||
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
||||
<div style="display: grid; grid-template-rows: auto 1fr;">
|
||||
<div style="min-height: 1rem;"></div>
|
||||
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-55 mb-10" style="min-width: 320px;">
|
||||
<div class="shine-effect"></div>
|
||||
<div class="text-center w-100">
|
||||
<p class="invalid-feedback f-18 w-100"><b>@localizer["Error"]</b></p>
|
||||
<p class="invalid-feedback f-18 w-100"><b>@localizer["NavigationFailed"]</b></p>
|
||||
@if (Model.ShouldShowRequestId)
|
||||
{
|
||||
<p class="text-disabled w-100">
|
||||
<strong>Request ID:</strong> <code>@Model.RequestId</code>
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (Model.ShouldShowRequestId)
|
||||
{
|
||||
<p>
|
||||
<strong>Request ID:</strong> <code>@Model.RequestId</code>
|
||||
</p>
|
||||
@section Scripts {
|
||||
<script type="text/plain" data-form="@scriptId">
|
||||
// The page is the navigation failure fallback, so the user is told that the page could not be loaded. When a marker
|
||||
// driven notification was already shown for this page, it is not repeated.
|
||||
if (!window.isServerUnreachable)
|
||||
notificationService.show(jsLocalizedMessages.navigationFailed, NotificationType.ERROR);
|
||||
</script>
|
||||
}
|
||||
|
||||
<h3>Development Mode</h3>
|
||||
<p>
|
||||
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
|
||||
</p>
|
||||
<p>
|
||||
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
|
||||
It can result in displaying sensitive information from exceptions to end users.
|
||||
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
|
||||
and restarting the app.
|
||||
</p>
|
||||
@@ -1,4 +1,5 @@
|
||||
@using Lumina.Presentation.Web.Common.DTO.Themes
|
||||
@using Lumina.Presentation.Web.Common.Http
|
||||
@using Lumina.Presentation.Web.Common.Primitives
|
||||
@using Lumina.Presentation.Web.Core.Themes
|
||||
@using Microsoft.AspNetCore.Html
|
||||
@@ -17,6 +18,11 @@
|
||||
bodyHtml = bodyWriter.ToString();
|
||||
}
|
||||
|
||||
// The page renders even when the API was unreachable during its authorization check. The marker is carried inside the main content,
|
||||
// so the global script reports the failed navigation both on a full page load and after an AJAX navigation swapped the content.
|
||||
if (ViewContext.HttpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true)
|
||||
bodyHtml = "<div id=\"server-unreachable-marker\" hidden></div>" + bodyHtml;
|
||||
|
||||
string scriptsHtml;
|
||||
using (StringWriter scriptsWriter = new())
|
||||
{
|
||||
@@ -63,6 +69,7 @@ else
|
||||
@await Html.PartialAsync("_AudioPlayer")
|
||||
}
|
||||
</div>
|
||||
@await Html.PartialAsync("_ServerUnreachableBanner")
|
||||
<div id="modal-background-menu"></div>
|
||||
@await Html.PartialAsync("_ThemeLayoutScripts")
|
||||
<div data-section="scripts">
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
@using Microsoft.Extensions.Localization
|
||||
|
||||
@inject IStringLocalizerFactory _stringLocalizerFactory
|
||||
|
||||
@{
|
||||
var localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
<div id="server-unreachable-banner" class="server-unreachable-banner" data-server-unreachable-banner role="status" aria-live="polite" aria-atomic="true"><span class="server-unreachable-banner-text">@localizer["ServerUnreachable"]</span></div>
|
||||
@@ -1 +1,7 @@
|
||||
@using Lumina.Presentation.Web.Common.Http
|
||||
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
|
||||
<script>
|
||||
// Set before any page script runs, so the API helpers suppress their duplicate error notifications when the page was
|
||||
// rendered while the API was unreachable, and the page only shows the single navigation failed notification.
|
||||
window.isServerUnreachable = @(ViewContext.HttpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true ? "true" : "false");
|
||||
</script>
|
||||
@@ -16,9 +16,11 @@
|
||||
var globalConfiguration = {
|
||||
serverBasePath: '@(_serverConfigurationModel.Value.BaseAddress):@(_serverConfigurationModel.Value.Port)',
|
||||
apiBasePath: '@(_serverConfigurationModel.Value.BaseAddress):@(_serverConfigurationModel.Value.Port)/api/v@(_serverConfigurationModel.Value.ApiVersion)',
|
||||
healthCheckUrl: '@Url.Content("~/health/ready")'
|
||||
};
|
||||
var jsLocalizedMessages = {
|
||||
navigationFailed: '@localizer["NavigationFailed"]',
|
||||
serverUnreachable: @Json.Serialize(localizer["ServerUnreachable"].Value)
|
||||
};
|
||||
var jsLocalizedDialogs = {
|
||||
ok: '@localizer["Ok"]',
|
||||
@@ -139,6 +141,7 @@
|
||||
<script defer src="~/js/notifications.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/dialogs.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/image-viewer.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/server-connection-status.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/site.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/playlists.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/favorites.js" asp-append-version="true"></script>
|
||||
|
||||
@@ -2470,3 +2470,49 @@ html.audio-player-initializing .audio-player-container {
|
||||
.statistics-delete-button {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The global server unreachable banner is rendered by the active theme, or by the application fallback, and is toggled
|
||||
by server-connection-status.js. A theme can restyle it by overriding this class or the custom properties in its own
|
||||
stylesheet, which loads after this one. */
|
||||
.server-unreachable-banner {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 2px 16px;
|
||||
background-color: var(--server-unreachable-background-color, #c62828);
|
||||
color: var(--server-unreachable-text-color, #ffffff);
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.server-unreachable-banner.is-visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* The text pulses slowly, so the bar catches the eye without flashing. A theme can replace this with its own animation
|
||||
by targeting the server-unreachable-banner-text class, or by rendering its own text wrapper. */
|
||||
.server-unreachable-banner.is-visible .server-unreachable-banner-text {
|
||||
animation: server-unreachable-fade 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes server-unreachable-fade {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0.45;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.server-unreachable-banner.is-visible .server-unreachable-banner-text {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Shows the global server unreachable banner while the health probe or a SignalR connection reports the server as
|
||||
* unreachable. The banner markup comes from the theme template, with a fallback created here for themes that do not
|
||||
* provide one.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const unreachableSources = new Set();
|
||||
let banner = null;
|
||||
|
||||
/**
|
||||
* Creates the banner the first time it is needed, and appends it to the body, so it survives the AJAX navigation
|
||||
* that only swaps the content of the main element.
|
||||
* @returns {HTMLElement} The banner element.
|
||||
*/
|
||||
function getBanner() {
|
||||
if (banner !== null && banner.isConnected)
|
||||
return banner;
|
||||
// A theme renders the banner through its shared/server-unreachable-banner template, and the application renders a fallback
|
||||
// when it does not. The data hook is the contract the script toggles.
|
||||
banner = document.querySelector('[data-server-unreachable-banner]');
|
||||
if (banner !== null)
|
||||
return banner;
|
||||
banner = document.createElement('div');
|
||||
banner.id = 'server-unreachable-banner';
|
||||
banner.className = 'server-unreachable-banner';
|
||||
banner.setAttribute('data-server-unreachable-banner', '');
|
||||
banner.setAttribute('role', 'status');
|
||||
banner.setAttribute('aria-live', 'polite');
|
||||
banner.setAttribute('aria-atomic', 'true');
|
||||
banner.textContent = window.jsLocalizedMessages?.serverUnreachable ?? 'Server is unreachable';
|
||||
document.body.appendChild(banner);
|
||||
return banner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the banner while at least one live connection is unreachable, and hides it once every connection recovered.
|
||||
*/
|
||||
function refreshBanner() {
|
||||
getBanner().classList.toggle('is-visible', unreachableSources.size > 0);
|
||||
}
|
||||
|
||||
window.serverConnectionStatus = {
|
||||
/**
|
||||
* Marks a live connection as unreachable, showing the global banner.
|
||||
* @param {string} source - The name of the connection that lost its connection.
|
||||
*/
|
||||
markUnreachable: function (source) {
|
||||
unreachableSources.add(source);
|
||||
refreshBanner();
|
||||
},
|
||||
|
||||
/**
|
||||
* Marks a live connection as reachable again, hiding the global banner when no other connection is unreachable.
|
||||
* @param {string} source - The name of the connection that reconnected.
|
||||
*/
|
||||
markReachable: function (source) {
|
||||
unreachableSources.delete(source);
|
||||
refreshBanner();
|
||||
}
|
||||
};
|
||||
|
||||
// The health endpoint is the page independent source of the banner: it reports the API as unreachable even on pages
|
||||
// that have no SignalR connection, so the banner appears on every page while the server cannot serve requests.
|
||||
const HEALTH_CHECK_INTERVAL_MS = 5000;
|
||||
const HEALTH_CHECK_TIMEOUT_MS = 4000;
|
||||
const HEALTH_CHECK_SOURCE = 'healthCheck';
|
||||
let isHealthCheckInFlight = false;
|
||||
|
||||
/**
|
||||
* Schedules the next health probe, with a little jitter so many open tabs do not probe in lockstep.
|
||||
*/
|
||||
function scheduleNextHealthCheck() {
|
||||
const jitter = Math.round((Math.random() * 2 - 1) * HEALTH_CHECK_INTERVAL_MS * 0.2);
|
||||
setTimeout(() => {
|
||||
if (document.visibilityState === 'visible')
|
||||
checkServerHealthAsync();
|
||||
else
|
||||
scheduleNextHealthCheck();
|
||||
}, Math.max(1000, HEALTH_CHECK_INTERVAL_MS + jitter));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the server can reach the API and updates the global banner accordingly.
|
||||
*/
|
||||
async function checkServerHealthAsync() {
|
||||
const healthCheckUrl = window.globalConfiguration?.healthCheckUrl;
|
||||
if (!healthCheckUrl || isHealthCheckInFlight) {
|
||||
scheduleNextHealthCheck();
|
||||
return;
|
||||
}
|
||||
isHealthCheckInFlight = true;
|
||||
const controller = new AbortController();
|
||||
const timeoutHandle = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(healthCheckUrl, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
cache: 'no-store',
|
||||
signal: controller.signal
|
||||
});
|
||||
if (response.ok) {
|
||||
// The API is reachable. Only the sources that describe server reachability are cleared; a disconnected
|
||||
// SignalR hub keeps its own source until it reconnects.
|
||||
unreachableSources.delete(HEALTH_CHECK_SOURCE);
|
||||
unreachableSources.delete('api');
|
||||
window.isServerUnreachable = false;
|
||||
refreshBanner();
|
||||
} else {
|
||||
unreachableSources.add(HEALTH_CHECK_SOURCE);
|
||||
refreshBanner();
|
||||
}
|
||||
} catch {
|
||||
unreachableSources.add(HEALTH_CHECK_SOURCE);
|
||||
refreshBanner();
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle);
|
||||
isHealthCheckInFlight = false;
|
||||
scheduleNextHealthCheck();
|
||||
}
|
||||
}
|
||||
|
||||
checkServerHealthAsync();
|
||||
|
||||
refreshBanner();
|
||||
})();
|
||||
@@ -10,6 +10,58 @@ let enableConsoleDebugMessages = false; // whether to display debug messages at
|
||||
|
||||
var ajaxCallCounter = 0;
|
||||
|
||||
/**
|
||||
* Shows the server unreachable notification once, and marks the API source as unreachable. A later successful call
|
||||
* clears the state. It is used for network failures, never for an HTTP status the server actually answered with.
|
||||
*/
|
||||
function showServerUnreachableOnce() {
|
||||
window.serverConnectionStatus?.markUnreachable('api');
|
||||
if (window.isServerUnreachable)
|
||||
return;
|
||||
window.isServerUnreachable = true;
|
||||
notificationService.show(jsLocalizedMessages.serverUnreachable, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the API as reachable again after a response the server produced, whether it was successful or a client error.
|
||||
*/
|
||||
function markApiReachable() {
|
||||
window.isServerUnreachable = false;
|
||||
window.serverConnectionStatus?.markReachable('api');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an unsuccessful JSON response. An outage response marks the server unreachable and shows the single unreachable
|
||||
* notification; any other failure shows the message the server provided.
|
||||
* @param {Object} jsonResponse - The unsuccessful response payload.
|
||||
*/
|
||||
function handleApiFailure(jsonResponse) {
|
||||
if (jsonResponse.serverUnreachable === true) {
|
||||
showServerUnreachableOnce();
|
||||
return;
|
||||
}
|
||||
markApiReachable();
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an HTTP response with an unsuccessful status, showing the message the server provided when it can be read.
|
||||
* The server answered, so this is not treated as an unreachable server.
|
||||
* @param {Response} response - The unsuccessful response.
|
||||
*/
|
||||
async function showHttpErrorAsync(response) {
|
||||
markApiReachable();
|
||||
let message = response.statusText || `HTTP ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body && typeof body.errorMessage === 'string' && body.errorMessage.length > 0)
|
||||
message = body.errorMessage;
|
||||
} catch {
|
||||
// The body was not JSON, so the status text is the best message available.
|
||||
}
|
||||
notificationService.show(message, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
|
||||
//+======================================================================================+
|
||||
//| API interaction |
|
||||
@@ -32,17 +84,31 @@ async function callApiGetAsync(url) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error('Network response was not ok');
|
||||
const jsonResponse = await response.json();
|
||||
if (jsonResponse.success)
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return;
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
// The server answered, but not with the expected JSON, so this is not an unreachable server.
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return;
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
return jsonResponse.data;
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,20 +151,32 @@ async function callApiPostAsync(url, data, options = {}) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const jsonResponse = await response.json();
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return;
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return;
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
if (jsonResponse.message)
|
||||
notificationService.show(jsonResponse.message, NotificationType.SUCCESS);
|
||||
return jsonResponse.data;
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,20 +219,32 @@ async function callApiPutAsync(url, data, options = {}) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const jsonResponse = await response.json();
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return { success: false };
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return { success: false };
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
if (jsonResponse.message)
|
||||
notificationService.show(jsonResponse.message, NotificationType.SUCCESS);
|
||||
return { success: jsonResponse.success === true, data: jsonResponse.data };
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
return { success: false };
|
||||
}
|
||||
@@ -196,20 +286,32 @@ async function callApiDeleteAsync(url, options = {}) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const jsonResponse = await response.json();
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return;
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return;
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
if (jsonResponse.message)
|
||||
notificationService.show(jsonResponse.message, NotificationType.SUCCESS);
|
||||
return jsonResponse.success;
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,9 +339,28 @@ function initializeNavigation() {
|
||||
|
||||
// execute the view scripts of the initially loaded page, now that the application scripts are loaded; the view scripts are
|
||||
// stored with a non-executable type, so the browser does not run them before the application scripts are available
|
||||
showServerUnreachableNotificationIfNeeded();
|
||||
processViewScriptsAsync(document.querySelector('[data-section="scripts"]'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the navigation failed notification when the rendered page reports that its authorization could not reach the API,
|
||||
* then removes the marker so the notification is shown once per failed navigation. While the page is marked unreachable,
|
||||
* the API helpers suppress their own error notifications, because they all report the same outage.
|
||||
*/
|
||||
function showServerUnreachableNotificationIfNeeded() {
|
||||
const marker = document.getElementById('server-unreachable-marker');
|
||||
if (!marker) {
|
||||
window.isServerUnreachable = false;
|
||||
window.serverConnectionStatus?.markReachable('api');
|
||||
return;
|
||||
}
|
||||
marker.remove();
|
||||
window.isServerUnreachable = true;
|
||||
window.serverConnectionStatus?.markUnreachable('api');
|
||||
notificationService.show(jsLocalizedMessages.navigationFailed, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds AJAX navigation behavior to links marked with .nav-link class.
|
||||
*/
|
||||
@@ -375,6 +496,17 @@ async function updateContentAsync(url, addToHistory) {
|
||||
});
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else if (!response.ok) {
|
||||
// The server answered with an error page for the requested address. Keep the address the user asked for in the bar
|
||||
// and report the failed navigation once, instead of leaving the previous address and letting the missing content throw.
|
||||
const failedState = { url, content: document.querySelector('main').innerHTML, title: document.title };
|
||||
if (addToHistory)
|
||||
history.pushState(failedState, document.title, url);
|
||||
else
|
||||
history.replaceState(failedState, document.title, url);
|
||||
notificationService.show(jsLocalizedMessages.navigationFailed, NotificationType.ERROR);
|
||||
console.error('Navigation failed with status:', response.status);
|
||||
}
|
||||
else {
|
||||
const html = await response.text();
|
||||
|
||||
@@ -387,6 +519,8 @@ async function updateContentAsync(url, addToHistory) {
|
||||
// update the page content
|
||||
document.querySelector('main').innerHTML = content;
|
||||
document.title = title;
|
||||
// The page scripts may start calling the API immediately, so the outage flag must be set before they run.
|
||||
showServerUnreachableNotificationIfNeeded();
|
||||
|
||||
// process all scripts in order: component scripts first, then view scripts
|
||||
const componentScripts = doc.querySelectorAll('script[data-component-script]');
|
||||
|
||||
@@ -36,6 +36,12 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
/// </summary>
|
||||
public GetAuthorizationResponse AuthorizationResponse { get; set; } = new(Guid.NewGuid(), "Admin", Enum.GetValues<AuthorizationPermission>());
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the exception thrown when the <c>auth/get-authorization</c> endpoint is called, or <see langword="null"/> to return
|
||||
/// <see cref="AuthorizationResponse"/>. It simulates an API outage during authorization.
|
||||
/// </summary>
|
||||
public Exception? AuthorizationException { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the initialization response returned for the <c>initialization</c> endpoint.
|
||||
/// </summary>
|
||||
@@ -198,6 +204,7 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
_deleteSuccessEndpoints.Clear();
|
||||
_deleteExceptions.Clear();
|
||||
_blobResponse = null;
|
||||
AuthorizationException = null;
|
||||
GetEndpointsCalled.Clear();
|
||||
PostRequests.Clear();
|
||||
PutRequests.Clear();
|
||||
@@ -219,7 +226,11 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
if (endpoint.StartsWith(ApiRoutes.Initialization.CHECK_INITIALIZATION, StringComparison.OrdinalIgnoreCase))
|
||||
return Task.FromResult((TResponse)(object)InitializationResponse);
|
||||
if (endpoint.Contains("auth/get-authorization", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (AuthorizationException is not null)
|
||||
throw AuthorizationException;
|
||||
return Task.FromResult((TResponse)(object)AuthorizationResponse);
|
||||
}
|
||||
throw new InvalidOperationException($"No GET response is registered for the endpoint '{endpoint}'.");
|
||||
}
|
||||
|
||||
|
||||
+25
@@ -5,6 +5,7 @@ using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using Polly.CircuitBreaker;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
@@ -70,4 +71,28 @@ public class ManageRolesViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManageRoles_WhenTheApiIsUnreachableDuringAuthorization_ShouldRenderThePage()
|
||||
{
|
||||
// Arrange
|
||||
// The policy handler runs under real endpoint routing, where the authorization resource is the endpoint, not the HttpContext.
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationException = new BrokenCircuitException();
|
||||
RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()];
|
||||
PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("data-server-unreachable-banner", content);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -41,6 +41,7 @@ public class HomeErrorEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("text-danger", content);
|
||||
Assert.Contains("Navigation failed!", content);
|
||||
Assert.Contains("data-server-unreachable-banner", content);
|
||||
}
|
||||
}
|
||||
+67
-3
@@ -2,12 +2,16 @@
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
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 Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using Polly.CircuitBreaker;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -24,6 +28,7 @@ public class AuthorizationServiceTests
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly AuthorizationService _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly DefaultHttpContext _httpContext;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -34,9 +39,9 @@ public class AuthorizationServiceTests
|
||||
_userId = Guid.NewGuid();
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(httpContext);
|
||||
_httpContext = new DefaultHttpContext();
|
||||
_httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(_httpContext);
|
||||
_sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor);
|
||||
}
|
||||
|
||||
@@ -111,4 +116,63 @@ public class AuthorizationServiceTests
|
||||
Arg.Is<string>(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAJsonRequest_ShouldRethrow()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "application/json";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<BrokenCircuitException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.Unauthorized)]
|
||||
[InlineData(HttpStatusCode.Forbidden)]
|
||||
[InlineData(HttpStatusCode.NotFound)]
|
||||
public async Task HasPermissionAsync_WhenTheApiReturnsAnAuthorizationStatusDuringAPageNavigation_ShouldRethrow(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, statusCode)));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ApiException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
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 NSubstitute;
|
||||
using Polly.CircuitBreaker;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InitializationHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InitializationHandlerTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly InitializationHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InitializationHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public InitializationHandlerTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = new InitializationHandler(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<InitializationResponse>(new BrokenCircuitException()));
|
||||
AuthorizationHandlerContext context = CreateContext(httpContext);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiReturnsUnauthorizedDuringAPageNavigation_ShouldRethrow()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.Unauthorized)));
|
||||
AuthorizationHandlerContext context = CreateContext(httpContext);
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ApiException>(() => _sut.HandleAsync(context));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
|
||||
AuthorizationHandlerContext context = CreateContext(httpContext);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a page navigation HTTP context.
|
||||
/// </summary>
|
||||
/// <returns>The created HTTP context.</returns>
|
||||
private static DefaultHttpContext CreateHttpContext()
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Request.Headers.Accept = "text/html";
|
||||
return httpContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authorization context that evaluates the initialization requirement.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context of the request being authorized.</param>
|
||||
/// <returns>The created authorization context.</returns>
|
||||
private static AuthorizationHandlerContext CreateContext(HttpContext httpContext)
|
||||
{
|
||||
return new AuthorizationHandlerContext(
|
||||
[new InitializationRequirement()],
|
||||
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
|
||||
httpContext);
|
||||
}
|
||||
}
|
||||
+50
-2
@@ -1,8 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
@@ -19,6 +22,7 @@ namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
public class PermissionAuthorizationHandlerTests
|
||||
{
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly DefaultHttpContext _httpContext;
|
||||
private readonly PermissionAuthorizationHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
@@ -27,7 +31,13 @@ public class PermissionAuthorizationHandlerTests
|
||||
public PermissionAuthorizationHandlerTests()
|
||||
{
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_sut = new PermissionAuthorizationHandler(_mockAuthorizationService);
|
||||
_httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
|
||||
};
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
httpContextAccessor.HttpContext.Returns(_httpContext);
|
||||
_sut = new PermissionAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -75,12 +85,50 @@ public class PermissionAuthorizationHandlerTests
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
// The authorization service returns no role or permission when the API is unreachable, and marks the request instead.
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.User = new ClaimsPrincipal();
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authorization context that evaluates a requirement for the permission to manage media libraries.
|
||||
/// </summary>
|
||||
/// <returns>The created authorization context.</returns>
|
||||
private static AuthorizationHandlerContext CreateContext()
|
||||
{
|
||||
return new AuthorizationHandlerContext([new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)], new ClaimsPrincipal(), resource: null);
|
||||
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
|
||||
return new AuthorizationHandlerContext(
|
||||
[new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)],
|
||||
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
|
||||
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RoleAuthorizationHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RoleAuthorizationHandlerTests
|
||||
{
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly DefaultHttpContext _httpContext;
|
||||
private readonly RoleAuthorizationHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RoleAuthorizationHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RoleAuthorizationHandlerTests()
|
||||
{
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
|
||||
};
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
httpContextAccessor.HttpContext.Returns(_httpContext);
|
||||
_sut = new RoleAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheUserBelongsToTheRequiredRole_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheUserBelongsToNoneOfTheRequiredRoles_ShouldNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
// The authorization service returns no role when the API is unreachable, and marks the request instead.
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.User = new ClaimsPrincipal();
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authorization context that evaluates a requirement for the administrator role.
|
||||
/// </summary>
|
||||
/// <returns>The created authorization context.</returns>
|
||||
private static AuthorizationHandlerContext CreateContext()
|
||||
{
|
||||
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
|
||||
return new AuthorizationHandlerContext(
|
||||
[new RoleRequirement("Admin")],
|
||||
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
|
||||
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
|
||||
}
|
||||
}
|
||||
+106
-9
@@ -66,9 +66,59 @@ public class ExceptionHandlingMiddlewareTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsNonApiException_ShouldLogErrorAndWriteFailureJson()
|
||||
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndApiRequest_ShouldLogErrorAndWriteFailureJson()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Contains("application/json", httpContext.Response.ContentType);
|
||||
string body = await ReadResponseBodyAsync(httpContext);
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
// An ordinary bug is not an unreachable server, so the client must not switch to the outage path for it.
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
|
||||
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "Unexpected failure"),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE");
|
||||
httpContext.Request.Headers.Accept = "text/html";
|
||||
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
|
||||
Assert.Contains("text/html", httpContext.Response.ContentType);
|
||||
Assert.Contains("localized:InternalServerError", await ReadResponseBodyAsync(httpContext));
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "Unexpected failure"),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndRequestStatesNoPreference_ShouldWriteFailureJson()
|
||||
{
|
||||
// Arrange
|
||||
// A caller that sends no Accept header is not proven to be a browser, so it keeps the historical JSON envelope.
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
|
||||
|
||||
@@ -80,13 +130,24 @@ public class ExceptionHandlingMiddlewareTests
|
||||
string body = await ReadResponseBodyAsync(httpContext);
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("Unexpected failure", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "Unexpected failure"),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
|
||||
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndRawRequest_ShouldWriteStatusCodeWithoutBody()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
httpContext.Request.Headers.Accept = "audio/mpeg";
|
||||
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
|
||||
Assert.Equal(0, httpContext.Response.Body.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -297,9 +358,45 @@ public class ExceptionHandlingMiddlewareTests
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
string errorMessage = await ReadErrorMessageAsync(httpContext);
|
||||
string body = await ReadResponseBodyAsync(httpContext);
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
string errorMessage = jsonDocument.RootElement.GetProperty("errorMessage").GetString() ?? string.Empty;
|
||||
Assert.Contains("An error occurred.", errorMessage);
|
||||
Assert.Contains("localized:InternalServerError", errorMessage);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionHasNoProblemDetailsAndPageRequest_ShouldWriteHtmlErrorPage()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-US");
|
||||
_nextDelegate = _ => throw new ApiException(null, HttpStatusCode.InternalServerError, "/api/v1/libraries/1");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
|
||||
Assert.Contains("text/html", httpContext.Response.ContentType);
|
||||
Assert.Contains("localized:InternalServerError", await ReadResponseBodyAsync(httpContext));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionHasClientErrorAndPageRequest_ShouldWriteHtmlErrorPageWithTheRealStatusAndLocalizedMessage()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-US");
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Validation.Failed", title: "General.Validation", status: 422);
|
||||
_nextDelegate = _ => throw new ApiException(problemDetails, (HttpStatusCode)422);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(422, httpContext.Response.StatusCode);
|
||||
Assert.Contains("text/html", httpContext.Response.ContentType);
|
||||
Assert.Contains("localized:Validation.Failed", await ReadResponseBodyAsync(httpContext));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+43
-1
@@ -44,6 +44,7 @@ public class ThemeLayoutRendererTests
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IView _mockHeadView;
|
||||
private readonly IView _mockAudioPlayerView;
|
||||
private readonly IView _mockServerUnreachableBannerView;
|
||||
private readonly IView _mockScriptsView;
|
||||
private readonly IView _mockNavMenuView;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
@@ -75,10 +76,12 @@ public class ThemeLayoutRendererTests
|
||||
|
||||
_mockHeadView = CreateView("<head-fragment>");
|
||||
_mockAudioPlayerView = CreateView("<audio-fragment>");
|
||||
_mockServerUnreachableBannerView = CreateView("<banner-fragment>");
|
||||
_mockScriptsView = CreateView("<scripts-fragment>");
|
||||
_mockNavMenuView = CreateView("<nav-menu-fragment>");
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_ThemeLayoutHead", false).Returns(ViewEngineResult.Found("_ThemeLayoutHead", _mockHeadView));
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_AudioPlayer", false).Returns(ViewEngineResult.Found("_AudioPlayer", _mockAudioPlayerView));
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_ServerUnreachableBanner", false).Returns(ViewEngineResult.Found("_ServerUnreachableBanner", _mockServerUnreachableBannerView));
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_ThemeLayoutScripts", false).Returns(ViewEngineResult.Found("_ThemeLayoutScripts", _mockScriptsView));
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_NavMenu", false).Returns(ViewEngineResult.Found("_NavMenu", _mockNavMenuView));
|
||||
|
||||
@@ -87,7 +90,7 @@ public class ThemeLayoutRendererTests
|
||||
ThemeService themeService = new(_mockApiHttpClient);
|
||||
ThemeAudioPlayerBuilder audioPlayerBuilder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor);
|
||||
ThemeAudioPlayerRenderer audioPlayerRenderer = new(themeService, new ThemeTemplateEngine(), audioPlayerBuilder);
|
||||
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, audioPlayerRenderer, _mockHttpContextAccessor);
|
||||
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, audioPlayerRenderer, _mockHttpContextAccessor, _mockStringLocalizerFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -188,6 +191,45 @@ public class ThemeLayoutRendererTests
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenThemeProvidesServerUnreachableBannerTemplate_ShouldRenderItInTheLayout()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-banner");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{serverUnreachableBanner}}}", navTemplate: "nav:{{siteName}}");
|
||||
string bannerEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "editorial-banner")
|
||||
.Replace("{*pageKey}", "shared/server-unreachable-banner");
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(bannerEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(_themeTemplateResponseDtoFixture.Create(theme: theme, template: "banner:{{message}}"));
|
||||
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(page, "editorial-banner", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("My Page|banner:Localized-ServerUnreachable", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenThemeDoesNotProvideServerUnreachableBannerTemplate_ShouldRenderTheApplicationFallback()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-without-banner");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{serverUnreachableBanner}}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(page, "editorial-without-banner", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("My Page|<banner-fragment>", result.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the API responses that return the layout and navigation menu templates of the given theme.
|
||||
/// </summary>
|
||||
|
||||
Reference in new issue
Block a user