Fixes 401 Unauthorized API responses being incorrectly cached

This commit is contained in:
BinaryAlley committed 2024-12-25 18:34:49 +02:00
1 parent f246f0bf75
commit d6af519e17
37 files changed
+298 -174

No files matched your search

@@ -9,9 +9,9 @@ namespace Lumina.Contracts.Requests.Authorization;
/// <summary>
/// Represents a request for updating the authorization role and permissions of a user.
/// </summary>
/// <param name="RoleId">The Id of the user. Required.</param>
/// <param name="RoleId">The Id of the role. Required.</param>
/// <param name="Permissions">The collection of Ids of the permissions of the role. Required.</param>
/// <param name="UserId">The Id of the user. Required.</param>
/// <param name="RoleId">The Id of the role. Optional.</param>
/// <param name="Permissions">The collection of Ids of the permissions of the role. Optional.</param>
[DebuggerDisplay("UserId: {UserId}")]
public record UpdateUserRoleAndPermissionsRequest(
Guid? UserId,
@@ -35,8 +35,8 @@ public class UpdateUserRoleAndPermissionsEndpointSummary : Summary<UpdateUserRol
);
RequestParam(r => r.UserId, "The Id of the user. Required.");
RequestParam(r => r.RoleId, "The Id of the role. Required.");
RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Required.");
RequestParam(r => r.RoleId, "The Id of the role. Optional.");
RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Optional.");
ResponseParam<AuthorizationResponse>(r => r.UserId, "The id of the user whose role and permissions were updated.");
ResponseParam<AuthorizationResponse>(r => r.Role, "The authorization role entity.");
@@ -8,7 +8,6 @@ using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
@@ -44,6 +43,8 @@ public class ApiHttpClient : IApiHttpClient
ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value;
httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
@@ -4,8 +4,6 @@ using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Models.UsersManagement;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;
#endregion
@@ -17,17 +15,14 @@ namespace Lumina.Presentation.Web.Common.Authorization;
public class InitializationHandler : AuthorizationHandler<InitializationRequirement>
{
private readonly IApiHttpClient _apiHttpClient;
private readonly IMemoryCache _cache;
/// <summary>
/// Initializes a new instance of the <see cref="InitializationHandler"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected HTTP typed client for interactions with the API.</param>
/// <param name="cache">Cache for storing the initialization status.</param>
public InitializationHandler(IApiHttpClient apiHttpClient, IMemoryCache cache)
public InitializationHandler(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
_cache = cache;
}
/// <summary>
@@ -3,7 +3,9 @@ using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters.ActionFilters;
using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.MiddlewareFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Lumina.Presentation.Web.Common.Security;
@@ -25,6 +27,7 @@ using Polly.Wrap;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json.Serialization;
@@ -48,8 +51,8 @@ public static class PresentationWebLayerServices
{
services.AddControllersWithViews(mvcOptions =>
{
//mvcOptions.Filters.Add<ApiExceptionFilter>();
mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter
mvcOptions.Filters.Add<StoreLastViewFilter>();
})
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
@@ -129,34 +132,59 @@ public static class PresentationWebLayerServices
// handle redirects to work with different base paths
OnRedirectToLogin = redirectContext =>
{
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
// preserve any base path or subdirectory and add return URL
string redirectPath = redirectContext.RedirectUri;
// insert culture into the path
redirectPath = redirectPath.Replace("/auth/login", $"/{culture}/auth/login");
if (redirectContext.Request.PathBase.HasValue)
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(redirectContext.Request.PathBase + redirectContext.Request.Path);
redirectContext.Response.Redirect(redirectPath);
HttpContext httpContext = redirectContext.HttpContext;
string culture = httpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string? lastDisplayedView = httpContext.Session.GetString(HttpContextItemKeys.LAST_DISPLAYED_VIEW);
// build the login path considering reverse proxy and subfolder scenarios
string? originalHost = httpContext.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? httpContext.Request.Host.Value;
string? originalScheme = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? httpContext.Request.Scheme;
string? originalPathBase = httpContext.Request.Headers["X-Forwarded-Prefix"].FirstOrDefault() ?? httpContext.Request.PathBase.Value;
string baseUrl = $"{originalScheme}://{originalHost}{originalPathBase}";
string loginPath = $"{baseUrl}/{culture}/auth/login";
if (!string.IsNullOrEmpty(lastDisplayedView))
{
string returnUrl = Uri.EscapeDataString(lastDisplayedView);
redirectContext.RedirectUri = $"{loginPath}?returnUrl={returnUrl}";
}
else
redirectContext.RedirectUri = loginPath;
httpContext.Response.Redirect(redirectContext.RedirectUri);
return Task.CompletedTask;
},
OnRedirectToLogout = redirectContext =>
{
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string redirectPath = redirectContext.RedirectUri;
redirectPath = redirectPath.Replace("/auth/logout", $"/{culture}/auth/logout");
if (redirectContext.Request.PathBase.HasValue)
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.LogoutPath;
redirectContext.Response.Redirect(redirectPath);
HttpContext httpContext = redirectContext.HttpContext;
string culture = httpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string? originalHost = httpContext.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? httpContext.Request.Host.Value;
string? originalScheme = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? httpContext.Request.Scheme;
string? originalPathBase = httpContext.Request.Headers["X-Forwarded-Prefix"].FirstOrDefault() ?? httpContext.Request.PathBase.Value;
string baseUrl = $"{originalScheme}://{originalHost}{originalPathBase}";
string logoutPath = $"{baseUrl}/{culture}/auth/logout";
redirectContext.RedirectUri = logoutPath;
httpContext.Response.Redirect(redirectContext.RedirectUri);
return Task.CompletedTask;
},
OnRedirectToAccessDenied = redirectContext =>
{
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string redirectPath = redirectContext.RedirectUri;
redirectPath = redirectPath.Replace("/auth/access-denied", $"/{culture}/auth/access-denied");
if (redirectContext.Request.PathBase.HasValue)
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.AccessDeniedPath;
redirectContext.Response.Redirect(redirectPath);
HttpContext httpContext = redirectContext.HttpContext;
string culture = httpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string? originalHost = httpContext.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? httpContext.Request.Host.Value;
string? originalScheme = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? httpContext.Request.Scheme;
string? originalPathBase = httpContext.Request.Headers["X-Forwarded-Prefix"].FirstOrDefault() ?? httpContext.Request.PathBase.Value;
string baseUrl = $"{originalScheme}://{originalHost}{originalPathBase}";
string accessDeniedPath = $"{baseUrl}/{culture}/auth/access-denied";
redirectContext.RedirectUri = accessDeniedPath;
httpContext.Response.Redirect(redirectContext.RedirectUri);
return Task.CompletedTask;
}
};
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
#endregion
namespace Lumina.Presentation.Web.Common.Filters.ActionFilters;
/// <summary>
/// Stores the current view path in session, for actions that return ViewResult. This is needed because when JWT expires, user is redirected to Login view, with a returnUrl.
/// This returnUrl needs to be that of the last displayed view, not of the call that triggered the re-authentication request, which can be an API call for data.
/// </summary>
public class StoreLastViewFilter : IActionFilter
{
/// <summary>
/// Executes before the action method is called
/// </summary>
/// <param name="context">The action executing context</param>
public void OnActionExecuting(ActionExecutingContext context)
{
// no action needed before execution
}
/// <summary>
/// Executes after the action method is called
/// </summary>
/// <param name="context">The action executed context containing the action result</param>
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Result is ViewResult)
{
HttpContext httpContext = context.HttpContext;
if (httpContext.Request.Path != "/en-us/auth/login")
httpContext.Session.SetString(HttpContextItemKeys.LAST_DISPLAYED_VIEW, $"{httpContext.Request.PathBase}{httpContext.Request.Path}{httpContext.Request.QueryString}");
}
}
}
@@ -41,12 +41,13 @@ public class ApiAuthorizationFilter : IAsyncAuthorizationFilter
if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement))
context.Result = new ForbidResult();
}
catch (ApiException ex)
catch (ApiException ex) // TODO: check if it should really catch exceptions here
{
if (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
{
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
context.HttpContext.Response.Cookies.Delete("Token");
throw;
}
}
}
@@ -7,4 +7,5 @@ public static class HttpContextItemKeys
{
public const string ERRORS = "errors";
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
public const string LAST_DISPLAYED_VIEW = "LastViewUrl";
}
@@ -80,6 +80,20 @@ public class ExceptionHandlingMiddleware
// handle unauthorized errors by prompting the user to re-login
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
await HandleUnauthorizedAsync(context);
else if (apiException.HttpStatusCode == HttpStatusCode.Forbidden)
{
if (IsApiRequest(context))
{
string errorMessage = BuildErrorMessage(apiException);
await WriteJsonResponseAsync(context, new
{
success = false,
errorMessage
});
}
else
await context.ForbidAsync();
}
else
{
string errorMessage = BuildErrorMessage(apiException);
@@ -97,7 +111,7 @@ public class ExceptionHandlingMiddleware
private async Task HandleUnauthorizedAsync(HttpContext context)
{
// when API JWT tokens expire, the client app is still logged in, so, sign out the user and delete the authentication cookie and token
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
context.Response.Cookies.Delete("Token");
if (IsApiRequest(context))
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Models.Common;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Net;
using System.Net.Http;
@@ -41,15 +40,15 @@ public class CachedAuthorizationHandler : DelegatingHandler
string requestPath = request.RequestUri!.AbsolutePath;
// if it's any endpoint other than the one for the authorization request, fire it away towards the original API service
if (!requestPath.EndsWith(AUTHORIZATION_ENDPOINT, StringComparison.OrdinalIgnoreCase))
return await base.SendAsync(request, cancellationToken);
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
// otherwise, check the hybrid cache to see if there is a cached authorization
CachedResponseModel response = await _hybridCache.GetOrCreateAsync(
AUTHORIZATION_ENDPOINT,
async (cancellationToken) =>
{
// perform the actual API call if cache is empty or expired
HttpResponseMessage result = await base.SendAsync(request, cancellationToken);
string content = await result.Content.ReadAsStringAsync(cancellationToken);
HttpResponseMessage result = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
string content = await result.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// cache both status code and content
return new CachedResponseModel
{
@@ -63,6 +62,10 @@ public class CachedAuthorizationHandler : DelegatingHandler
},
cancellationToken: cancellationToken
);
// if the API returned 401 Unauthorized (i.e. token expired), DO NOT cache this response - it will be used for authorization endpoints even after successful login,
// resulting in incorrect login redirection cycles!
if (response.StatusCode == HttpStatusCode.Unauthorized)
await _hybridCache.RemoveAsync(AUTHORIZATION_ENDPOINT, cancellationToken).ConfigureAwait(false);
return new HttpResponseMessage(response.StatusCode)
{
Content = new StringContent(response.Content)
@@ -66,8 +66,6 @@ public class UrlService : IUrlService
foreach (PropertyInfo prop in additionalRouteValues.GetType().GetProperties())
routeValues.Add(prop.Name, prop.GetValue(additionalRouteValues));
// create route values based on whether the controller is localized
object values = needsCulture ? new { culture, action } : new { action };
return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: routeValues, scheme: scheme);
return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: routeValues, scheme: scheme);
}
}
@@ -62,7 +62,7 @@ public class AdminController : Controller
/// </summary>
/// <param name="roleId">The Id of the role for which to get the list of permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-permissions-by-role-id/{roleId}")]
[HttpGet("api-get-permissions-by-role-id/{roleId}")]
public async Task<IActionResult> GetPermissionsByRoleId(Guid roleId, CancellationToken cancellationToken)
{
RolePermissionsModel response = await _apiHttpClient.GetAsync<RolePermissionsModel>($"roles/{roleId}/permissions", cancellationToken).ConfigureAwait(false);
@@ -74,7 +74,7 @@ public class AdminController : Controller
/// </summary>
/// <param name="userId">The Id of the user for whom to get the list of permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-permissions-by-user-id/{userId}")]
[HttpGet("api-get-permissions-by-user-id/{userId}")]
public async Task<IActionResult> GetPermissionsByUserId(Guid userId, CancellationToken cancellationToken)
{
PermissionModel[] response = await _apiHttpClient.GetAsync<PermissionModel[]>($"auth/users/{userId}/permissions", cancellationToken).ConfigureAwait(false);
@@ -86,7 +86,7 @@ public class AdminController : Controller
/// </summary>
/// <param name="userId">The Id of the user for whom to get the role.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-role-by-user-id/{userId}")]
[HttpGet("api-get-role-by-user-id/{userId}")]
public async Task<IActionResult> GetRoleByUserId(Guid userId, CancellationToken cancellationToken)
{
RoleModel? response = await _apiHttpClient.GetAsync<RoleModel?>($"auth/users/{userId}/role", cancellationToken).ConfigureAwait(false);
@@ -97,7 +97,7 @@ public class AdminController : Controller
/// Gets the collection of authorization roles.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-roles")]
[HttpGet("api-get-roles")]
public async Task<IActionResult> GetRoles(CancellationToken cancellationToken)
{
RoleModel[] response = await _apiHttpClient.GetAsync<RoleModel[]>($"roles/", cancellationToken).ConfigureAwait(false);
@@ -109,7 +109,7 @@ public class AdminController : Controller
/// </summary>
/// <param name="model">The model containing the data of the role to be created.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpPost("create-role")]
[HttpPost("api-create-role")]
public async Task<IActionResult> CreateRole([FromBody] AddRoleRequestModel model, CancellationToken cancellationToken)
{
RolePermissionsModel response = await _apiHttpClient.PostAsync<RolePermissionsModel, AddRoleRequestModel>($"roles/", model, cancellationToken).ConfigureAwait(false);
@@ -121,7 +121,7 @@ public class AdminController : Controller
/// </summary>
/// <param name="model">The model containing the data of the role to be updated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpPut("update-role")]
[HttpPut("api-update-role")]
public async Task<IActionResult> UpdateRole([FromBody] UpdateRoleRequestModel model, CancellationToken cancellationToken)
{
RolePermissionsModel response = await _apiHttpClient.PutAsync<RolePermissionsModel, UpdateRoleRequestModel>($"roles/", model, cancellationToken).ConfigureAwait(false);
@@ -133,7 +133,7 @@ public class AdminController : Controller
/// </summary>
/// <param name="roleId">The Id of the role to be deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpDelete("delete-role/{roleId}")]
[HttpDelete("api-delete-role/{roleId}")]
public async Task<IActionResult> DeleteRole(Guid roleId, CancellationToken cancellationToken)
{
await _apiHttpClient.DeleteAsync($"roles/{roleId}", cancellationToken).ConfigureAwait(false);
@@ -145,7 +145,7 @@ public class AdminController : Controller
/// </summary>
/// <param name="model">The model containing the data of the role to be updated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpPut("update-user-authorization")]
[HttpPut("api-update-user-authorization")]
public async Task<IActionResult> UpdateUserAuthorization([FromBody] UpdateUserRoleAndPermissionsRequestModel model, CancellationToken cancellationToken)
{
GetAuthorizationResponse response = await _apiHttpClient.PutAsync<GetAuthorizationResponse, UpdateUserRoleAndPermissionsRequestModel>($"auth/users/{model.UserId}/role-and-permissions", model, cancellationToken).ConfigureAwait(false);
@@ -35,7 +35,7 @@ public class DirectoriesController : Controller
/// <param name="path">The path for which to get the directories.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-directories")]
[HttpGet("api-get-directories")]
public async Task<IActionResult> GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<DirectoryModel> response = await _apiHttpClient.GetAsync<DirectoryModel[]>(
@@ -49,9 +49,10 @@ public class DirectoriesController : Controller
/// <param name="path">The path for which to get the directories.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-tree-directories")]
[HttpGet("api-get-tree-directories")]
public async Task<IActionResult> GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
// TODO: check if it's really used
IEnumerable<FileSystemTreeNodeModel> response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
$"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
@@ -63,9 +64,10 @@ public class DirectoriesController : Controller
/// <param name="path">The path for which to get the directory tree.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-directory-tree")]
[HttpGet("api-get-directory-tree")]
public async Task<IActionResult> GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
// TODO: check if it's really used
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
$"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
@@ -31,7 +31,7 @@ public class DrivesController : Controller
/// Controller action for getting the list of all file system drives.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-drives")]
[HttpGet("api-get-drives")]
public async Task<IActionResult> GetDrives(CancellationToken cancellationToken)
{
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"drives/get-drives", cancellationToken).ConfigureAwait(false);
@@ -31,7 +31,7 @@ public class FileSystemController : Controller
/// Gets the type of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-type")]
[HttpGet("api-get-type")]
public async Task<IActionResult> GetType(CancellationToken cancellationToken)
{
FileSystemTypeModel response = await _apiHttpClient.GetAsync<FileSystemTypeModel>($"file-system/get-type", cancellationToken).ConfigureAwait(false);
@@ -35,7 +35,7 @@ public class FilesController : Controller
/// <param name="path">The path for which to get the files.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-tree-files")]
[HttpGet("api-get-tree-files")]
public async Task<IActionResult> GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<FileSystemTreeNodeModel> response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
@@ -49,9 +49,10 @@ public class FilesController : Controller
/// <param name="path">The path for which to get the files.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-files")]
[HttpGet("api-get-files")]
public async Task<IActionResult> GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
// TODO: check if it's really used
IEnumerable<FileModel> response = await _apiHttpClient.GetAsync<FileModel[]>(
$"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
@@ -33,9 +33,10 @@ public class PathController : Controller
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-root")]
[HttpGet("api-get-path-root")]
public async Task<IActionResult> GetPathRoot([FromQuery] string path, CancellationToken cancellationToken)
{
// TODO: check if it's really used
PathSegmentModel response = await _apiHttpClient.GetAsync<PathSegmentModel>($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = new { root = response } });
}
@@ -44,7 +45,7 @@ public class PathController : Controller
/// Gets the path separator character of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-separator")]
[HttpGet("api-get-path-separator")]
public async Task<IActionResult> GetPathSeparator(CancellationToken cancellationToken)
{
PathSeparatorModel response = await _apiHttpClient.GetAsync<PathSeparatorModel>($"path/get-path-separator", cancellationToken).ConfigureAwait(false);
@@ -56,7 +57,7 @@ public class PathController : Controller
/// </summary>
/// <param name="path">The path for which to get the parent path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-parent")]
[HttpGet("api-get-path-parent")]
public async Task<IActionResult> GetPathParent([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false);
@@ -68,7 +69,7 @@ public class PathController : Controller
/// </summary>
/// <param name="path">The path for which to get the path segments.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("split")]
[HttpGet("api-split")]
public async Task<IActionResult> SplitPath([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false);
@@ -80,7 +81,7 @@ public class PathController : Controller
/// </summary>
/// <param name="path">The path to be validated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("validate")]
[HttpGet("api-validate")]
public async Task<IActionResult> ValidatePath([FromQuery] string path, CancellationToken cancellationToken)
{
PathValidModel response = await _apiHttpClient.GetAsync<PathValidModel>($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false);
@@ -93,7 +94,7 @@ public class PathController : Controller
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("check-path-exists")]
[HttpGet("api-check-path-exists")]
public async Task<IActionResult> CheckPathExists([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
PathExistsModel response = await _apiHttpClient.GetAsync<PathExistsModel>(
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Attributes;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Models.Libraries;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -56,7 +54,7 @@ public class LibraryManagementController : Controller
/// <param name="data">The model containing the new library data.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[ValidateAntiForgeryToken]
[HttpPost("item")]
[HttpPost("api-item")]
public async Task<IActionResult> SaveLibrary([FromBody] LibraryModel data, CancellationToken cancellationToken)
{
// call different API endpoints based on whether this is a new library or an existing one
@@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
@@ -132,8 +133,8 @@ public class AuthController : Controller
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequestModel data, CancellationToken cancellationToken)
[HttpPost("api-register")]
public async Task<IActionResult> RegisterPost([FromBody] RegisterRequestModel data, CancellationToken cancellationToken)
{
// call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup
string endpoint = data.RegistrationType == "Admin" ? "initialization" : "auth/register";
@@ -149,8 +150,8 @@ public class AuthController : Controller
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequestModel data, CancellationToken cancellationToken)
[HttpPost("api-login")]
public async Task<IActionResult> LoginPost([FromBody] LoginRequestModel data, CancellationToken cancellationToken)
{
try
{
@@ -236,8 +237,8 @@ public class AuthController : Controller
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("recover-password")]
public async Task<IActionResult> RecoverPassword([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken)
[HttpPost("api-recover-password")]
public async Task<IActionResult> RecoverPasswordPost([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken)
{
RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync<RecoverPasswordResponseModel, RecoverPasswordRequestModel>("auth/recover-password", data, cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
@@ -249,8 +250,8 @@ public class AuthController : Controller
/// <param name="data">User credentials used for password change.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[ValidateAntiForgeryToken]
[HttpPost("change-password")]
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequestModel data, CancellationToken cancellationToken)
[HttpPost("api-change-password")]
public async Task<IActionResult> ChangePasswordPost([FromBody] ChangePasswordRequestModel data, CancellationToken cancellationToken)
{
data = data with { Username = User?.Identity?.Name }; // assign the currently logged in user as the user for which to change the password
ChangePasswordResponseModel response = await _apiHttpClient.PostAsync<ChangePasswordResponseModel, ChangePasswordRequestModel>("auth/change-password", data, cancellationToken).ConfigureAwait(false);
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>Neue Passwortbestätigung darf nicht leer sein!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>Sie sind nicht berechtigt, diese Ressource anzusehen!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>Sie sind nicht berechtigt, diesen Vorgang auszuführen!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>New password confirm cannot be empty!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>You are not authorized to view this resource!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>You are not authorized to perform this operation!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>¡La confirmación de la nueva contraseña no puede estar vacía!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>¡No estás autorizado para ver este recurso!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>¡No está autorizado para realizar esta operación!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>La confirmation du nouveau mot de passe ne peut pas être vide!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>Vous n'êtes pas autorisé à voir cette ressource !</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>Vous n'êtes pas autorisé à effectuer cette opération!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>La conferma della nuova password non può essere vuota!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>Non sei autorizzato a visualizzare questa risorsa!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>Non sei autorizzato a eseguire questa operazione!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>新しいパスワードの確認を入力してください!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>このリソースを表示する権限がありません!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>この操作を実行する権限がありません!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>New password confirm cannot be empty!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>You are not authorized to view this resource!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>You are not authorized to perform this operation!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>Confirmarea noii parole nu poate fi goală!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>Nu aveți autorizația necesară pentru vizualizarea aceastei resurse!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>Nu sunteți autorizat să efectuați această operațiune!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>Подтверждение нового пароля не может быть пустым!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>У вас нет прав для просмотра этого ресурса!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>У вас нет прав для выполнения этой операции!</value>
</data>
@@ -351,6 +351,9 @@
<data name="NewPasswordConfirmCannotBeEmpty" xml:space="preserve">
<value>新密码确认不能为空!</value>
</data>
<data name="Forbidden" xml:space="preserve">
<value>您无权查看此资源!</value>
</data>
<data name="NotAuthorized" xml:space="preserve">
<value>您无权执行此操作!</value>
</data>
@@ -91,7 +91,7 @@
NewPassword: txtNewPassword.value,
NewPasswordConfirm: txtNewPasswordConfirm.value
};
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")', formData);
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("ChangePasswordPost", "Auth")', formData);
if (data && data.isPasswordChanged === true) {
changePasswordSuccess.classList.replace('hidden', 'block');
divCurrentPassword.classList.add('hidden');
@@ -85,7 +85,7 @@
TotpCode: txtTotpCode.value,
ReturnUrl: returnUrlInput.value
};
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("Login", "Auth")', formData);
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("LoginPost", "Auth")', formData);
if (data && data.isTotpRequired === true) {
txtUsername.disabled = true;
txtPassword.disabled = true;
@@ -77,7 +77,7 @@
Username: txtUsername.value,
TotpCode: txtTotpCode.value
};
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")', formData);
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("RecoverPasswordPost", "Auth")', formData);
if (data && data.isPasswordReset === true) {
divUsername.classList.add('hidden');
btnValidateTotp.classList.add('hidden');
@@ -123,7 +123,7 @@
Use2fa: chkUse2FA.checked,
RegistrationType: form.querySelector('[name="RegistrationType"]').value
};
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("Register", "Auth")', formData);
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("RegisterPost", "Auth")', formData);
if (data) {
txtUsername.value = '';
txtPassword.value = '';
@@ -0,0 +1,4 @@
@*
/library/manage
*@
<p>libraries</p>
@@ -51,7 +51,7 @@
@_localizer["Library"]
</div>
<ul>
<li><a href="library/manage" class="nav-link"><span>@_localizer["ManageLibraries"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")" class="nav-link"><span>@_localizer["ManageLibraries"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link"><span>@_localizer["AddNewLibrary"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
@@ -150,7 +150,7 @@
<input type="radio" id="library-menu" name="menu">
<label for="library-menu">@_localizer["Library"]</label>
<ul>
<li tabindex="0"><a href="library/manage" class="nav-link">@_localizer["ManageLibraries"]</a></li>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")" class="nav-link">@_localizer["ManageLibraries"]</a></li>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link">@_localizer["AddNewLibrary"]</a></li>
<li class="has-submenu" tabindex="0">
<label>@_localizer["WrittenContent"]</label>
@@ -233,11 +233,11 @@
*/
async function getFileSystemPropertiesAsync() {
// call the API to get the file system type (platform type)
const fileSystemTypeResponse = await callApiGetAsync(`${clientBasePath}file-system/get-type`);
const fileSystemTypeResponse = await callApiGetAsync(`${clientBasePath}file-system/api-get-type`);
if (fileSystemTypeResponse !== undefined)
platformType = fileSystemTypeResponse.platformType;
// call the API to get the path separator for the file system
const pathSeparatorResponse = await callApiGetAsync(`${clientBasePath}path/get-path-separator`);
const pathSeparatorResponse = await callApiGetAsync(`${clientBasePath}path/api-get-path-separator`);
if (pathSeparatorResponse !== undefined)
pathSeparator = pathSeparatorResponse.pathSeparator;
}
@@ -248,7 +248,7 @@
* @returns {Promise<boolean>} A promise that resolves to whether the path is valid and exists, or not.
*/
async function checkPathAsync(path) {
const pathValidResponse = await callApiGetAsync(`${clientBasePath}path/validate?path=${encodeURIComponent(path)}`);
const pathValidResponse = await callApiGetAsync(`${clientBasePath}path/api-validate?path=${encodeURIComponent(path)}`);
if (pathValidResponse !== undefined) {
if (!pathValidResponse.isValid) {
notificationService.show("Specified path is not valid!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented
@@ -256,7 +256,7 @@
if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator))
addressBarInput.value += pathSeparator;
} else {
const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/check-path-exists?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`);
const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/api-check-path-exists?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`);
if (pathExistsResponse !== undefined && !pathExistsResponse.exists) {
notificationService.show("Specified path does not exist!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented
return false;
@@ -338,7 +338,7 @@
async function navigateUpAsync() {
if (addressBarInput.value !== null) {
// ask the API for the parent path
const parentLocationResponse = await callApiGetAsync(`${clientBasePath}path/get-path-parent?path=${encodeURIComponent(addressBarInput.value)}`);
const parentLocationResponse = await callApiGetAsync(`${clientBasePath}path/api-get-path-parent?path=${encodeURIComponent(addressBarInput.value)}`);
if (parentLocationResponse !== undefined && parentLocationResponse.pathSegments !== null) {
// if the answer was valid, and we can navigate up, reconstruct the provided path from its segments, and navigate to it
platformType = parentLocationResponse.pathSegments;
@@ -362,7 +362,7 @@
* @param {any} path The path for which to get the navigator path segments.
*/
async function getNavigatorPathAsync(path) {
const pathSplitResponse = await callApiGetAsync(`${clientBasePath}path/split?path=${encodeURIComponent(path)}`);
const pathSplitResponse = await callApiGetAsync(`${clientBasePath}path/api-split?path=${encodeURIComponent(path)}`);
if (pathSplitResponse !== undefined)
renderAddressBar(pathSplitResponse.pathSegments);
}
@@ -589,7 +589,7 @@
* @returns {Promise<Array<Object>|undefined>} A promise that resolves to an array of drive objects, or undefined if the API call fails.
*/
async function getFileSystemDrivesAsync() {
const getDrivesResponse = await callApiGetAsync(`${clientBasePath}drives/get-drives`);
const getDrivesResponse = await callApiGetAsync(`${clientBasePath}drives/api-get-drives`);
if (getDrivesResponse !== undefined)
return getDrivesResponse.drives;
}
@@ -716,7 +716,7 @@
* @param {Function} callback - Function to call for each directory received.
*/
async function fetchFileSystemDirectoriesAsync(path, callback) {
await fetchJsonDataAsync(`${clientBasePath}directories/get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory');
await fetchJsonDataAsync(`${clientBasePath}directories/api-get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory');
}
/**
@@ -725,7 +725,7 @@
* @param {Function} callback - Function to call for each file received.
*/
async function fetchFileSystemFilesAsync(path, callback) {
await fetchJsonDataAsync(`${clientBasePath}files/get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File');
await fetchJsonDataAsync(`${clientBasePath}files/api-get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File');
}
/**
+92 -84
View File
@@ -23,8 +23,12 @@ var ajaxCallCounter = 0;
*/
async function callApiGetAsync(url) {
try {
// create the URL for the API endpoint
const response = await fetch(url); // call the API
// call the API
const response = await fetch(url, {
headers: {
'Accept': 'application/json'
}
});
if (response.redirected) // if a redirect is requested, perform it
window.location.href = response.url;
else {
@@ -279,85 +283,88 @@ async function updateContentAsync(url, addToHistory) {
}
const response = await fetch(url);
const html = await response.text();
if (response.redirected) // if a redirect is requested, perform it
window.location.href = response.url;
else {
const html = await response.text();
// parse the new content
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const content = doc.querySelector('main').innerHTML;
const title = doc.querySelector('title')?.textContent || document.title;
// parse the new content
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const content = doc.querySelector('main').innerHTML;
const title = doc.querySelector('title')?.textContent || document.title;
// update the page content
document.querySelector('main').innerHTML = content;
document.title = title;
// update the page content
document.querySelector('main').innerHTML = content;
document.title = title;
// process all scripts in order: component scripts first, then view scripts
const componentScripts = doc.querySelectorAll('script[data-component-script]');
for (const script of componentScripts) {
const newScript = document.createElement('script');
// copy script attributes
Array.from(script.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
if (script.src) {
// wait for external script to fully load before continuing
await new Promise((resolve, reject) => {
newScript.onload = resolve;
newScript.onerror = reject;
document.body.appendChild(newScript);
// process all scripts in order: component scripts first, then view scripts
const componentScripts = doc.querySelectorAll('script[data-component-script]');
for (const script of componentScripts) {
const newScript = document.createElement('script');
// copy script attributes
Array.from(script.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
if (script.src) {
// wait for external script to fully load before continuing
await new Promise((resolve, reject) => {
newScript.onload = resolve;
newScript.onerror = reject;
document.body.appendChild(newScript);
});
}
}
}
// execute component initialization scripts
const componentInits = doc.querySelectorAll('script[data-component-init]');
for (const script of componentInits) {
const newScript = document.createElement('script');
// copy script attributes
Array.from(script.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
newScript.textContent = script.textContent;
document.body.appendChild(newScript);
}
// process view scripts
const viewScripts = doc.querySelector('[data-section="scripts"]')?.getElementsByTagName('script') || [];
// get or create scripts container
let scriptsContainer = document.querySelector('[data-section="scripts"]');
if (!scriptsContainer) {
scriptsContainer = document.createElement('div');
scriptsContainer.setAttribute('data-section', 'scripts');
document.body.appendChild(scriptsContainer);
}
// clear existing scripts in container
scriptsContainer.innerHTML = '';
// process view scripts
for (const script of viewScripts) {
const scriptId = script.getAttribute('data-form');
// remove existing script with same Id if it exists
const existingScript = document.querySelector(`script[data-form="${scriptId}"]`);
if (existingScript)
existingScript.remove();
const newScript = document.createElement('script');
// copy script attributes
Array.from(script.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
// handle both inline and external scripts
if (script.src) {
newScript.src = script.src;
// wait for external script to load
await new Promise((resolve, reject) => {
newScript.onload = resolve;
newScript.onerror = reject;
// execute component initialization scripts
const componentInits = doc.querySelectorAll('script[data-component-init]');
for (const script of componentInits) {
const newScript = document.createElement('script');
// copy script attributes
Array.from(script.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
} else {
// wrap inline scripts in a safety check
newScript.textContent = `
newScript.textContent = script.textContent;
document.body.appendChild(newScript);
}
// process view scripts
const viewScripts = doc.querySelector('[data-section="scripts"]')?.getElementsByTagName('script') || [];
// get or create scripts container
let scriptsContainer = document.querySelector('[data-section="scripts"]');
if (!scriptsContainer) {
scriptsContainer = document.createElement('div');
scriptsContainer.setAttribute('data-section', 'scripts');
document.body.appendChild(scriptsContainer);
}
// clear existing scripts in container
scriptsContainer.innerHTML = '';
// process view scripts
for (const script of viewScripts) {
const scriptId = script.getAttribute('data-form');
// remove existing script with same Id if it exists
const existingScript = document.querySelector(`script[data-form="${scriptId}"]`);
if (existingScript)
existingScript.remove();
const newScript = document.createElement('script');
// copy script attributes
Array.from(script.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
// handle both inline and external scripts
if (script.src) {
newScript.src = script.src;
// wait for external script to load
await new Promise((resolve, reject) => {
newScript.onload = resolve;
newScript.onerror = reject;
});
} else {
// wrap inline scripts in a safety check
newScript.textContent = `
(function() {
const safeGetElement = (id) => document.getElementById(id);
const safeAddEventListener = (element, e, handler) => {
@@ -367,17 +374,18 @@ async function updateContentAsync(url, addToHistory) {
${script.textContent}
})();
`;
}
// add script to scripts container
scriptsContainer.appendChild(newScript);
}
// add script to scripts container
scriptsContainer.appendChild(newScript);
}
// bind navigation links in the new content
bindNavigationLinks();
// bind navigation links in the new content
bindNavigationLinks();
// save to history if needed
if (addToHistory) {
const state = { url, content, title };
history.pushState(state, title, url);
// save to history if needed
if (addToHistory) {
const state = { url, content, title };
history.pushState(state, title, url);
}
}
} catch (error) {
notificationService.show(jsLocalizedMessages.navigationFailed, NotificationType.ERROR);