From d6af519e179667b18185cdbb276700a2ba627bd3 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 25 Dec 2024 18:34:49 +0200 Subject: [PATCH] Fixes 401 Unauthorized API responses being incorrectly cached --- .../UpdateUserRoleAndPermissionsRequest.cs | 6 +- ...teUserRoleAndPermissionsEndpointSummary.cs | 4 +- .../Common/Api/ApiHttpClient.cs | 3 +- .../Authorization/InitializationHandler.cs | 7 +- .../PresentationWebLayerServices.cs | 70 ++++--- .../ActionFilters/StoreLastViewFilter.cs | 38 ++++ .../ApiAuthorizationFilter.cs | 5 +- .../Common/Http/HttpContextItemKeys.cs | 1 + .../ExceptionHandlingMiddleware.cs | 16 +- .../Services/CachedAuthorizationHandler.cs | 11 +- .../Common/Services/UrlService.cs | 4 +- .../Controllers/AdminController.cs | 16 +- .../DirectoriesController.cs | 8 +- .../FileSystemManagement/DrivesController.cs | 2 +- .../FileSystemController.cs | 2 +- .../FileSystemManagement/FilesController.cs | 5 +- .../FileSystemManagement/PathController.cs | 13 +- .../Management/LibraryManagementController.cs | 4 +- .../UsersManagement/AuthController.cs | 17 +- .../ExceptionHandlingMiddleware.de-DE.resx | 3 + .../ExceptionHandlingMiddleware.en-US.resx | 3 + .../ExceptionHandlingMiddleware.es-ES.resx | 3 + .../ExceptionHandlingMiddleware.fr-FR.resx | 3 + .../ExceptionHandlingMiddleware.it-IT.resx | 3 + .../ExceptionHandlingMiddleware.ja-JP.resx | 3 + .../ExceptionHandlingMiddleware.resx | 3 + .../ExceptionHandlingMiddleware.ro-RO.resx | 3 + .../ExceptionHandlingMiddleware.ru-RU.resx | 3 + .../ExceptionHandlingMiddleware.zh-CN.resx | 3 + .../Views/Auth/ChangePassword.cshtml | 2 +- .../Views/Auth/Login.cshtml | 2 +- .../Views/Auth/RecoverPassword.cshtml | 2 +- .../Views/Auth/Register.cshtml | 2 +- .../Views/Library/Management/Index.cshtml | 4 + .../Views/Shared/_NavMenu.cshtml | 4 +- .../wwwroot/js/file-system-browser-dialog.js | 18 +- .../wwwroot/js/site.js | 176 +++++++++--------- 37 files changed, 298 insertions(+), 174 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/Filters/ActionFilters/StoreLastViewFilter.cs create mode 100644 src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml diff --git a/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs b/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs index 68742ee4..7a1ac023 100644 --- a/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs @@ -9,9 +9,9 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// Represents a request for updating the authorization role and permissions of a user. /// -/// The Id of the user. Required. -/// The Id of the role. Required. -/// The collection of Ids of the permissions of the role. Required. +/// The Id of the user. Required. +/// The Id of the role. Optional. +/// The collection of Ids of the permissions of the role. Optional. [DebuggerDisplay("UserId: {UserId}")] public record UpdateUserRoleAndPermissionsRequest( Guid? UserId, diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs index 39ee8627..f1446150 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs @@ -35,8 +35,8 @@ public class UpdateUserRoleAndPermissionsEndpointSummary : Summary 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(r => r.UserId, "The id of the user whose role and permissions were updated."); ResponseParam(r => r.Role, "The authorization role entity."); diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index 87e6c801..f904959d 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -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, diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs index ccf3aec8..51dd850c 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs @@ -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 { private readonly IApiHttpClient _apiHttpClient; - private readonly IMemoryCache _cache; /// /// Initializes a new instance of the class. /// /// Injected HTTP typed client for interactions with the API. - /// Cache for storing the initialization status. - public InitializationHandler(IApiHttpClient apiHttpClient, IMemoryCache cache) + public InitializationHandler(IApiHttpClient apiHttpClient) { _apiHttpClient = apiHttpClient; - _cache = cache; } /// diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 05197e4c..cda383c2 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -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(); mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter + mvcOptions.Filters.Add(); }) .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; } }; diff --git a/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/StoreLastViewFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/StoreLastViewFilter.cs new file mode 100644 index 00000000..cb8946be --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/StoreLastViewFilter.cs @@ -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; + +/// +/// 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. +/// +public class StoreLastViewFilter : IActionFilter +{ + /// + /// Executes before the action method is called + /// + /// The action executing context + public void OnActionExecuting(ActionExecutingContext context) + { + // no action needed before execution + } + + /// + /// Executes after the action method is called + /// + /// The action executed context containing the action result + 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}"); + } + } +} diff --git a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs index c6bf492a..0375fb54 100644 --- a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs +++ b/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs @@ -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; } } } diff --git a/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs index f47a0ec7..440e00f6 100644 --- a/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs +++ b/src/Lumina.Presentation.Web/Common/Http/HttpContextItemKeys.cs @@ -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"; } diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs index 11bc559a..56621ec3 100644 --- a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -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)) diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs b/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs index 0d118442..d9bc83c4 100644 --- a/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs @@ -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) diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs index 00ef414e..1f3cfd9f 100644 --- a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -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); } } diff --git a/src/Lumina.Presentation.Web/Controllers/AdminController.cs b/src/Lumina.Presentation.Web/Controllers/AdminController.cs index b83e9591..e87aad2c 100644 --- a/src/Lumina.Presentation.Web/Controllers/AdminController.cs +++ b/src/Lumina.Presentation.Web/Controllers/AdminController.cs @@ -62,7 +62,7 @@ public class AdminController : Controller /// /// The Id of the role for which to get the list of permissions. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-permissions-by-role-id/{roleId}")] + [HttpGet("api-get-permissions-by-role-id/{roleId}")] public async Task GetPermissionsByRoleId(Guid roleId, CancellationToken cancellationToken) { RolePermissionsModel response = await _apiHttpClient.GetAsync($"roles/{roleId}/permissions", cancellationToken).ConfigureAwait(false); @@ -74,7 +74,7 @@ public class AdminController : Controller /// /// The Id of the user for whom to get the list of permissions. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-permissions-by-user-id/{userId}")] + [HttpGet("api-get-permissions-by-user-id/{userId}")] public async Task GetPermissionsByUserId(Guid userId, CancellationToken cancellationToken) { PermissionModel[] response = await _apiHttpClient.GetAsync($"auth/users/{userId}/permissions", cancellationToken).ConfigureAwait(false); @@ -86,7 +86,7 @@ public class AdminController : Controller /// /// The Id of the user for whom to get the role. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-role-by-user-id/{userId}")] + [HttpGet("api-get-role-by-user-id/{userId}")] public async Task GetRoleByUserId(Guid userId, CancellationToken cancellationToken) { RoleModel? response = await _apiHttpClient.GetAsync($"auth/users/{userId}/role", cancellationToken).ConfigureAwait(false); @@ -97,7 +97,7 @@ public class AdminController : Controller /// Gets the collection of authorization roles. /// /// Cancellation token that can be used to stop the execution. - [HttpGet("get-roles")] + [HttpGet("api-get-roles")] public async Task GetRoles(CancellationToken cancellationToken) { RoleModel[] response = await _apiHttpClient.GetAsync($"roles/", cancellationToken).ConfigureAwait(false); @@ -109,7 +109,7 @@ public class AdminController : Controller /// /// The model containing the data of the role to be created. /// Cancellation token that can be used to stop the execution. - [HttpPost("create-role")] + [HttpPost("api-create-role")] public async Task CreateRole([FromBody] AddRoleRequestModel model, CancellationToken cancellationToken) { RolePermissionsModel response = await _apiHttpClient.PostAsync($"roles/", model, cancellationToken).ConfigureAwait(false); @@ -121,7 +121,7 @@ public class AdminController : Controller /// /// The model containing the data of the role to be updated. /// Cancellation token that can be used to stop the execution. - [HttpPut("update-role")] + [HttpPut("api-update-role")] public async Task UpdateRole([FromBody] UpdateRoleRequestModel model, CancellationToken cancellationToken) { RolePermissionsModel response = await _apiHttpClient.PutAsync($"roles/", model, cancellationToken).ConfigureAwait(false); @@ -133,7 +133,7 @@ public class AdminController : Controller /// /// The Id of the role to be deleted. /// Cancellation token that can be used to stop the execution. - [HttpDelete("delete-role/{roleId}")] + [HttpDelete("api-delete-role/{roleId}")] public async Task DeleteRole(Guid roleId, CancellationToken cancellationToken) { await _apiHttpClient.DeleteAsync($"roles/{roleId}", cancellationToken).ConfigureAwait(false); @@ -145,7 +145,7 @@ public class AdminController : Controller /// /// The model containing the data of the role to be updated. /// Cancellation token that can be used to stop the execution. - [HttpPut("update-user-authorization")] + [HttpPut("api-update-user-authorization")] public async Task UpdateUserAuthorization([FromBody] UpdateUserRoleAndPermissionsRequestModel model, CancellationToken cancellationToken) { GetAuthorizationResponse response = await _apiHttpClient.PutAsync($"auth/users/{model.UserId}/role-and-permissions", model, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs index dd46cd03..add2a4d1 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs @@ -35,7 +35,7 @@ public class DirectoriesController : Controller /// The path for which to get the directories. /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-directories")] + [HttpGet("api-get-directories")] public async Task GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { IEnumerable response = await _apiHttpClient.GetAsync( @@ -49,9 +49,10 @@ public class DirectoriesController : Controller /// The path for which to get the directories. /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-tree-directories")] + [HttpGet("api-get-tree-directories")] public async Task GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { + // TODO: check if it's really used IEnumerable response = await _apiHttpClient.GetAsync( $"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 /// The path for which to get the directory tree. /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-directory-tree")] + [HttpGet("api-get-directory-tree")] public async Task GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { + // TODO: check if it's really used FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync( $"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs index a247b5c3..b3b5efe9 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs @@ -31,7 +31,7 @@ public class DrivesController : Controller /// Controller action for getting the list of all file system drives. /// /// Cancellation token that can be used to stop the execution. - [HttpGet("get-drives")] + [HttpGet("api-get-drives")] public async Task GetDrives(CancellationToken cancellationToken) { FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"drives/get-drives", cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs index 17e03c65..3844edaf 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs @@ -31,7 +31,7 @@ public class FileSystemController : Controller /// Gets the type of the file system. /// /// Cancellation token that can be used to stop the execution. - [HttpGet("get-type")] + [HttpGet("api-get-type")] public async Task GetType(CancellationToken cancellationToken) { FileSystemTypeModel response = await _apiHttpClient.GetAsync($"file-system/get-type", cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs index 1fc3ded5..ab1a5517 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs @@ -35,7 +35,7 @@ public class FilesController : Controller /// The path for which to get the files. /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-tree-files")] + [HttpGet("api-get-tree-files")] public async Task GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { IEnumerable response = await _apiHttpClient.GetAsync( @@ -49,9 +49,10 @@ public class FilesController : Controller /// The path for which to get the files. /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-files")] + [HttpGet("api-get-files")] public async Task GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { + // TODO: check if it's really used IEnumerable response = await _apiHttpClient.GetAsync( $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs index 650a9a24..177a63a8 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs @@ -33,9 +33,10 @@ public class PathController : Controller /// /// The path for which to get the root. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-path-root")] + [HttpGet("api-get-path-root")] public async Task GetPathRoot([FromQuery] string path, CancellationToken cancellationToken) { + // TODO: check if it's really used PathSegmentModel response = await _apiHttpClient.GetAsync($"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. /// /// Cancellation token that can be used to stop the execution. - [HttpGet("get-path-separator")] + [HttpGet("api-get-path-separator")] public async Task GetPathSeparator(CancellationToken cancellationToken) { PathSeparatorModel response = await _apiHttpClient.GetAsync($"path/get-path-separator", cancellationToken).ConfigureAwait(false); @@ -56,7 +57,7 @@ public class PathController : Controller /// /// The path for which to get the parent path. /// Cancellation token that can be used to stop the execution. - [HttpGet("get-path-parent")] + [HttpGet("api-get-path-parent")] public async Task GetPathParent([FromQuery] string path, CancellationToken cancellationToken) { PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); @@ -68,7 +69,7 @@ public class PathController : Controller /// /// The path for which to get the path segments. /// Cancellation token that can be used to stop the execution. - [HttpGet("split")] + [HttpGet("api-split")] public async Task SplitPath([FromQuery] string path, CancellationToken cancellationToken) { PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); @@ -80,7 +81,7 @@ public class PathController : Controller /// /// The path to be validated. /// Cancellation token that can be used to stop the execution. - [HttpGet("validate")] + [HttpGet("api-validate")] public async Task ValidatePath([FromQuery] string path, CancellationToken cancellationToken) { PathValidModel response = await _apiHttpClient.GetAsync($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); @@ -93,7 +94,7 @@ public class PathController : Controller /// The path to be checked. /// Whether to include hidden file system elements or not. /// Cancellation token that can be used to stop the execution. - [HttpGet("check-path-exists")] + [HttpGet("api-check-path-exists")] public async Task CheckPathExists([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { PathExistsModel response = await _apiHttpClient.GetAsync( diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs index e83265aa..4c5b71b1 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -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 /// The model containing the new library data. /// Cancellation token that can be used to stop the execution. [ValidateAntiForgeryToken] - [HttpPost("item")] + [HttpPost("api-item")] public async Task SaveLibrary([FromBody] LibraryModel data, CancellationToken cancellationToken) { // call different API endpoints based on whether this is a new library or an existing one diff --git a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs index f4c0a541..59b689de 100644 --- a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs +++ b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs @@ -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 /// Cancellation token that can be used to stop the execution. [AllowAnonymous] [ValidateAntiForgeryToken] - [HttpPost("register")] - public async Task Register([FromBody] RegisterRequestModel data, CancellationToken cancellationToken) + [HttpPost("api-register")] + public async Task 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 /// Cancellation token that can be used to stop the execution. [AllowAnonymous] [ValidateAntiForgeryToken] - [HttpPost("login")] - public async Task Login([FromBody] LoginRequestModel data, CancellationToken cancellationToken) + [HttpPost("api-login")] + public async Task LoginPost([FromBody] LoginRequestModel data, CancellationToken cancellationToken) { try { @@ -236,8 +237,8 @@ public class AuthController : Controller /// Cancellation token that can be used to stop the execution. [AllowAnonymous] [ValidateAntiForgeryToken] - [HttpPost("recover-password")] - public async Task RecoverPassword([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken) + [HttpPost("api-recover-password")] + public async Task RecoverPasswordPost([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken) { RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync("auth/recover-password", data, cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); @@ -249,8 +250,8 @@ public class AuthController : Controller /// User credentials used for password change. /// Cancellation token that can be used to stop the execution. [ValidateAntiForgeryToken] - [HttpPost("change-password")] - public async Task ChangePassword([FromBody] ChangePasswordRequestModel data, CancellationToken cancellationToken) + [HttpPost("api-change-password")] + public async Task 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("auth/change-password", data, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 4e35f2b6..b62e24c8 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -351,6 +351,9 @@ Neue Passwortbestätigung darf nicht leer sein! + + Sie sind nicht berechtigt, diese Ressource anzusehen! + Sie sind nicht berechtigt, diesen Vorgang auszuführen! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index cf429712..f949be0c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -351,6 +351,9 @@ New password confirm cannot be empty! + + You are not authorized to view this resource! + You are not authorized to perform this operation! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index af94dbd3..da624ff0 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -351,6 +351,9 @@ ¡La confirmación de la nueva contraseña no puede estar vacía! + + ¡No estás autorizado para ver este recurso! + ¡No está autorizado para realizar esta operación! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 14d01457..5c0d6138 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -351,6 +351,9 @@ La confirmation du nouveau mot de passe ne peut pas être vide! + + Vous n'êtes pas autorisé à voir cette ressource ! + Vous n'êtes pas autorisé à effectuer cette opération! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 41489661..c8b8d4c9 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -351,6 +351,9 @@ La conferma della nuova password non può essere vuota! + + Non sei autorizzato a visualizzare questa risorsa! + Non sei autorizzato a eseguire questa operazione! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index b5c7eb36..539f4afc 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -351,6 +351,9 @@ 新しいパスワードの確認を入力してください! + + このリソースを表示する権限がありません! + この操作を実行する権限がありません! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 51b66fad..3d70ef17 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -351,6 +351,9 @@ New password confirm cannot be empty! + + You are not authorized to view this resource! + You are not authorized to perform this operation! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index 0b13bb89..b698683c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -351,6 +351,9 @@ Confirmarea noii parole nu poate fi goală! + + Nu aveți autorizația necesară pentru vizualizarea aceastei resurse! + Nu sunteți autorizat să efectuați această operațiune! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index bbe9306a..24a1ccb7 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -351,6 +351,9 @@ Подтверждение нового пароля не может быть пустым! + + У вас нет прав для просмотра этого ресурса! + У вас нет прав для выполнения этой операции! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 1ea6f1ed..dad89403 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -351,6 +351,9 @@ 新密码确认不能为空! + + 您无权查看此资源! + 您无权执行此操作! diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml index 5f5eedb4..fb971570 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml @@ -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'); diff --git a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml index 70b2627e..29615bec 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml @@ -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; diff --git a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml index f2f903ca..4174e487 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml @@ -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'); diff --git a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml index 7474c99d..d1634a86 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml @@ -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 = ''; diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml new file mode 100644 index 00000000..153c525c --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml @@ -0,0 +1,4 @@ +@* +/library/manage +*@ +

libraries

diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml index 9cd043c8..b50817b8 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -51,7 +51,7 @@ @_localizer["Library"]
@@ -150,7 +150,7 @@
    -
  • @_localizer["ManageLibraries"]
  • +
  • @_localizer["ManageLibraries"]
  • @_localizer["AddNewLibrary"]
  • diff --git a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js index 851c8e29..a3e87f67 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js @@ -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} 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|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'); } /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 9bb38ac5..4eb4776f 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -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);