From 2c31fd8714bc96aa3d704863788bc3de3b3c80d0 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 20 Nov 2024 21:08:34 +0200 Subject: [PATCH] Adds localization to Lumina.Presentation.Web project --- .../GetThumbnailQueryValidator.cs | 2 +- .../Common/Errors/Errors.Thumbnails.cs | 2 +- .../Validation/FluentValidationOptions.cs | 1 - .../PresentationApiLayerServices.cs | 10 +- src/Lumina.Presentation.Api/Program.cs | 5 +- .../Authorization/InitializationHandler.cs | 2 +- .../PresentationWebLayerServices.cs | 144 ++++++--- .../Common/Filters/ApiExceptionFilter.cs | 53 +++- .../Filters/InitializationCheckAttribute.cs | 4 +- .../MiddlewareFilters/LocalizationPipeline.cs | 28 ++ .../Middlewares/CultureRedirectMiddleware.cs | 47 +++ .../Common/Services/IUrlService.cs | 3 + .../Common/Services/UrlService.cs | 33 +- .../CultureRedirectMiddlewareExtensions.cs | 24 ++ .../Validation/FluentValidationOptions.cs | 1 - .../DirectoriesController.cs | 9 +- .../FileSystemManagement/DrivesController.cs | 4 +- .../FileSystemController.cs | 4 +- .../FileSystemManagement/FilesController.cs | 6 +- .../FileSystemManagement/PathController.cs | 15 +- .../Controllers/HomeController.cs | 29 +- .../Management/LibraryManagementController.cs | 23 +- .../BookLibrary/BooksController.cs | 2 +- .../Controllers/Tools/LanguageController.cs | 72 +++++ .../UsersManagement/AuthController.cs | 57 +++- .../Lumina.Presentation.Web.csproj | 294 ++++++++++++++++++ src/Lumina.Presentation.Web/Program.cs | 34 +- .../Filters/ApiExceptionFilter.de-DE.resx | 3 + .../Filters/ApiExceptionFilter.en-US.resx | 3 + .../Filters/ApiExceptionFilter.es-ES.resx | 3 + .../Filters/ApiExceptionFilter.fr-FR.resx | 3 + .../Filters/ApiExceptionFilter.it-IT.resx | 3 + .../Filters/ApiExceptionFilter.ja-JP.resx | 3 + .../Common/Filters/ApiExceptionFilter.resx | 3 + .../Filters/ApiExceptionFilter.ro-RO.resx | 3 + .../Filters/ApiExceptionFilter.ru-RU.resx | 3 + .../Filters/ApiExceptionFilter.zh-CN.resx | 3 + .../Views/Library/Management/Item.ro-RO.resx | 2 +- .../Views/Shared/_NavMenu.de-DE.resx | 3 + .../Views/Shared/_NavMenu.en-US.resx | 3 + .../Views/Shared/_NavMenu.es-ES.resx | 3 + .../Views/Shared/_NavMenu.fr-FR.resx | 3 + .../Views/Shared/_NavMenu.it-IT.resx | 3 + .../Views/Shared/_NavMenu.ja-JP.resx | 3 + .../Resources/Views/Shared/_NavMenu.resx | 3 + .../Views/Shared/_NavMenu.ro-RO.resx | 3 + .../Views/Shared/_NavMenu.ru-RU.resx | 3 + .../Views/Shared/_NavMenu.zh-CN.resx | 3 + .../Views/Auth/ChangePassword.cshtml | 28 +- .../Views/Auth/Login.cshtml | 20 +- .../Views/Auth/RecoverPassword.cshtml | 20 +- .../Views/Auth/Register.cshtml | 36 ++- .../Views/Library/Management/Item.cshtml | 117 +++---- .../FileSystemBrowser/Default.cshtml | 51 +-- .../Views/Shared/_Layout.cshtml | 9 +- .../Views/Shared/_Layout.cshtml.css | 1 + .../Views/Shared/_NavMenu.cshtml | 152 +++++---- .../Shared/_ValidationScriptsPartial.cshtml | 2 - .../wwwroot/js/site.js | 9 +- .../Thumbnails/GetThumbnailEndpointTests.cs | 2 +- .../Authentication/AuthLoginTests.cs | 2 +- .../AuthRecoverPasswordTests.cs | 2 +- .../Authentication/AuthRegisterTests.cs | 2 +- .../GetThumbnailQueryValidatorTests.cs | 4 +- .../FluentValidationOptionsTests.cs | 3 +- 65 files changed, 1111 insertions(+), 319 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/MiddlewareFilters/LocalizationPipeline.cs create mode 100644 src/Lumina.Presentation.Web/Common/Middlewares/CultureRedirectMiddleware.cs create mode 100644 src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareExtensions.cs create mode 100644 src/Lumina.Presentation.Web/Controllers/Tools/LanguageController.cs create mode 100644 src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css delete mode 100644 src/Lumina.Presentation.Web/Views/Shared/_ValidationScriptsPartial.cshtml diff --git a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs index d62e68b5..9f9dcf13 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidator.cs @@ -16,6 +16,6 @@ public class GetThumbnailQueryValidator : AbstractValidator public GetThumbnailQueryValidator() { RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - RuleFor(x => x.Quality).InclusiveBetween(0, 100).WithMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description); + RuleFor(x => x.Quality).InclusiveBetween(0, 100).WithMessage(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred.Description); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs index 8d9ee829..ba144198 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Thumbnails.cs @@ -12,6 +12,6 @@ public static partial class Errors public static class Thumbnails { public static Error NoThumbnail => Error.Failure(description: nameof(NoThumbnail)); - public static Error ImageQaulityMustBeBetweenZeroAndOneHundred => Error.Validation(description: nameof(ImageQaulityMustBeBetweenZeroAndOneHundred)); + public static Error ImageQualityMustBeBetweenZeroAndOneHundred => Error.Validation(description: nameof(ImageQualityMustBeBetweenZeroAndOneHundred)); } } diff --git a/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs b/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs index 510e1826..e6c0d696 100644 --- a/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs +++ b/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs @@ -52,7 +52,6 @@ public class FluentValidationOptions : IValidateOptions wher return ValidateOptionsResult.Success; // if the validation fails, collect the error messages - // TODO: add translation support for the error messages string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") .ToArray(); diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 5cbec4bd..36a866db 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -7,8 +7,8 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; -using Serilog; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -49,13 +49,13 @@ public static class PresentationApiLayerServices rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests; rateLimiterOptions.OnRejected = async (onRejectedContext, cancellationToken) => { - ILogger logger = onRejectedContext.HttpContext.RequestServices.GetRequiredService(); + ILogger logger = onRejectedContext.HttpContext.RequestServices.GetRequiredService>(); string clientIp = onRejectedContext.HttpContext.Request.Headers["X-Forwarded-For"] .FirstOrDefault()?.Split(',')[0].Trim() ?? onRejectedContext.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; - Log.Warning( + logger.LogWarning( "Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}", clientIp, onRejectedContext.HttpContext.Request.Path, @@ -76,9 +76,9 @@ public static class PresentationApiLayerServices var problem = new { type = "https://tools.ietf.org/html/rfc7231#section-6.5.29", - title = "TooManyRequests", // TODO: implement translation? + title = "TooManyRequests", status = StatusCodes.Status429TooManyRequests, - detail = "Too many attempts. Please try again later.", + detail = "TooManyRequests", retryAfter = "900" }; diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index fbec176f..eeb1a630 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -12,6 +12,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Logging; using Scalar.AspNetCore; using Serilog; using System; @@ -84,8 +85,8 @@ public class Program } catch (Exception ex) { - ILogger logger = services.GetRequiredService(); - logger.Fatal(ex, "Failed to run database migrations"); + Microsoft.Extensions.Logging.ILogger logger = services.GetRequiredService(); + logger.LogCritical(ex, "Failed to run database migrations"); } } diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs index 8e15a798..ccf3aec8 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs @@ -37,7 +37,7 @@ public class InitializationHandler : AuthorizationHandlerThe initialization requirement to be evaluated. protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement) { - InitializationModel result = await _apiHttpClient.GetAsync("initialization/"); + InitializationModel result = await _apiHttpClient.GetAsync("initialization/").ConfigureAwait(false); HttpContext? httpContext = context.Resource as HttpContext; if (result.IsInitialized) { diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index f21ac11c..f5813334 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -4,6 +4,7 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Filters; +using Lumina.Presentation.Web.Common.MiddlewareFilters; using Lumina.Presentation.Web.Common.Security; using Lumina.Presentation.Web.Common.Services; using Microsoft.AspNetCore.Authentication.Cookies; @@ -11,6 +12,10 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Localization; +using Microsoft.AspNetCore.Localization.Routing; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.DependencyInjection; using Polly; using Polly.CircuitBreaker; @@ -18,6 +23,7 @@ using Polly.Retry; using Polly.Wrap; using System; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Net; using System.Net.Http; using System.Text.Json.Serialization; @@ -39,49 +45,117 @@ public static class PresentationWebLayerServices /// The updated . public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) { - services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter))) - .AddJsonOptions(options => + services.AddControllersWithViews(mvcOptions => + { + mvcOptions.Filters.Add(); + mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter + }) + .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) + .AddDataAnnotationsLocalization() + .AddJsonOptions(jsonOptions => + { + jsonOptions.JsonSerializerOptions.MaxDepth = 256; + jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); + // configure URL-based localization + services.AddLocalization(localizationOptions => + { + localizationOptions.ResourcesPath = "Resources"; + }); + + services.Configure(requestLocalizationOptions => + { + CultureInfo[] supportedCultures = + [ + new CultureInfo("de-DE"), + new CultureInfo("en-US"), + new CultureInfo("es-ES"), + new CultureInfo("fr-FR"), + new CultureInfo("it-IT"), + new CultureInfo("ja-JP"), + new CultureInfo("ro-RO"), + new CultureInfo("ru-RU"), + new CultureInfo("zh-CN"), + ]; + requestLocalizationOptions.DefaultRequestCulture = new RequestCulture("en-US"); + requestLocalizationOptions.SupportedCultures = supportedCultures; + requestLocalizationOptions.SupportedUICultures = supportedCultures; + + // configure route-based culture provider + RouteDataRequestCultureProvider routeDataRequestCultureProvider = new() { - options.JsonSerializerOptions.MaxDepth = 256; - options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures - options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); - }); + RouteDataStringKey = "culture", + UIRouteDataStringKey = "culture", + Options = requestLocalizationOptions + }; + // make the route culture provider the first one to be evaluated + requestLocalizationOptions.RequestCultureProviders = + [ + routeDataRequestCultureProvider, // keep route-based culture handling + new CookieRequestCultureProvider(), // but also add cookie option, so the application "remembers" the last used language the next time it's opened + new AcceptLanguageHeaderRequestCultureProvider() + ]; + }); // configure cookie-based authentication services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) - .AddCookie(options => + .AddCookie(cookieAuthenticationOptions => { // basic path configuration - options.LoginPath = "/auth/login"; - options.LogoutPath = "/auth/logout"; - options.AccessDeniedPath = "/auth/access-denied"; + cookieAuthenticationOptions.LoginPath = "/auth/login"; + cookieAuthenticationOptions.LogoutPath = "/auth/logout"; + cookieAuthenticationOptions.AccessDeniedPath = "/auth/access-denied"; - // Cookie configuration - options.Cookie = new CookieBuilder + // cookie configuration + cookieAuthenticationOptions.Cookie = new CookieBuilder { Name = ".Lumina.Auth", // unique name to avoid conflicts HttpOnly = true, // prevent JavaScript access - SameSite = SameSiteMode.Lax, // balance between security and functionality + SameSite = SameSiteMode.Strict, SecurePolicy = CookieSecurePolicy.Always, // require HTTPS Path = "/", // make cookie available for all paths IsEssential = true // mark as essential for GDPR }; // security settings - options.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user? - options.SlidingExpiration = true; + cookieAuthenticationOptions.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user? + cookieAuthenticationOptions.SlidingExpiration = true; // handle validation to support various deployment scenarios - options.Events = new CookieAuthenticationEvents + cookieAuthenticationOptions.Events = new CookieAuthenticationEvents { // handle redirects to work with different base paths - OnRedirectToLogin = context => + OnRedirectToLogin = redirectContext => { - // preserve any base path or subdirectory - string redirectPath = context.RedirectUri; - if (context.Request.PathBase.HasValue) - redirectPath = context.Request.PathBase + options.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(context.Request.PathBase + context.Request.Path); - context.Response.Redirect(redirectPath); + 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); + 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); + 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); return Task.CompletedTask; } }; @@ -89,22 +163,22 @@ public static class PresentationWebLayerServices // add an authorization policy that ensures application is initialized with super admin account before allowing access services.AddAuthorizationBuilder() - .AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement())); + .AddPolicy("RequireInitialization", authorizationPolicyBuilder => authorizationPolicyBuilder.Requirements.Add(new InitializationRequirement())); // add forwarded headers middleware to handle reverse proxy scenarios - services.Configure(options => + services.Configure(forwardedHeadersOptions => { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; - options.KnownNetworks.Clear(); - options.KnownProxies.Clear(); + forwardedHeadersOptions.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; + forwardedHeadersOptions.KnownNetworks.Clear(); + forwardedHeadersOptions.KnownProxies.Clear(); }); // configure session management to maintain user-specific data across requests - services.AddSession(options => + services.AddSession(sessionOptions => { - options.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity - options.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security - options.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance + sessionOptions.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity + sessionOptions.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security + sessionOptions.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance }); // scan the current assembly for validators and register them to the DI container @@ -113,16 +187,16 @@ public static class PresentationWebLayerServices // handle transient errors like network timeouts or intermittent failures AsyncRetryPolicy retryPolicy = Policy .Handle() - .OrInner(ex => - ex.HttpStatusCode != HttpStatusCode.BadRequest && - ex.HttpStatusCode != HttpStatusCode.Forbidden) + .OrInner(apiException => + apiException.HttpStatusCode != HttpStatusCode.BadRequest && // do not retry Bad Request and Forbidden responses, it's pointless + apiException.HttpStatusCode != HttpStatusCode.Forbidden) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); // use a circuit breaker to prevent repeatedly calling a failing service AsyncCircuitBreakerPolicy circuitBreakerPolicy = Policy .Handle() - .OrInner(ex => ex.HttpStatusCode == HttpStatusCode.InternalServerError) + .OrInner(apiException => apiException.HttpStatusCode == HttpStatusCode.InternalServerError) .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30)); AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); diff --git a/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs index 307d933d..cc07de03 100644 --- a/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs +++ b/src/Lumina.Presentation.Web/Common/Filters/ApiExceptionFilter.cs @@ -6,8 +6,9 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Collections.Generic; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using System.Linq; using System.Net; using System.Text; using System.Text.Json; @@ -21,6 +22,20 @@ namespace Lumina.Presentation.Web.Common.Filters; /// public class ApiExceptionFilter : IExceptionFilter { + private readonly IStringLocalizer _stringLocalizer; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class with the specified localizer and logger. + /// + /// Injected service used for providing localized strings. + /// Injected service used for logging. + public ApiExceptionFilter(IStringLocalizer stringLocalizer, ILogger logger) + { + _stringLocalizer = stringLocalizer; + _logger = logger; + } + /// /// Called after an action has thrown an Exception. /// @@ -30,11 +45,20 @@ public class ApiExceptionFilter : IExceptionFilter // check if the exception is an ApiException if (context.Exception is ApiException apiException) { + // Log all available details for debugging/monitoring + _logger.LogError( + apiException, + "API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}", + apiException.HttpStatusCode, + apiException.ProblemDetails?.Title, + apiException.ProblemDetails?.Detail, + apiException.ProblemDetails?.Extensions); // 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) { SignOutSynchronously(context.HttpContext); string currentUrl = context.HttpContext.Request.GetDisplayUrl(); + _logger.LogInformation("Redirecting unauthorized user to {Url}", currentUrl); context.HttpContext.Response.Redirect(currentUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too } else @@ -42,33 +66,29 @@ public class ApiExceptionFilter : IExceptionFilter StringBuilder errorMessage = new(); if (apiException.ProblemDetails is not null) { - errorMessage.AppendLine($"HTTP {apiException.ProblemDetails.Status} {apiException.HttpStatusCode}
"); + // only show the meaningful error message to the user if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail)) - errorMessage.AppendLine($"{apiException.ProblemDetails.Detail}"); + errorMessage.AppendLine($"{_stringLocalizer[apiException.ProblemDetails.Detail]}
"); else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title)) - errorMessage.AppendLine($"{apiException.ProblemDetails.Title}"); - if (apiException.ProblemDetails.Extensions is not null && apiException.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj)) + errorMessage.AppendLine($"{_stringLocalizer[apiException.ProblemDetails.Title]}
"); + + if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true) { - if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object) + if (errorsObj.ValueKind == JsonValueKind.Object) { - errorMessage.AppendLine("Validation Errors:"); - foreach (JsonProperty error in jsonElement.EnumerateObject()) + foreach (JsonProperty error in errorsObj.EnumerateObject()) { - string fieldName = error.Name; + _logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString())); if (error.Value.ValueKind == JsonValueKind.Array) foreach (JsonElement errorValue in error.Value.EnumerateArray()) - errorMessage.AppendLine($"- {fieldName}: {errorValue}
"); + errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}
"); } } } - if (apiException.ProblemDetails.Extensions is not null) - foreach (KeyValuePair extension in apiException.ProblemDetails.Extensions) - if (extension.Key != "errors") - errorMessage.AppendLine($"{extension.Key}: {extension.Value}
"); } else { - errorMessage.AppendLine($"HTTP {apiException.HttpStatusCode}
"); + _logger.LogError(apiException, "Generic API error occurred"); errorMessage.AppendLine($"{apiException.Message}
"); } // return a JSON result with the error details @@ -81,6 +101,7 @@ public class ApiExceptionFilter : IExceptionFilter } else { + _logger.LogError(context.Exception, "Unexpected exception occurred: {Message}", context.Exception.Message); // return a JSON result with the error details context.Result = new JsonResult(new { diff --git a/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs b/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs index f7543734..8c569054 100644 --- a/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs +++ b/src/Lumina.Presentation.Web/Common/Filters/InitializationCheckAttribute.cs @@ -20,7 +20,7 @@ public class InitializationCheckAttribute : ActionFilterAttribute public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService(); - await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization"); - await next(); + await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization").ConfigureAwait(false); + await next().ConfigureAwait(false); } } diff --git a/src/Lumina.Presentation.Web/Common/MiddlewareFilters/LocalizationPipeline.cs b/src/Lumina.Presentation.Web/Common/MiddlewareFilters/LocalizationPipeline.cs new file mode 100644 index 00000000..a10a2dfb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/MiddlewareFilters/LocalizationPipeline.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Localization; +using Microsoft.Extensions.Options; +#endregion + +namespace Lumina.Presentation.Web.Common.MiddlewareFilters; + +/// +/// Defines a pipeline for configuring middleware to handle localization. +/// +/// +/// To use a MiddlewareFilter, you first need to create a pipeline. This acts as a mini startup configuration where you define an +/// to specify the middleware that should run as part of the pipeline. Multiple middleware can be configured in this way. +/// +public class LocalizationPipeline +{ + /// + /// Configures the middleware pipeline to include the for handling localization. + /// + /// The used to configure the middleware pipeline. + /// The instance for , containing localization settings to be applied. + public void Configure(IApplicationBuilder app, IOptions options) + { + // runs the RequestLocalizationMiddleware with the provided options + app.UseRequestLocalization(options.Value); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/CultureRedirectMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/CultureRedirectMiddleware.cs new file mode 100644 index 00000000..d40cecd0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Middlewares/CultureRedirectMiddleware.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Localization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Middlewares; + +/// +/// Middleware to handle requests lacking a culture prefix in the URL, by redirecting to a default culture. +/// +public class CultureRedirectMiddleware +{ + private readonly RequestDelegate _next; + + /// + /// Initializes a new instance of the class. + /// + /// The next middleware in the request pipeline. + public CultureRedirectMiddleware(RequestDelegate next) + { + _next = next; + } + + /// + /// Handles incoming requests and redirects to the default culture if necessary. + /// + /// The for the current request. + public async Task InvokeAsync(HttpContext context) + { + // check if the request path starts with "/" and does not contain any culture + string? path = context.Request.Path.Value?.ToLowerInvariant(); + // redirect routes that would lead to the home page + if (path == "/" || path == "/home" || path == "/index") + { + // try to get the user's preferred culture from cookies + IRequestCultureFeature? feature = context.Features.Get(); + string? userCulture = feature?.RequestCulture.Culture.Name; + // if no specific culture is found, use "en-US" as fallback + string redirectCulture = userCulture ?? "en-US"; + // redirect the user to their preferred culture route + context.Response.Redirect($"/{redirectCulture.ToLower()}/"); + return; + } + await _next(context).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs index f28f6696..7b5e47b0 100644 --- a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -1,5 +1,8 @@ namespace Lumina.Presentation.Web.Common.Services; +/// +/// Interface for the service for generating URLs from action and controller names, with URL localization. +/// public interface IUrlService { /// diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs index 2f8ed3b5..b90d989d 100644 --- a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -1,27 +1,34 @@ #region ========================================================================= USING ===================================================================================== using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; +using System; +using System.Linq; #endregion namespace Lumina.Presentation.Web.Common.Services; /// -/// Service for generating URLs from action and controller names. +/// Service for generating URLs from action and controller names, with URL localization. /// public class UrlService : IUrlService { private readonly LinkGenerator _linkGenerator; private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; /// /// Initializes a new instance of the class. /// /// The ASP.NET Core link generator service. /// Provides access to the current HTTP context. - public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor) + /// The used to retrieve information about the application's routes and actions. + public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) { _linkGenerator = linkGenerator; _httpContextAccessor = httpContextAccessor; + _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; } /// @@ -32,7 +39,25 @@ public class UrlService : IUrlService /// An absolute URL to the specified action. public string? GetAbsoluteUrl(string action, string controller) { - string? scheme = _httpContextAccessor.HttpContext?.Request.Scheme; - return _linkGenerator.GetUriByAction(_httpContextAccessor.HttpContext!, action: action, controller: controller, values: null, scheme: scheme); + HttpContext? httpContext = _httpContextAccessor.HttpContext; + if (httpContext is null) + return null; + string scheme = httpContext.Request.Scheme; + string culture = httpContext.Request.RouteValues["culture"]?.ToString() ?? "en-US"; + // find the controller's route template + ControllerActionDescriptor? controllerActionDescriptor = _actionDescriptorCollectionProvider + .ActionDescriptors.Items + .OfType() + .FirstOrDefault(ad => + ad.ControllerName.Equals(controller, StringComparison.OrdinalIgnoreCase) && + ad.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase)); + if (controllerActionDescriptor is null) + return null; + // check if the route template contains {culture} + string? routeTemplate = controllerActionDescriptor.AttributeRouteInfo?.Template; + bool needsCulture = routeTemplate?.Contains("{culture}") == true; + // 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: values, scheme: scheme); } } diff --git a/src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareExtensions.cs b/src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareExtensions.cs new file mode 100644 index 00000000..107a1d45 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareExtensions.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Middlewares; +using Microsoft.AspNetCore.Builder; +#endregion + +namespace Lumina.Presentation.Web.Common.Utilities; + +/// +/// Extension methods for making it easier for to be added the middleware. +/// +// Extension method to make it easier to add the middleware +public static class CultureRedirectMiddlewareExtensions +{ + /// + /// Adds the to the application's request pipeline. + /// Redirects requests to include or validate the culture in the URL. + /// + /// The used to configure the application's request pipeline. + /// The for further configuration. + public static IApplicationBuilder UseCultureRedirect(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs b/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs index 5d6cbe1d..65dd9627 100644 --- a/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs +++ b/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs @@ -52,7 +52,6 @@ public class FluentValidationOptions : IValidateOptions wher return ValidateOptionsResult.Success; // if the validation fails, collect the error messages - // TODO: add translation support for the error messages string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") .ToArray(); diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs index d7109c39..dd46cd03 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs @@ -15,7 +15,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// Controller for managing file system directories. /// [Authorize] -[Route("[controller]")] +[Route("directories")] public class DirectoriesController : Controller { private readonly IApiHttpClient _apiHttpClient; @@ -39,7 +39,7 @@ public class DirectoriesController : Controller public async Task GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { IEnumerable response = await _apiHttpClient.GetAsync( - $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken); + $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } @@ -53,7 +53,7 @@ public class DirectoriesController : Controller public async Task GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { IEnumerable response = await _apiHttpClient.GetAsync( - $"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken); + $"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } @@ -66,7 +66,8 @@ public class DirectoriesController : Controller [HttpGet("get-directory-tree")] public async Task GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { - FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken); + 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 e45ceca2..a247b5c3 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs @@ -13,7 +13,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// Controller for managing file system drives. /// [Authorize] -[Route("[controller]")] +[Route("drives")] public class DrivesController : Controller { private readonly IApiHttpClient _apiHttpClient; @@ -34,7 +34,7 @@ public class DrivesController : Controller [HttpGet("get-drives")] public async Task GetDrives(CancellationToken cancellationToken) { - FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"drives/get-drives", cancellationToken); + FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"drives/get-drives", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = new { drives = response } }); } } diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs index 61f606a5..17e03c65 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs @@ -13,7 +13,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// Controller for managing file systems. /// [Authorize] -[Route("/file-system")] +[Route("file-system")] public class FileSystemController : Controller { private readonly IApiHttpClient _apiHttpClient; @@ -34,7 +34,7 @@ public class FileSystemController : Controller [HttpGet("get-type")] public async Task GetType(CancellationToken cancellationToken) { - FileSystemTypeModel response = await _apiHttpClient.GetAsync($"file-system/get-type", cancellationToken); + FileSystemTypeModel response = await _apiHttpClient.GetAsync($"file-system/get-type", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = new { platformType = response.PlatformType.ToString() } }); } } diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs index e1c82663..1fc3ded5 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs @@ -15,7 +15,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// Controller for managing file system files. /// [Authorize] -[Route("[controller]")] +[Route("files")] public class FilesController : Controller { private readonly IApiHttpClient _apiHttpClient; @@ -39,7 +39,7 @@ public class FilesController : Controller public async Task GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { IEnumerable response = await _apiHttpClient.GetAsync( - $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken); + $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } @@ -53,7 +53,7 @@ public class FilesController : Controller public async Task GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { IEnumerable response = await _apiHttpClient.GetAsync( - $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken); + $"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 7cf9509d..650a9a24 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs @@ -14,7 +14,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; /// Controller for managing file system paths. /// [Authorize] -[Route("[controller]")] +[Route("path")] public class PathController : Controller { private readonly IApiHttpClient _apiHttpClient; @@ -36,7 +36,7 @@ public class PathController : Controller [HttpGet("get-path-root")] public async Task GetPathRoot([FromQuery] string path, CancellationToken cancellationToken) { - PathSegmentModel response = await _apiHttpClient.GetAsync($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken); + 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 } }); } @@ -47,7 +47,7 @@ public class PathController : Controller [HttpGet("get-path-separator")] public async Task GetPathSeparator(CancellationToken cancellationToken) { - PathSeparatorModel response = await _apiHttpClient.GetAsync($"path/get-path-separator", cancellationToken); + PathSeparatorModel response = await _apiHttpClient.GetAsync($"path/get-path-separator", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = new { pathSeparator = response.Separator } }); } @@ -59,7 +59,7 @@ public class PathController : Controller [HttpGet("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); + PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = new { pathSegments = response } }); } @@ -71,7 +71,7 @@ public class PathController : Controller [HttpGet("split")] public async Task SplitPath([FromQuery] string path, CancellationToken cancellationToken) { - PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken); + PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = new { pathSegments = response } }); } @@ -83,7 +83,7 @@ public class PathController : Controller [HttpGet("validate")] public async Task ValidatePath([FromQuery] string path, CancellationToken cancellationToken) { - PathValidModel response = await _apiHttpClient.GetAsync($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken); + PathValidModel response = await _apiHttpClient.GetAsync($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = new { isValid = response.IsValid } }); } @@ -96,7 +96,8 @@ public class PathController : Controller [HttpGet("check-path-exists")] public async Task CheckPathExists([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) { - PathExistsModel response = await _apiHttpClient.GetAsync($"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken); + PathExistsModel response = await _apiHttpClient.GetAsync( + $"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = new { exists = response.Exists } }); } } diff --git a/src/Lumina.Presentation.Web/Controllers/HomeController.cs b/src/Lumina.Presentation.Web/Controllers/HomeController.cs index 939bebe2..1440fc03 100644 --- a/src/Lumina.Presentation.Web/Controllers/HomeController.cs +++ b/src/Lumina.Presentation.Web/Controllers/HomeController.cs @@ -1,32 +1,55 @@ +#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Serilog; +using Microsoft.Extensions.Logging; using System.Diagnostics; +#endregion namespace Lumina.Presentation.Web.Controllers; +/// +/// Controller for home page. +/// [Authorize] +[Route("")] // randle root path - this is needed because app.UseCultureRedirect will redirect to the correct route +[Route("{culture}")] // culture-specific routes public class HomeController : Controller { - private readonly ILogger _logger; + private readonly ILogger _logger; - public HomeController(ILogger logger) + /// + /// Initializes a new instance of the class. + /// + /// Injected service for logging. + public HomeController(ILogger logger) { _logger = logger; } + /// + /// Displays the view for the home page. + /// + [HttpGet("")] public IActionResult Index() { return View(); } + /// + /// Displays the view for privacy. + /// + [HttpGet("privacy")] public IActionResult Privacy() { return View(); } + /// + /// Displays the view for errors. + /// [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] + [HttpGet("error")] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs index aae4a99e..b73fd0a5 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -1,12 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Enums.Library; using Lumina.Presentation.Web.Common.Models.Libraries; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Formatters; using System; -using System.Security.Claims; using System.Threading; using System.Threading.Tasks; #endregion @@ -14,28 +11,40 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Controllers.Library.Management; [Authorize] -[Route("/library/manage/")] +[Route("{culture}/library/manage")] public class LibraryManagementController : Controller { private readonly IApiHttpClient _apiHttpClient; + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. public LibraryManagementController(IApiHttpClient apiHttpClient) { _apiHttpClient = apiHttpClient; } + /// + /// Displays the view for displaying the list of media libraries. + /// [HttpGet("")] public IActionResult Index() { return View("/Views/Library/Management/Index.cshtml"); } + /// + /// Displays the view for adding or editing a media library. + /// + /// The optional id of the media library to edit. + /// Cancellation token that can be used to stop the execution. [HttpGet("item/{id?}")] public async Task EditLibrary(Guid? id = null, CancellationToken cancellationToken = default) { LibraryModel libraryModel = new(); if (id is not null) - libraryModel = await _apiHttpClient.GetAsync($"libraries/{id}", cancellationToken); + libraryModel = await _apiHttpClient.GetAsync($"libraries/{id}", cancellationToken).ConfigureAwait(false); return View("/Views/Library/Management/Item.cshtml", libraryModel); } @@ -50,8 +59,8 @@ public class LibraryManagementController : Controller { // call different API endpoints based on whether this is a new library or an existing one LibraryModel response = data.Id.HasValue - ? await _apiHttpClient.PutAsync($"libraries/{data.Id}", data, cancellationToken) - : await _apiHttpClient.PostAsync("libraries", data, cancellationToken); + ? await _apiHttpClient.PutAsync($"libraries/{data.Id}", data, cancellationToken).ConfigureAwait(false) + : await _apiHttpClient.PostAsync("libraries", data, cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } } diff --git a/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs b/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs index bdecbc89..aab488d4 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs @@ -5,7 +5,7 @@ using System; namespace Lumina.Presentation.Web.Controllers.Library.WrittenContentLibrary.BookLibrary; [Authorize] -[Route("/library/written-content-library/books-library/books/")] +[Route("{culture}library/written-content-library/books-library/books")] public class BooksController : Controller { [HttpGet("")] diff --git a/src/Lumina.Presentation.Web/Controllers/Tools/LanguageController.cs b/src/Lumina.Presentation.Web/Controllers/Tools/LanguageController.cs new file mode 100644 index 00000000..6d40f560 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/Tools/LanguageController.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Localization; +using Microsoft.AspNetCore.Mvc; +using System; +#endregion + +namespace Lumina.Presentation.Web.Controllers.Tools; + +/// +/// Controller for language related operations. +/// +[Route("{culture}/tools/language")] +public class LanguageController : Controller +{ + private readonly IUrlService _urlService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + public LanguageController(IUrlService urlService) + { + _urlService = urlService; + } + + /// + /// Sets the culture used in the application. + /// + /// The new culture to set. + /// The URL to return to after setting the new culture. + [HttpGet("set-language")] + public IActionResult SetLanguage(string newCulture, string returnUrl) + { + // store culture preference in cookie + Response.Cookies.Append( + CookieRequestCultureProvider.DefaultCookieName, + CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(newCulture)), + new CookieOptions + { + Expires = DateTimeOffset.UtcNow.AddYears(1), + IsEssential = true, + SameSite = SameSiteMode.Lax, + Path = "/" // ensure cookie works across all paths + } + ); + // ensure returnUrl includes the correct culture + if (string.IsNullOrEmpty(returnUrl)) + returnUrl = _urlService.GetAbsoluteUrl("Index", "Home")!; // default fallback URL + // handle culture replacement in return URL + string? currentCulture = HttpContext.Request.RouteValues["culture"]?.ToString() ?? "en-us"; + if (currentCulture != null) + { + // ensure we handle both with and without trailing slashes + string culturePath = $"/{currentCulture.ToLower()}/"; + string newCulturePath = $"/{newCulture.ToLower()}/"; + + // Handle base path if present + if (!string.IsNullOrEmpty(Request.PathBase)) + returnUrl = returnUrl.Replace(Request.PathBase.Value!, "", StringComparison.OrdinalIgnoreCase); + // replace culture in URL + returnUrl = returnUrl.Replace(culturePath, newCulturePath, StringComparison.OrdinalIgnoreCase); + + // re-apply base path if present + if (!string.IsNullOrEmpty(Request.PathBase)) + returnUrl = Request.PathBase.Value + returnUrl; + } + // redirect to the original page + return LocalRedirect(returnUrl); + } +} diff --git a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs index f4cdd624..99e6c5f7 100644 --- a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs +++ b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs @@ -5,11 +5,13 @@ using Lumina.Presentation.Web.Common.Filters; using Lumina.Presentation.Web.Common.Http; using Lumina.Presentation.Web.Common.Models.UsersManagement; using Lumina.Presentation.Web.Common.Security; +using Lumina.Presentation.Web.Common.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; using System.Security.Claims; @@ -24,21 +26,24 @@ namespace Lumina.Presentation.Web.Controllers.UsersManagement; /// Controller for authentication related operations. /// [Authorize] -[Route("/auth/")] +[Route("{culture}/auth")] public class AuthController : Controller { private readonly IApiHttpClient _apiHttpClient; private readonly ICryptographyService _cryptographyService; + private readonly IUrlService _urlService; /// /// Initializes a new instance of the class. /// /// Injected service for interactions with the API. /// Injected service for cryptographic functionality. - public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService) + /// Injected service for generating URLs from action and controller names, with localization. + public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService, IUrlService urlService) { _apiHttpClient = apiHttpClient; _cryptographyService = cryptographyService; + _urlService = urlService; } /// @@ -67,14 +72,14 @@ public class AuthController : Controller ViewData["ReturnUrl"] = returnUrl; // if the user is already logged in, redirect them to the home page if (User?.Identity?.IsAuthenticated == true) - return RedirectToAction("Index", "Home"); + return Redirect(_urlService.GetAbsoluteUrl("Index", "Home")!); // check if the application is initialized (does contain at least the super user account); if it's not, redirect to registration view string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); if (isPendingSuperAdminSetup == "true") // TODO: should be: // return View("~/Views/Auth/Register", new RegisterRequestDto()); // but doesn't work because of an ASP.NET bug: https://github.com/dotnet/AspNetCore.Docs/issues/25157 - return RedirectToAction("Register", "Auth"); + return Redirect(_urlService.GetAbsoluteUrl("Register", "Auth")!); return View(new LoginRequestModel()); } @@ -88,7 +93,7 @@ public class AuthController : Controller { // if the user is already logged in, redirect them to the home page if (User?.Identity?.IsAuthenticated == true) - return RedirectToAction("Index", "Home"); + return Redirect(_urlService.GetAbsoluteUrl("Index", "Home")!); return View(); } @@ -123,7 +128,7 @@ public class AuthController : Controller // 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"; // attempt API registration - RegisterResponseModel response = await _apiHttpClient.PostAsync(endpoint, data, cancellationToken); + RegisterResponseModel response = await _apiHttpClient.PostAsync(endpoint, data, cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } @@ -140,7 +145,7 @@ public class AuthController : Controller try { // attempt API registration - LoginResponseModel response = await _apiHttpClient.PostAsync("auth/login", data, cancellationToken); + LoginResponseModel response = await _apiHttpClient.PostAsync("auth/login", data, cancellationToken).ConfigureAwait(false); // store the received token in a secure cookie Response.Cookies.Delete("Token"); Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions @@ -148,7 +153,9 @@ public class AuthController : Controller Expires = DateTimeOffset.UtcNow.AddMonths(1), Path = "/", HttpOnly = true, - Secure = true + Secure = true, + IsEssential = true, + SameSite = SameSiteMode.Strict }); // tell asp.net we are logged in List claims = @@ -158,9 +165,29 @@ public class AuthController : Controller new Claim("Token", response.Token!), ]; ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)).ConfigureAwait(false); + // get current culture from route data or use default if not set + string currentCulture = HttpContext.Request.RouteValues["culture"]?.ToString() ?? "en-US"; + // handle ReturnUrl and ensure it includes the correct culture + string redirectUrl; + if (!string.IsNullOrEmpty(data.ReturnUrl) && Url.IsLocalUrl(data.ReturnUrl)) // ensure that return URL contains the correct culture + redirectUrl = data.ReturnUrl.StartsWith($"/{currentCulture}/") ? data.ReturnUrl : $"/{currentCulture}{data.ReturnUrl}"; + else + { + // if no ReturnUrl is provided or it's invalid, use a default URL with respect to base paths + redirectUrl = Url.Content("~/"); + + // handle reverse proxy scenarios by respecting any base path or forwarded headers + if (HttpContext.Request.Headers.TryGetValue("X-Forwarded-Prefix", out StringValues pathBase)) + redirectUrl = pathBase + redirectUrl; + + // ensure that default redirect contains the correct culture + if (!redirectUrl.StartsWith($"/{currentCulture}/")) + redirectUrl = $"/{currentCulture}{redirectUrl}"; + } + // return success status and redirect URL - return Json(new { success = true, data = string.IsNullOrEmpty(data.ReturnUrl) || !Url.IsLocalUrl(data.ReturnUrl) ? Url.Content("~/") : Url.Content(data.ReturnUrl) }); + return Json(new { success = true, data = redirectUrl }); } catch (ApiException ex) { @@ -186,10 +213,10 @@ public class AuthController : Controller { // if the user is not logged in, redirect them to the home page if (User?.Identity?.IsAuthenticated == false) - return RedirectToAction("Index", "Home"); + return Redirect(_urlService.GetAbsoluteUrl("Index", "Home")!); Response.Cookies.Delete("Token"); - await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); - return RedirectToAction("Login", "Auth"); + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false); + return Redirect(_urlService.GetAbsoluteUrl("Login", "Auth")!); } /// @@ -202,7 +229,7 @@ public class AuthController : Controller [HttpPost("recover-password")] public async Task RecoverPassword([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken) { - RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync("auth/recover-password", data, cancellationToken); + RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync("auth/recover-password", data, cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } @@ -216,7 +243,7 @@ public class AuthController : Controller public async Task ChangePassword([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); + ChangePasswordResponseModel response = await _apiHttpClient.PostAsync("auth/change-password", data, cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } } diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index 86518506..6319c432 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -33,6 +33,300 @@ + + + True + True + ChangePassword.resx + + + True + True + Login.resx + + + True + True + RecoverPassword.resx + + + True + True + Register.resx + + + True + True + Item.resx + + + + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + ChangePassword.Designer.cs + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + Login.Designer.cs + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + RecoverPassword.Designer.cs + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + Register.Designer.cs + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + Item.Designer.cs + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + $(NoWarn);TS6385 diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index 109a3e6e..bd7b38e9 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -1,7 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Utilities; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing.Constraints; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Primitives; @@ -9,6 +12,7 @@ using Serilog; using System; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; using System.Threading.Tasks; #endregion @@ -58,6 +62,7 @@ public class Program WebApplication app = builder.Build(); + app.UseRequestLocalization(); app.UseSerilogRequestLogging(); // configure the HTTP request pipeline. @@ -69,7 +74,21 @@ public class Program } //app.UseHttpsRedirection(); - app.UseStaticFiles(); + app.UseStaticFiles(new StaticFileOptions + { + OnPrepareResponse = staticFileResponseContext => + { + // disable static file caching during development + if (app.Environment.IsDevelopment()) + { + staticFileResponseContext.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store"); + staticFileResponseContext.Context.Response.Headers.Append("Expires", "-1"); + } + }, + // prevent static files from being processed by routing + ServeUnknownFileTypes = true + }); + app.UseCultureRedirect(); // if the user attempts to go to a localized route without providing a culture, redirect to default culture app.UseRouting(); app.UseSession(); app.UseAuthentication(); @@ -84,8 +103,17 @@ public class Program return next(); }); - - app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); + // use localized routes for those that need localization + app.MapControllerRoute( + name: "localized", + pattern: "{culture}/{*catchall}", + constraints: new { culture = new RegexRouteConstraint("^[a-z]{2}(?:-[A-Z]{2})?$") } + ); + // for the rest, use default routing + app.MapControllerRoute( + name: "default", + pattern: "{*catchall}" + ); await app.RunAsync(); } diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.de-DE.resx index e2e342a6..ab237ad9 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.de-DE.resx @@ -465,6 +465,9 @@ Titel darf maximal 255 Zeichen lang sein! + + Zu viele Anfragen! Bitte versuchen Sie es in 15 Minuten erneut! + Der TOTP-Code darf nicht leer sein! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.en-US.resx index a4828e55..902c2169 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.en-US.resx @@ -465,6 +465,9 @@ Title must be maximum 255 characters long! + + Too many requests! Please try again later! + The TOTP code cannot be empty! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.es-ES.resx index ea97ab03..680804b4 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.es-ES.resx @@ -465,6 +465,9 @@ ¡El título debe tener máximo 255 caracteres! + + ¡Demasiadas solicitudes! ¡Por favor, inténtelo en 15 minutos! + ¡El código TOTP no puede estar vacío! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.fr-FR.resx index b9bf928f..f641dfc4 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.fr-FR.resx @@ -465,6 +465,9 @@ Le titre ne doit pas dépasser 255 caractères ! + + Trop de requêtes ! Veuillez réessayer dans 15 minutes ! + Le code TOTP ne peut pas être vide! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.it-IT.resx index 05fe2b16..78a68832 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.it-IT.resx @@ -465,6 +465,9 @@ Il titolo deve essere lungo al massimo 255 caratteri! + + Troppe richieste! Si prega di riprovare tra 15 minuti! + Il codice TOTP non può essere vuoto! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ja-JP.resx index 013c52e0..693ae9c1 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ja-JP.resx @@ -465,6 +465,9 @@ タイトルは最大255文字までです! + + リクエストが多すぎます!15分後にもう一度お試しください! + TOTPコードを入力してください! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.resx index a4828e55..1b976a8f 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.resx @@ -465,6 +465,9 @@ Title must be maximum 255 characters long! + + Too many requests! Please try again in 15 minutes! + The TOTP code cannot be empty! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ro-RO.resx index 52c33b79..5af38c93 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ro-RO.resx @@ -465,6 +465,9 @@ Titlul trebuie să aibă maximum 255 caractere! + + Prea multe cereri! Vă rugăm să încercați din nou în 15 minute! + Codul TOTP nu poate fi gol! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ru-RU.resx index 1451cdc1..6b95aa36 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ru-RU.resx @@ -465,6 +465,9 @@ Название не должно превышать 255 символов! + + Слишком много запросов! Пожалуйста, повторите попытку через 15 минут! + Код TOTP не может быть пустым! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.zh-CN.resx index eb1a20d6..ed73a9f9 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.zh-CN.resx @@ -465,6 +465,9 @@ 标题最多只能有255个字符! + + 请求过多!请15分钟后重试! + TOTP验证码不能为空! diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx index fb82fc8a..313885cb 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx @@ -124,7 +124,7 @@ Adaugă dosar - Adaugă Librărie Nouă + Adaugă Bibliotecă Nouă Anime diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx index c9a8262e..d647f419 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx @@ -144,6 +144,9 @@ Interviews + + Sprache + Mediathek diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx index 14718c81..8441ce56 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx @@ -144,6 +144,9 @@ Interviews + + Language + Library diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx index 23eb19df..b35c9c21 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx @@ -144,6 +144,9 @@ Entrevistas + + Lenguaje + Biblioteca diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx index e49ac3cb..de077b54 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx @@ -144,6 +144,9 @@ Entretiens + + Langue + Bibliothèque diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx index 87ca8c44..13760225 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx @@ -144,6 +144,9 @@ Interviste + + Lingua + Libreria diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx index 402c50bd..32d2dd5a 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx @@ -144,6 +144,9 @@ インタビュー + + 言語 + ライブラリ diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx index 14718c81..8441ce56 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx @@ -144,6 +144,9 @@ Interviews + + Language + Library diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx index 6c7ae989..eb72b03a 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx @@ -144,6 +144,9 @@ Interviuri + + Limbă + Bibliotecă diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx index c1fed371..561d97cf 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx @@ -144,6 +144,9 @@ Интервью + + Язык + Библиотека diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx index fae50129..c79fcc7b 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx @@ -144,6 +144,9 @@ 面试 + + 语言 + 媒体库 diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml index 3c71fa20..c5970e10 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml @@ -4,63 +4,65 @@ @using Lumina.Presentation.Web.Common.Models.UsersManagement @using Lumina.Presentation.Web.Common.Services - -@inject IUrlService _urlService +@using Microsoft.AspNetCore.Mvc.Localization @{ // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } +@inject IUrlService _urlService +@inject IViewLocalizer _localizer + @model ChangePasswordRequestModel -
+
-
+ @Html.AntiForgeryToken()
- + *:
- DescriptionCurrentPassword + @_localizer["DescriptionCurrentPassword"]
- + *:
- DescriptionNewPassword + @_localizer["DescriptionNewPassword"]
- + *:
- DescriptionNewPasswordConfirm + @_localizer["DescriptionNewPasswordConfirm"]
- +
- +
@section Scripts { @@ -103,7 +105,5 @@ divChangePasswordSubmit.classList.add('hidden'); } } - - } diff --git a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml index 90b9185c..548e4abf 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml @@ -4,26 +4,28 @@ @using Lumina.Presentation.Web.Common.Models.UsersManagement @using Lumina.Presentation.Web.Common.Services - -@inject IUrlService _urlService +@using Microsoft.AspNetCore.Mvc.Localization @{ // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } +@inject IUrlService _urlService +@inject IViewLocalizer _localizer + @model LoginRequestModel
-
+ @Html.AntiForgeryToken()
- : + :
@@ -32,27 +34,27 @@
- : + :
- - + +
- +
diff --git a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml index a5e3dee8..5b85c160 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml @@ -4,25 +4,27 @@ @using Lumina.Presentation.Web.Common.Models.UsersManagement @using Lumina.Presentation.Web.Common.Services - -@inject IUrlService _urlService +@using Microsoft.AspNetCore.Mvc.Localization @{ // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } +@inject IUrlService _urlService +@inject IViewLocalizer _localizer + @model RecoverPasswordRequestModel
-
+ @Html.AntiForgeryToken()
- + *:
@@ -32,7 +34,7 @@
- + *:
@@ -40,15 +42,15 @@
- - + +
- - + +
@section Scripts { diff --git a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml index bcd3a0ec..d8199620 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml @@ -4,6 +4,7 @@ @using Lumina.Presentation.Web.Common.Models.UsersManagement @using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization @{ string? registrationType = ViewData["RegistrationType"] as string; @@ -12,12 +13,13 @@ } @inject IUrlService _urlService +@inject IViewLocalizer _localizer @model RegisterRequestModel
-
+ @Html.AntiForgeryToken() @@ -25,41 +27,41 @@ @if (registrationType == "Admin") {
-

Admin account registration

+

@_localizer["AdminAccountRegistration"]

}
- + *:
- DescriptionUsername + @_localizer["DescriptionUsername"]
- + *:
- DescriptionPassword + @_localizer["DescriptionPassword"]
- + *:
- DescriptionPasswordConfirm + @_localizer["DescriptionPasswordConfirm"]
@@ -68,27 +70,27 @@
- Description2Fa + @_localizer["Description2Fa"]
- +
- +
- + - + @if (User?.Identity?.IsAuthenticated == false) { - + }
@@ -144,11 +146,11 @@ } document.querySelector('[name="Use2fa"]').addEventListener('change', function () { const isChecked = this.checked; - document.getElementById('#register-two-fa-attention').classList.replace( + document.getElementById('register-two-fa-attention').classList.replace( isChecked ? 'inline' : 'hidden', isChecked ? 'hidden' : 'inline' ); - document.getElementById('#hidden-use-two-fa').value = isChecked.toString(); + document.getElementById('hidden-use-two-fa').value = isChecked.toString(); }); if (btnLogin) { btnLogin.addEventListener('click', () => { diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml index e46089de..96acac72 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml @@ -4,6 +4,7 @@ @using Lumina.Presentation.Web.Common.Models.Libraries @using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization @{ var id = Context.Request.RouteValues["id"] as string; @@ -12,6 +13,7 @@ } @inject IUrlService _urlService +@inject IViewLocalizer _localizer @model LibraryModel @@ -19,30 +21,32 @@
-
+ @Html.AntiForgeryToken()
-

@(id is not null ? "Edit" : "Add New") Library

+

+ @(_localizer[id is not null ? "EditLibrary" : "AddNewLibrary"]) +

-

General Information

+

@_localizer["GeneralInformation"]

- + *:
- DescriptionTitle + @_localizer["DescriptionTitle"]
- + *:
@@ -50,60 +54,59 @@
- -
Written Content
-
Book
-
E Book
-
Book Series
-
Comic Book
-
Comic Series
-
Magazine
-
Manga
-
Graphic Novel
-
Academic Paper
-
Sheet Music
-
Screenplay
-
Video Content
-
Tv Show
-
Movie
-
Film Series
-
Film Franchise
-
Concert
-
Documentary
-
Tutorial
-
Personal
-
Anime
-
Youtube
-
Videoclip
-
Audio Content
-
Music
-
Audio Book
-
Live Performance
-
Interview
-
Cover
-
Remix
-
Soundeffect
-
Podcast
-
Radio Show
-
Visual Content
-
Photo Album
-
Miscellaneous Content
-
Other
+
@_localizer["WrittenContent"]
+
@_localizer["Book"]
+
@_localizer["EBook"]
+
@_localizer["BookSeries"]
+
@_localizer["ComicBook"]
+
@_localizer["ComicSeries"]
+
@_localizer["Magazine"]
+
@_localizer["Manga"]
+
@_localizer["GraphicNovel"]
+
@_localizer["AcademicPaper"]
+
@_localizer["SheetMusic"]
+
@_localizer["Screenplay"]
+
@_localizer["VideoContent"]
+
@_localizer["TvShow"]
+
@_localizer["Movie"]
+
@_localizer["FilmSeries"]
+
@_localizer["FilmFranchise"]
+
@_localizer["Concert"]
+
@_localizer["Documentary"]
+
@_localizer["Tutorial"]
+
@_localizer["Personal"]
+
@_localizer["Anime"]
+
@_localizer["Youtube"]
+
@_localizer["Videoclip"]
+
@_localizer["AudioContent"]
+
@_localizer["Music"]
+
@_localizer["AudioBook"]
+
@_localizer["LivePerformance"]
+
@_localizer["Interview"]
+
@_localizer["Cover"]
+
@_localizer["Remix"]
+
@_localizer["Soundeffect"]
+
@_localizer["Podcast"]
+
@_localizer["RadioShow"]
+
@_localizer["VisualContent"]
+
@_localizer["PhotoAlbum"]
+
@_localizer["MiscellaneousContent"]
+
@_localizer["Other"]
- DescriptionLibraryType + @_localizer["DescriptionLibraryType"]
- + *: - Add directory + @_localizer[
@@ -112,22 +115,22 @@ {
@Model.ContentLocations[i] - Remove + @_localizer[
}
- DescriptionDirectories + @_localizer["DescriptionDirectories"]
- +
- - - + + +
@section Scripts { @@ -154,7 +157,7 @@ Id: form.querySelector('[name="Id"]').value || null, UserId: form.querySelector('[name="UserId"]').value || null, Title: form.querySelector('[name="Title"]').value, - LibraryType: form.querySelector('.enlightenment-selected-text').textContent, + LibraryType: form.querySelector('#library-selected-item').getAttribute('data-value'), ContentLocations: Array.from(form.querySelectorAll('.form-table-row span')) .map(span => span.textContent) }; @@ -198,7 +201,7 @@ formTable.insertAdjacentHTML('beforeend', `
${path} - Remove + @_localizer[
`); } diff --git a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml index 2d519483..71523b8d 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -4,10 +4,13 @@ @using Lumina.Presentation.Web.Common.Enums.Notifications @using Lumina.Presentation.Web.Common.Exceptions @using Lumina.Presentation.Web.Common.Models.FileSystemManagement +@using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.AspNetCore.Components @using System.Text.Json @using System.Text +@inject IViewLocalizer _localizer +
@@ -18,7 +21,7 @@
@@ -492,7 +495,7 @@
- Name + @_localizer["Name"]
@@ -502,20 +505,20 @@
- +
- - + +
@*
- + - Cancel - Confirm *@ + @_localizer["Cancel"] + @_localizer["Confirm"] *@
diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml index 126f23c1..dbf3932d 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml @@ -1,3 +1,7 @@ +@using Microsoft.AspNetCore.Mvc.Localization + +@inject IViewLocalizer _localizer + @@ -27,7 +31,6 @@ @if (User?.Identity?.IsAuthenticated == true) - { }
diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css new file mode 100644 index 00000000..5f282702 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml index f469a3ed..9183fa2e 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -1,6 +1,8 @@ @using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization @inject IUrlService _urlService +@inject IViewLocalizer _localizer