Merge pull request #80 from BinaryAlley/feature/add-localization-to-presentation-web-project

Adds localization to Lumina.Presentation.Web project
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-11-20 21:14:12 +02:00
commit 5bfb2ca212
65 files changed
+1111 -319

No files matched your search

@@ -16,6 +16,6 @@ public class GetThumbnailQueryValidator : AbstractValidator<GetThumbnailQuery>
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);
}
}
@@ -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));
}
}
@@ -52,7 +52,6 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> 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();
@@ -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>();
ILogger<Program> logger = onRejectedContext.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
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"
};
+3 -2
View File
@@ -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<ILogger>();
logger.Fatal(ex, "Failed to run database migrations");
Microsoft.Extensions.Logging.ILogger logger = services.GetRequiredService<Microsoft.Extensions.Logging.ILogger>();
logger.LogCritical(ex, "Failed to run database migrations");
}
}
@@ -37,7 +37,7 @@ public class InitializationHandler : AuthorizationHandler<InitializationRequirem
/// <param name="requirement">The initialization requirement to be evaluated.</param>
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement)
{
InitializationModel result = await _apiHttpClient.GetAsync<InitializationModel>("initialization/");
InitializationModel result = await _apiHttpClient.GetAsync<InitializationModel>("initialization/").ConfigureAwait(false);
HttpContext? httpContext = context.Resource as HttpContext;
if (result.IsInitialized)
{
@@ -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
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services)
{
services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter)))
.AddJsonOptions(options =>
services.AddControllersWithViews(mvcOptions =>
{
mvcOptions.Filters.Add<ApiExceptionFilter>();
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>(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<ForwardedHeadersOptions>(options =>
services.Configure<ForwardedHeadersOptions>(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<HttpResponseMessage> retryPolicy = Policy<HttpResponseMessage>
.Handle<HttpRequestException>()
.OrInner<ApiException>(ex =>
ex.HttpStatusCode != HttpStatusCode.BadRequest &&
ex.HttpStatusCode != HttpStatusCode.Forbidden)
.OrInner<ApiException>(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<HttpResponseMessage> circuitBreakerPolicy = Policy<HttpResponseMessage>
.Handle<HttpRequestException>()
.OrInner<ApiException>(ex => ex.HttpStatusCode == HttpStatusCode.InternalServerError)
.OrInner<ApiException>(apiException => apiException.HttpStatusCode == HttpStatusCode.InternalServerError)
.CircuitBreakerAsync(3, TimeSpan.FromSeconds(30));
AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
@@ -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;
/// </summary>
public class ApiExceptionFilter : IExceptionFilter
{
private readonly IStringLocalizer<ApiExceptionFilter> _stringLocalizer;
private readonly ILogger<ApiExceptionFilter> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ApiExceptionFilter"/> class with the specified localizer and logger.
/// </summary>
/// <param name="stringLocalizer">Injected service used for providing localized strings.</param>
/// <param name="logger">Injected service used for logging.</param>
public ApiExceptionFilter(IStringLocalizer<ApiExceptionFilter> stringLocalizer, ILogger<ApiExceptionFilter> logger)
{
_stringLocalizer = stringLocalizer;
_logger = logger;
}
/// <summary>
/// Called after an action has thrown an Exception.
/// </summary>
@@ -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}<br>");
// only show the meaningful error message to the user
if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail))
errorMessage.AppendLine($"<b>{apiException.ProblemDetails.Detail}<b>");
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Detail]}</b><br>");
else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title))
errorMessage.AppendLine($"<b>{apiException.ProblemDetails.Title}<b>");
if (apiException.ProblemDetails.Extensions is not null && apiException.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj))
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Title]}</b><br>");
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}<br>");
errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}<br>");
}
}
}
if (apiException.ProblemDetails.Extensions is not null)
foreach (KeyValuePair<string, JsonElement> extension in apiException.ProblemDetails.Extensions)
if (extension.Key != "errors")
errorMessage.AppendLine($"{extension.Key}: {extension.Value}<br>");
}
else
{
errorMessage.AppendLine($"HTTP {apiException.HttpStatusCode}<br>");
_logger.LogError(apiException, "Generic API error occurred");
errorMessage.AppendLine($"{apiException.Message}<br>");
}
// 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
{
@@ -20,7 +20,7 @@ public class InitializationCheckAttribute : ActionFilterAttribute
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService<IAuthorizationService>();
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);
}
}
@@ -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;
/// <summary>
/// Defines a pipeline for configuring middleware to handle localization.
/// </summary>
/// <remarks>
/// To use a MiddlewareFilter, you first need to create a pipeline. This acts as a mini startup configuration where you define an <see cref="IApplicationBuilder"/>
/// to specify the middleware that should run as part of the pipeline. Multiple middleware can be configured in this way.
/// </remarks>
public class LocalizationPipeline
{
/// <summary>
/// Configures the middleware pipeline to include the <see cref="RequestLocalizationMiddleware"/> for handling localization.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> used to configure the middleware pipeline.</param>
/// <param name="options">The <see cref="IOptions{TOptions}"/> instance for <see cref="RequestLocalizationOptions"/>, containing localization settings to be applied.</param>
public void Configure(IApplicationBuilder app, IOptions<RequestLocalizationOptions> options)
{
// runs the RequestLocalizationMiddleware with the provided options
app.UseRequestLocalization(options.Value);
}
}
@@ -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;
/// <summary>
/// Middleware to handle requests lacking a culture prefix in the URL, by redirecting to a default culture.
/// </summary>
public class CultureRedirectMiddleware
{
private readonly RequestDelegate _next;
/// <summary>
/// Initializes a new instance of the <see cref="CultureRedirectMiddleware"/> class.
/// </summary>
/// <param name="next">The next middleware in the request pipeline.</param>
public CultureRedirectMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// Handles incoming requests and redirects to the default culture if necessary.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
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<IRequestCultureFeature>();
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);
}
}
@@ -1,5 +1,8 @@
namespace Lumina.Presentation.Web.Common.Services;
/// <summary>
/// Interface for the service for generating URLs from action and controller names, with URL localization.
/// </summary>
public interface IUrlService
{
/// <summary>
@@ -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;
/// <summary>
/// Service for generating URLs from action and controller names.
/// Service for generating URLs from action and controller names, with URL localization.
/// </summary>
public class UrlService : IUrlService
{
private readonly LinkGenerator _linkGenerator;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
/// <summary>
/// Initializes a new instance of the <see cref="UrlService"/> class.
/// </summary>
/// <param name="linkGenerator">The ASP.NET Core link generator service.</param>
/// <param name="httpContextAccessor">Provides access to the current HTTP context.</param>
public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor)
/// <param name="actionDescriptorCollectionProvider">The <see cref="IActionDescriptorCollectionProvider"/> used to retrieve information about the application's routes and actions.</param>
public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_linkGenerator = linkGenerator;
_httpContextAccessor = httpContextAccessor;
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
/// <summary>
@@ -32,7 +39,25 @@ public class UrlService : IUrlService
/// <returns>An absolute URL to the specified action.</returns>
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<ControllerActionDescriptor>()
.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);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Middlewares;
using Microsoft.AspNetCore.Builder;
#endregion
namespace Lumina.Presentation.Web.Common.Utilities;
/// <summary>
/// Extension methods for making it easier for <see cref="CultureRedirectMiddleware"/> to be added the middleware.
/// </summary>
// Extension method to make it easier to add the middleware
public static class CultureRedirectMiddlewareExtensions
{
/// <summary>
/// Adds the <see cref="CultureRedirectMiddleware"/> to the application's request pipeline.
/// Redirects requests to include or validate the culture in the URL.
/// </summary>
/// <param name="builder">The <see cref="IApplicationBuilder"/> used to configure the application's request pipeline.</param>
/// <returns>The <see cref="IApplicationBuilder"/> for further configuration.</returns>
public static IApplicationBuilder UseCultureRedirect(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CultureRedirectMiddleware>();
}
}
@@ -52,7 +52,6 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> 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();
@@ -15,7 +15,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement;
/// Controller for managing file system directories.
/// </summary>
[Authorize]
[Route("[controller]")]
[Route("directories")]
public class DirectoriesController : Controller
{
private readonly IApiHttpClient _apiHttpClient;
@@ -39,7 +39,7 @@ public class DirectoriesController : Controller
public async Task<IActionResult> GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<DirectoryModel> response = await _apiHttpClient.GetAsync<DirectoryModel[]>(
$"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<IActionResult> GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<FileSystemTreeNodeModel> response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
$"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<IActionResult> GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken);
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
$"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
}
}
@@ -13,7 +13,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement;
/// Controller for managing file system drives.
/// </summary>
[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<IActionResult> GetDrives(CancellationToken cancellationToken)
{
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"drives/get-drives", cancellationToken);
FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>($"drives/get-drives", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = new { drives = response } });
}
}
@@ -13,7 +13,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement;
/// Controller for managing file systems.
/// </summary>
[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<IActionResult> GetType(CancellationToken cancellationToken)
{
FileSystemTypeModel response = await _apiHttpClient.GetAsync<FileSystemTypeModel>($"file-system/get-type", cancellationToken);
FileSystemTypeModel response = await _apiHttpClient.GetAsync<FileSystemTypeModel>($"file-system/get-type", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = new { platformType = response.PlatformType.ToString() } });
}
}
@@ -15,7 +15,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement;
/// Controller for managing file system files.
/// </summary>
[Authorize]
[Route("[controller]")]
[Route("files")]
public class FilesController : Controller
{
private readonly IApiHttpClient _apiHttpClient;
@@ -39,7 +39,7 @@ public class FilesController : Controller
public async Task<IActionResult> GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<FileSystemTreeNodeModel> response = await _apiHttpClient.GetAsync<FileSystemTreeNodeModel[]>(
$"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<IActionResult> GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
IEnumerable<FileModel> response = await _apiHttpClient.GetAsync<FileModel[]>(
$"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 });
}
}
@@ -14,7 +14,7 @@ namespace Lumina.Presentation.Web.Controllers.FileSystemManagement;
/// Controller for managing file system paths.
/// </summary>
[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<IActionResult> GetPathRoot([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel response = await _apiHttpClient.GetAsync<PathSegmentModel>($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken);
PathSegmentModel response = await _apiHttpClient.GetAsync<PathSegmentModel>($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = new { root = response } });
}
@@ -47,7 +47,7 @@ public class PathController : Controller
[HttpGet("get-path-separator")]
public async Task<IActionResult> GetPathSeparator(CancellationToken cancellationToken)
{
PathSeparatorModel response = await _apiHttpClient.GetAsync<PathSeparatorModel>($"path/get-path-separator", cancellationToken);
PathSeparatorModel response = await _apiHttpClient.GetAsync<PathSeparatorModel>($"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<IActionResult> GetPathParent([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken);
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"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<IActionResult> SplitPath([FromQuery] string path, CancellationToken cancellationToken)
{
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken);
PathSegmentModel[] response = await _apiHttpClient.GetAsync<PathSegmentModel[]>($"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<IActionResult> ValidatePath([FromQuery] string path, CancellationToken cancellationToken)
{
PathValidModel response = await _apiHttpClient.GetAsync<PathValidModel>($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken);
PathValidModel response = await _apiHttpClient.GetAsync<PathValidModel>($"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<IActionResult> CheckPathExists([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
PathExistsModel response = await _apiHttpClient.GetAsync<PathExistsModel>($"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken);
PathExistsModel response = await _apiHttpClient.GetAsync<PathExistsModel>(
$"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = new { exists = response.Exists } });
}
}
@@ -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;
/// <summary>
/// Controller for home page.
/// </summary>
[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<HomeController> _logger;
public HomeController(ILogger logger)
/// <summary>
/// Initializes a new instance of the <see cref="HomeController"/> class.
/// </summary>
/// <param name="logger">Injected service for logging.</param>
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
/// <summary>
/// Displays the view for the home page.
/// </summary>
[HttpGet("")]
public IActionResult Index()
{
return View();
}
/// <summary>
/// Displays the view for privacy.
/// </summary>
[HttpGet("privacy")]
public IActionResult Privacy()
{
return View();
}
/// <summary>
/// Displays the view for errors.
/// </summary>
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[HttpGet("error")]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
@@ -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;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryManagementController"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public LibraryManagementController(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Displays the view for displaying the list of media libraries.
/// </summary>
[HttpGet("")]
public IActionResult Index()
{
return View("/Views/Library/Management/Index.cshtml");
}
/// <summary>
/// Displays the view for adding or editing a media library.
/// </summary>
/// <param name="id">The optional id of the media library to edit.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("item/{id?}")]
public async Task<IActionResult> EditLibrary(Guid? id = null, CancellationToken cancellationToken = default)
{
LibraryModel libraryModel = new();
if (id is not null)
libraryModel = await _apiHttpClient.GetAsync<LibraryModel>($"libraries/{id}", cancellationToken);
libraryModel = await _apiHttpClient.GetAsync<LibraryModel>($"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<LibraryModel, LibraryModel>($"libraries/{data.Id}", data, cancellationToken)
: await _apiHttpClient.PostAsync<LibraryModel, LibraryModel>("libraries", data, cancellationToken);
? await _apiHttpClient.PutAsync<LibraryModel, LibraryModel>($"libraries/{data.Id}", data, cancellationToken).ConfigureAwait(false)
: await _apiHttpClient.PostAsync<LibraryModel, LibraryModel>("libraries", data, cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
}
}
@@ -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("")]
@@ -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;
/// <summary>
/// Controller for language related operations.
/// </summary>
[Route("{culture}/tools/language")]
public class LanguageController : Controller
{
private readonly IUrlService _urlService;
/// <summary>
/// Initializes a new instance of the <see cref="LanguageController"/> class.
/// </summary>
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
public LanguageController(IUrlService urlService)
{
_urlService = urlService;
}
/// <summary>
/// Sets the culture used in the application.
/// </summary>
/// <param name="newCulture">The new culture to set.</param>
/// <param name="returnUrl">The URL to return to after setting the new culture.</param>
[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);
}
}
@@ -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.
/// </summary>
[Authorize]
[Route("/auth/")]
[Route("{culture}/auth")]
public class AuthController : Controller
{
private readonly IApiHttpClient _apiHttpClient;
private readonly ICryptographyService _cryptographyService;
private readonly IUrlService _urlService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthController"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService)
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService, IUrlService urlService)
{
_apiHttpClient = apiHttpClient;
_cryptographyService = cryptographyService;
_urlService = urlService;
}
/// <summary>
@@ -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<RegisterResponseModel, RegisterRequestModel>(endpoint, data, cancellationToken);
RegisterResponseModel response = await _apiHttpClient.PostAsync<RegisterResponseModel, RegisterRequestModel>(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<LoginResponseModel, LoginRequestModel>("auth/login", data, cancellationToken);
LoginResponseModel response = await _apiHttpClient.PostAsync<LoginResponseModel, LoginRequestModel>("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<Claim> 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")!);
}
/// <summary>
@@ -202,7 +229,7 @@ public class AuthController : Controller
[HttpPost("recover-password")]
public async Task<IActionResult> RecoverPassword([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken)
{
RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync<RecoverPasswordResponseModel, RecoverPasswordRequestModel>("auth/recover-password", data, cancellationToken);
RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync<RecoverPasswordResponseModel, RecoverPasswordRequestModel>("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<IActionResult> 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<ChangePasswordResponseModel, ChangePasswordRequestModel>("auth/change-password", data, cancellationToken);
ChangePasswordResponseModel response = await _apiHttpClient.PostAsync<ChangePasswordResponseModel, ChangePasswordRequestModel>("auth/change-password", data, cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
}
}
@@ -33,6 +33,300 @@
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\Views\Auth\ChangePassword.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>ChangePassword.resx</DependentUpon>
</Compile>
<Compile Update="Resources\Views\Auth\Login.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Login.resx</DependentUpon>
</Compile>
<Compile Update="Resources\Views\Auth\RecoverPassword.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>RecoverPassword.resx</DependentUpon>
</Compile>
<Compile Update="Resources\Views\Auth\Register.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Register.resx</DependentUpon>
</Compile>
<Compile Update="Resources\Views\Library\Management\Item.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Item.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Common\Filters\ApiExceptionFilter.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>ChangePassword.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\ChangePassword.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Login.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Login.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>RecoverPassword.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\RecoverPassword.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Register.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Auth\Register.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Item.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Library\Management\Item.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\Components\FileSystemBrowser\Default.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_Layout.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.de-DE.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.en-US.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.es-ES.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.fr-FR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.it-IT.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.ja-JP.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.ro-RO.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.ru-RU.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Shared\_NavMenu.zh-CN.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
</EmbeddedResource>
</ItemGroup>
<!--disable warnings generated by Mediator source generator-->
<PropertyGroup>
<NoWarn>$(NoWarn);TS6385</NoWarn>
+31 -3
View File
@@ -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();
}
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>Titel darf maximal 255 Zeichen lang sein!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>Zu viele Anfragen! Bitte versuchen Sie es in 15 Minuten erneut!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>Der TOTP-Code darf nicht leer sein!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>Title must be maximum 255 characters long!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>Too many requests! Please try again later!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>The TOTP code cannot be empty!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>¡El título debe tener máximo 255 caracteres!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>¡Demasiadas solicitudes! ¡Por favor, inténtelo en 15 minutos!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>¡El código TOTP no puede estar vacío!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>Le titre ne doit pas dépasser 255 caractères !</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>Trop de requêtes ! Veuillez réessayer dans 15 minutes !</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>Le code TOTP ne peut pas être vide!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>Il titolo deve essere lungo al massimo 255 caratteri!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>Troppe richieste! Si prega di riprovare tra 15 minuti!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>Il codice TOTP non può essere vuoto!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>タイトルは最大255文字までです!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>リクエストが多すぎます!15分後にもう一度お試しください!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>TOTPコードを入力してください!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>Title must be maximum 255 characters long!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>Too many requests! Please try again in 15 minutes!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>The TOTP code cannot be empty!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>Titlul trebuie să aibă maximum 255 caractere!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>Prea multe cereri! Vă rugăm să încercați din nou în 15 minute!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>Codul TOTP nu poate fi gol!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>Название не должно превышать 255 символов!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>Слишком много запросов! Пожалуйста, повторите попытку через 15 минут!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>Код TOTP не может быть пустым!</value>
</data>
@@ -465,6 +465,9 @@
<data name="TitleMustBeMaximum255CharactersLong" xml:space="preserve">
<value>标题最多只能有255个字符!</value>
</data>
<data name="TooManyRequests" xml:space="preserve">
<value>请求过多!请15分钟后重试!</value>
</data>
<data name="TotpCannotBeEmpty" xml:space="preserve">
<value>TOTP验证码不能为空!</value>
</data>
@@ -124,7 +124,7 @@
<value>Adaugă dosar</value>
</data>
<data name="AddNewLibrary" xml:space="preserve">
<value>Adaugă Librărie Nouă</value>
<value>Adaugă Bibliotecă Nouă</value>
</data>
<data name="Anime" xml:space="preserve">
<value>Anime</value>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Interviews</value>
</data>
<data name="Language" xml:space="preserve">
<value>Sprache</value>
</data>
<data name="Library" xml:space="preserve">
<value>Mediathek</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Interviews</value>
</data>
<data name="Language" xml:space="preserve">
<value>Language</value>
</data>
<data name="Library" xml:space="preserve">
<value>Library</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Entrevistas</value>
</data>
<data name="Language" xml:space="preserve">
<value>Lenguaje</value>
</data>
<data name="Library" xml:space="preserve">
<value>Biblioteca</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Entretiens</value>
</data>
<data name="Language" xml:space="preserve">
<value>Langue</value>
</data>
<data name="Library" xml:space="preserve">
<value>Bibliothèque</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Interviste</value>
</data>
<data name="Language" xml:space="preserve">
<value>Lingua</value>
</data>
<data name="Library" xml:space="preserve">
<value>Libreria</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>インタビュー</value>
</data>
<data name="Language" xml:space="preserve">
<value>言語</value>
</data>
<data name="Library" xml:space="preserve">
<value>ライブラリ</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Interviews</value>
</data>
<data name="Language" xml:space="preserve">
<value>Language</value>
</data>
<data name="Library" xml:space="preserve">
<value>Library</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Interviuri</value>
</data>
<data name="Language" xml:space="preserve">
<value>Limbă</value>
</data>
<data name="Library" xml:space="preserve">
<value>Bibliotecă</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>Интервью</value>
</data>
<data name="Language" xml:space="preserve">
<value>Язык</value>
</data>
<data name="Library" xml:space="preserve">
<value>Библиотека</value>
</data>
@@ -144,6 +144,9 @@
<data name="Interviews" xml:space="preserve">
<value>面试</value>
</data>
<data name="Language" xml:space="preserve">
<value>语言</value>
</data>
<data name="Library" xml:space="preserve">
<value>媒体库</value>
</data>
@@ -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
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-55 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="Auth" asp-action="ChangePassword" method="post" id="change-password-form" class="inline">
<form method="post" id="change-password-form" class="inline">
@Html.AntiForgeryToken()
<input type="text" name="username" autocomplete="username" value="@User.Identity!.Name" hidden />
<div class="form-container">
<!-- Current Password -->
<div class="form-row" id="div-current-password">
<div class="form-label">
<label asp-for="CurrentPassword">Current Password</label>
<label asp-for="CurrentPassword">@_localizer["CurrentPassword"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input type="password" asp-for="CurrentPassword" autocomplete="new-password" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionCurrentPassword</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionCurrentPassword"]</small>
</div>
<!-- New Password -->
<div class="form-row" id="div-new-password">
<div class="form-label">
<label asp-for="NewPassword">New Password</label>
<label asp-for="NewPassword">@_localizer["NewPassword"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input type="password" asp-for="NewPassword" autocomplete="new-password" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionNewPassword</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionNewPassword"]</small>
</div>
<!-- New Password Confirm-->
<div class="form-row" id="div-new-password-confirm">
<div class="form-label">
<label asp-for="NewPasswordConfirm">New Password Confirm</label>
<label asp-for="NewPasswordConfirm">@_localizer["NewPasswordConfirm"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input type="password" asp-for="NewPasswordConfirm" autocomplete="new-password" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionNewPasswordConfirm</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionNewPasswordConfirm"]</small>
</div>
<div class="form-row" id="div-change-password-submit" style="justify-content: center;">
<button type="submit" class="confirm-button h-22px w-150px">Change Password</button>
<button type="submit" class="confirm-button h-22px">@_localizer["ChangePasswordKey"]</button>
</div>
</div>
</form>
<!-- section registration success -->
<div class="text-center w-100">
<p id="change-password-success" class="text-light-one w-100 hidden">Password Changed</p>
<p id="change-password-success" class="text-light-one w-100 hidden">@_localizer["PasswordChanged"]</p>
</div>
</div>
@section Scripts {
@@ -103,7 +105,5 @@
divChangePasswordSubmit.classList.add('hidden');
}
}
</script>
}
@@ -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
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="Auth" asp-action="Login" method="post" id="login-form" class="inline">
<form method="post" id="login-form" class="inline">
@Html.AntiForgeryToken()
<input type="hidden" name="ReturnUrl" value="@ViewData["ReturnUrl"]" />
<div class="form-container">
<!-- Username -->
<div class="form-row">
<div class="form-label">
<label asp-for="Username">Username</label>:
<label asp-for="Username">@_localizer["Username"]</label>:
</div>
<div class="form-field">
<input asp-for="Username" autocomplete="username" class="enlightenment-input" />
@@ -32,27 +34,27 @@
<!-- Password -->
<div class="form-row">
<div class="form-label">
<label asp-for="Password">Password</label>:
<label asp-for="Password">@_localizer["Password"]</label>:
</div>
<div class="form-field">
<input type="password" asp-for="Password" autocomplete="current-password" class="enlightenment-input" />
</div>
</div>
<div class="form-row">
<button id="btn-recover-password" type="button" class="abort-button h-22px w-150px">Recover Password</button>
<button id="btn-login" type="submit" class="confirm-button h-22px w-100px">Login</button>
<button id="btn-recover-password" type="button" class="abort-button h-22px">@_localizer["RecoverPassword"]</button>
<button id="btn-login" type="submit" class="confirm-button h-22px">@_localizer["LoginKey"]</button>
</div>
<!-- 2FA -->
<div class="form-row mt-10 hidden" id="div-totp-code">
<div class="form-label">
<label asp-for="TotpCode">Totp Code</label>
<label asp-for="TotpCode">@_localizer["TotpCode"]</label>
</div>
<div class="form-field">
<input type="number" asp-for="TotpCode" autocomplete="one-time-code" class="enlightenment-input" />
</div>
</div>
<div class="form-row">
<button type="submit" id="btn-validate-totp" class="confirm-button h-22px w-100px hidden">Validate Code</button>
<button type="submit" id="btn-validate-totp" class="confirm-button h-22px hidden">@_localizer["ValidateCode"]</button>
</div>
</div>
</form>
@@ -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
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="Auth" asp-action="RecoverPassword" method="post" id="recover-password-form" class="inline">
<form method="post" id="recover-password-form" class="inline">
@Html.AntiForgeryToken()
<div class="form-container">
<!-- Username -->
<div class="form-row" id="div-username">
<div class="form-label">
<label asp-for="Username">Username</label>
<label asp-for="Username">@_localizer["Username"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
@@ -32,7 +34,7 @@
<!-- 2FA -->
<div class="form-row" id="div-totp-code">
<div class="form-label">
<label asp-for="TotpCode">Totp Code</label>
<label asp-for="TotpCode">@_localizer["TotpCode"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
@@ -40,15 +42,15 @@
</div>
</div>
<div class="form-row">
<button id="btn-login" type="button" class="abort-button h-22px w-100px">Back To Login</button>
<button type="submit" id="btn-validate-totp" class="confirm-button h-22px w-100px">Validate Code</button>
<button id="btn-login" type="button" class="abort-button h-22px">@_localizer["BackToLogin"]</button>
<button type="submit" id="btn-validate-totp" class="confirm-button h-22px">@_localizer["ValidateCode"]</button>
</div>
</div>
</form>
<!-- section registration success -->
<div class="text-center w-100">
<p id="recover-password-success" class="text-light-one w-100 hidden">Password Temporarily Reset</p>
<button id="btn-redirect-login" type="submit" class="confirm-button h-22px w-80px hidden">Login</button>
<p id="recover-password-success" class="text-light-one w-100 hidden">@_localizer["PasswordTemporarilyReset"]</p>
<button id="btn-redirect-login" type="submit" class="confirm-button h-22px hidden">@_localizer["Login"]</button>
</div>
</div>
@section Scripts {
@@ -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
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="Auth" asp-action="Register" method="post" id="register-account-form" class="inline">
<form method="post" id="register-account-form" class="inline">
@Html.AntiForgeryToken()
<!-- section for determining registration type (regular user/admin) -->
<input type="hidden" name="RegistrationType" value="@registrationType" />
@@ -25,41 +27,41 @@
@if (registrationType == "Admin")
{
<div class="form-row">
<p class="invalid-feedback w-95 text-center f-18">Admin account registration</p>
<p class="invalid-feedback w-95 text-center f-18">@_localizer["AdminAccountRegistration"]</p>
</div>
}
<!-- Username -->
<div class="form-row">
<div class="form-label">
<label asp-for="Username">Username</label>
<label asp-for="Username">@_localizer["Username"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input asp-for="Username" autocomplete="username" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionUsername</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionUsername"]</small>
</div>
<!-- Password -->
<div class="form-row">
<div class="form-label">
<label asp-for="Password">Password</label>
<label asp-for="Password">@_localizer["Password"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input type="password" asp-for="Password" autocomplete="new-password" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionPassword</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionPassword"]</small>
</div>
<!-- Password Confirm-->
<div class="form-row">
<div class="form-label">
<label asp-for="PasswordConfirm">Password Confirm</label>
<label asp-for="PasswordConfirm">@_localizer["PasswordConfirm"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input type="password" asp-for="PasswordConfirm" autocomplete="new-password" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionPasswordConfirm</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionPasswordConfirm"]</small>
</div>
<!-- 2FA -->
<input type="hidden" id="hidden-use-two-fa" name="use2fa" value="true">
@@ -68,27 +70,27 @@
<label class="enlightenment-checkbox-label">
<input type="checkbox" asp-for="Use2fa" class="enlightenment-checkbox-hidden" value="true" checked/>
<span class="enlightenment-checkbox"></span>
Enable two factor authentication
@_localizer["EnableTwoFactorAuthentication"]
</label>
</div>
<small class="form-label text-disabled form-description">Description2Fa</small>
<small class="form-label text-disabled form-description">@_localizer["Description2Fa"]</small>
</div>
<div class="form-row">
<span id="register-two-fa-attention" class="invalid-feedback w-95 text-center hidden">Password recovery is allowed only if two factor authentication is enabled!</span>
<span id="register-two-fa-attention" class="invalid-feedback w-95 text-center hidden">@_localizer["DisclaimerTwoFactor"]</span>
</div>
<div class="form-row" style="justify-content: center;">
<button type="submit" class="confirm-button h-22px w-100px">Register</button>
<button type="submit" class="confirm-button h-22px">@_localizer["RegisterKey"]</button>
</div>
</div>
</form>
<!-- section registration success -->
<div class="text-center w-100">
<p id="register-success" class="text-light-one w-100 hidden">Account Created</p>
<p id="register-success" class="text-light-one w-100 hidden">@_localizer["AccountCreated"]</p>
<img id="totp-image" class="w-200px h-200px h-align-m mx-auto mt-10 hidden" />
<p id="totp-message" class="text-light-one w-100 hidden">Scan Totp Code</p>
<p id="totp-message" class="text-light-one w-100 hidden">@_localizer["ScanTotpCode"]</p>
@if (User?.Identity?.IsAuthenticated == false)
{
<button id="btn-login" type="button" class="confirm-button h-22px w-80px mx-auto mt-10 hidden">Login</button>
<button id="btn-login" type="button" class="confirm-button h-22px mx-auto mt-10 hidden">@_localizer["Login"]</button>
}
</div>
</div>
@@ -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', () => {
@@ -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 @@
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="LibraryManagement" asp-action="EditLibrary" method="post" id="add-media-library-form" class="inline">
<form method="post" id="add-media-library-form" class="inline">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Id" value="@id" />
<input type="hidden" asp-for="UserId" value="@Model.UserId"/>
<div class="form-row">
<h1 class="text-light-two w-100 text-center pt-0 pb-0 engraved-title">@(id is not null ? "Edit" : "Add New") Library</h1>
<h1 class="text-light-two w-100 text-center pt-0 pb-0 engraved-title">
@(_localizer[id is not null ? "EditLibrary" : "AddNewLibrary"])
</h1>
</div>
<div class="form-container">
<h3 class="text-light-two">General Information</h3>
<h3 class="text-light-two">@_localizer["GeneralInformation"]</h3>
<!-- Title -->
<div class="form-row">
<div class="form-label">
<label asp-for="Title">Title</label>
<label asp-for="Title">@_localizer["Title"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
<input asp-for="Title" class="enlightenment-input" />
</div>
<small class="form-label text-disabled form-description">DescriptionTitle</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionTitle"]</small>
</div>
<!-- Library Type -->
<div class="form-row">
<div class="form-label">
<label asp-for="LibraryType">Library Type</label>
<label asp-for="LibraryType">@_localizer["LibraryType"]</label>
<span class="mandatory-field">*</span>:
</div>
<div class="form-field">
@@ -50,60 +54,59 @@
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" class="enlightenment-toggle-checkbox" id="library-type" />
<label class="enlightenment-toggle" for="library-type">
<span class="enlightenment-selected-text">@Model.LibraryType</span>
<span id="library-selected-item" class="enlightenment-selected-text" data-value="@(Model.LibraryType ?? "Book")">@(Model.LibraryType ?? _localizer["Book"].Value)</span>
</label>
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<!-- Dropdown options remain the same -->
<div class="enlightenment-option first-option disabled">Written Content</div>
<div class="enlightenment-option" data-value="Book">Book</div>
<div class="enlightenment-option" data-value="EBook">E Book</div>
<div class="enlightenment-option" data-value="BookSeries">Book Series</div>
<div class="enlightenment-option" data-value="ComicBook">Comic Book</div>
<div class="enlightenment-option" data-value="ComicSeries">Comic Series</div>
<div class="enlightenment-option" data-value="Magazine">Magazine</div>
<div class="enlightenment-option" data-value="Manga">Manga</div>
<div class="enlightenment-option" data-value="GraphicNovel">Graphic Novel</div>
<div class="enlightenment-option" data-value="AcademicPaper">Academic Paper</div>
<div class="enlightenment-option" data-value="SheetMusic">Sheet Music</div>
<div class="enlightenment-option" data-value="Screenplay">Screenplay</div>
<div class="enlightenment-option disabled">Video Content</div>
<div class="enlightenment-option" data-value="TvShow">Tv Show</div>
<div class="enlightenment-option" data-value="Movie">Movie</div>
<div class="enlightenment-option" data-value="FilmSeries">Film Series</div>
<div class="enlightenment-option" data-value="FilmFranchise">Film Franchise</div>
<div class="enlightenment-option" data-value="Concert">Concert</div>
<div class="enlightenment-option" data-value="Documentary">Documentary</div>
<div class="enlightenment-option" data-value="Tutorial">Tutorial</div>
<div class="enlightenment-option" data-value="Personal">Personal</div>
<div class="enlightenment-option" data-value="Anime">Anime</div>
<div class="enlightenment-option" data-value="Youtube">Youtube</div>
<div class="enlightenment-option" data-value="Videoclip">Videoclip</div>
<div class="enlightenment-option disabled">Audio Content</div>
<div class="enlightenment-option" data-value="Music">Music</div>
<div class="enlightenment-option" data-value="AudioBook">Audio Book</div>
<div class="enlightenment-option" data-value="LivePerformance">Live Performance</div>
<div class="enlightenment-option" data-value="Interview">Interview</div>
<div class="enlightenment-option" data-value="Cover">Cover</div>
<div class="enlightenment-option" data-value="Remix">Remix</div>
<div class="enlightenment-option" data-value="Soundeffect">Soundeffect</div>
<div class="enlightenment-option" data-value="Podcast">Podcast</div>
<div class="enlightenment-option" data-value="RadioShow">Radio Show</div>
<div class="enlightenment-option disabled">Visual Content</div>
<div class="enlightenment-option" data-value="PhotoAlbum">Photo Album</div>
<div class="enlightenment-option disabled">Miscellaneous Content</div>
<div class="enlightenment-option last-option" data-value="Other">Other</div>
<div class="enlightenment-option first-option disabled">@_localizer["WrittenContent"]</div>
<div class="enlightenment-option" data-value="Book">@_localizer["Book"]</div>
<div class="enlightenment-option" data-value="EBook">@_localizer["EBook"]</div>
<div class="enlightenment-option" data-value="BookSeries">@_localizer["BookSeries"]</div>
<div class="enlightenment-option" data-value="ComicBook">@_localizer["ComicBook"]</div>
<div class="enlightenment-option" data-value="ComicSeries">@_localizer["ComicSeries"]</div>
<div class="enlightenment-option" data-value="Magazine">@_localizer["Magazine"]</div>
<div class="enlightenment-option" data-value="Manga">@_localizer["Manga"]</div>
<div class="enlightenment-option" data-value="GraphicNovel">@_localizer["GraphicNovel"]</div>
<div class="enlightenment-option" data-value="AcademicPaper">@_localizer["AcademicPaper"]</div>
<div class="enlightenment-option" data-value="SheetMusic">@_localizer["SheetMusic"]</div>
<div class="enlightenment-option" data-value="Screenplay">@_localizer["Screenplay"]</div>
<div class="enlightenment-option disabled">@_localizer["VideoContent"]</div>
<div class="enlightenment-option" data-value="TvShow">@_localizer["TvShow"]</div>
<div class="enlightenment-option" data-value="Movie">@_localizer["Movie"]</div>
<div class="enlightenment-option" data-value="FilmSeries">@_localizer["FilmSeries"]</div>
<div class="enlightenment-option" data-value="FilmFranchise">@_localizer["FilmFranchise"]</div>
<div class="enlightenment-option" data-value="Concert">@_localizer["Concert"]</div>
<div class="enlightenment-option" data-value="Documentary">@_localizer["Documentary"]</div>
<div class="enlightenment-option" data-value="Tutorial">@_localizer["Tutorial"]</div>
<div class="enlightenment-option" data-value="Personal">@_localizer["Personal"]</div>
<div class="enlightenment-option" data-value="Anime">@_localizer["Anime"]</div>
<div class="enlightenment-option" data-value="Youtube">@_localizer["Youtube"]</div>
<div class="enlightenment-option" data-value="Videoclip">@_localizer["Videoclip"]</div>
<div class="enlightenment-option disabled">@_localizer["AudioContent"]</div>
<div class="enlightenment-option" data-value="Music">@_localizer["Music"]</div>
<div class="enlightenment-option" data-value="AudioBook">@_localizer["AudioBook"]</div>
<div class="enlightenment-option" data-value="LivePerformance">@_localizer["LivePerformance"]</div>
<div class="enlightenment-option" data-value="Interview">@_localizer["Interview"]</div>
<div class="enlightenment-option" data-value="Cover">@_localizer["Cover"]</div>
<div class="enlightenment-option" data-value="Remix">@_localizer["Remix"]</div>
<div class="enlightenment-option" data-value="Soundeffect">@_localizer["Soundeffect"]</div>
<div class="enlightenment-option" data-value="Podcast">@_localizer["Podcast"]</div>
<div class="enlightenment-option" data-value="RadioShow">@_localizer["RadioShow"]</div>
<div class="enlightenment-option disabled">@_localizer["VisualContent"]</div>
<div class="enlightenment-option" data-value="PhotoAlbum">@_localizer["PhotoAlbum"]</div>
<div class="enlightenment-option disabled">@_localizer["MiscellaneousContent"]</div>
<div class="enlightenment-option last-option" data-value="Other">@_localizer["Other"]</div>
</div>
</div>
</div>
<small class="form-label text-disabled form-description">DescriptionLibraryType</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionLibraryType"]</small>
</div>
<!-- Directories -->
<div class="form-row mt-10">
<div class="form-label">
<label asp-for="ContentLocations">Directories</label>
<label asp-for="ContentLocations">@_localizer["Directories"]</label>
<span class="mandatory-field">*</span>:
<img src="~/images/ui/add-directory.svg" alt="Add directory" id="add-media-directory" title="Add directory" class="add-form-table-row-icon ml-5" />
<img src="~/images/ui/add-directory.svg" alt="@_localizer["AddDirectory"]" id="add-media-directory" title="@_localizer["AddDirectory"]" class="add-form-table-row-icon ml-5" />
</div>
</div>
<div class="form-row">
@@ -112,22 +115,22 @@
{
<div class="form-table-row">
<span title="@Model.ContentLocations[i]">@Model.ContentLocations[i]</span>
<img src="~/images/ui/delete.svg" alt="Remove" title="Remove" class="remove-form-table-row-icon" />
<img src="~/images/ui/delete.svg" alt="@_localizer["Remove"]" title="@_localizer["Remove"]" class="remove-form-table-row-icon" />
</div>
}
</div>
<small class="form-label text-disabled form-description">DescriptionDirectories</small>
<small class="form-label text-disabled form-description">@_localizer["DescriptionDirectories"]</small>
</div>
<div class="form-row">
<button type="submit" class="confirm-button w-100px">Save</button>
<button type="submit" class="confirm-button w-100px">@_localizer["Save"]</button>
</div>
</div>
</form>
<!-- section success -->
<div class="text-center w-100">
<p id="save-success" class="text-light-one w-100 hidden">Library Saved</p>
<button id="btn-back-to-libraries" type="button" class="abort-button h-22px w-150px mx-auto mt-10 hidden">Back To Libraries</button>
<button id="btn-add-new-library" type="button" class="confirm-button h-22px w-150px mx-auto mt-10 hidden">Add New Library</button>
<p id="save-success" class="text-light-one w-100 hidden">@_localizer["LibrarySaved"]</p>
<button id="btn-back-to-libraries" type="button" class="abort-button h-22px w-150px mx-auto mt-10 hidden">@_localizer["BackToLibraries"]</button>
<button id="btn-add-new-library" type="button" class="confirm-button h-22px w-150px mx-auto mt-10 hidden">@_localizer["AddNewLibrary"]</button>
</div>
</div>
@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', `
<div class="form-table-row">
<span title="${path}">${path}</span>
<img src="/images/ui/delete.svg" alt="Remove" title="Remove" class="remove-form-table-row-icon" onclick="this.closest('.form-table-row').remove();" />
<img src="/images/ui/delete.svg" alt="@_localizer["Remove"]" title="@_localizer["Remove"]" class="remove-form-table-row-icon" onclick="this.closest('.form-table-row').remove();" />
</div>
`);
}
@@ -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
<div id="file-system-browser-dialog" class="container-background above-modal">
<div id="file-system-browser-content">
<div id="file-system-browser-header">
@@ -18,7 +21,7 @@
<div id="navigator-view-mode-container">
<!--List View Mode-->
<svg id="navigator-list-view" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>List View</title>
<title>@_localizer["ListView"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -70,7 +73,7 @@
</svg>
<!--Details View Mode-->
<svg id="navigator-details-view" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Details View</title>
<title>@_localizer["DetailsView"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -121,7 +124,7 @@
</svg>
<!--Small Icons View Mode-->
<svg id="navigator-small-icons-view" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Small Icons View</title>
<title>@_localizer["SmallIconsView"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -182,7 +185,7 @@
</svg>
<!--Medium Icons View Mode-->
<svg id="navigator-medium-icons-view" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Medium Icons View</title>
<title>@_localizer["MediumIconsView"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -228,7 +231,7 @@
</svg>
<!--Large Icons View Mode-->
<svg id="navigator-large-icons-view" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Large Icons View</title>
<title>@_localizer["LargeIconsView"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -265,7 +268,7 @@
</svg>
<!--Extra Large Icons View Mode-->
<svg id="navigator-extra-large-icons-view" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Extra Large Icons View</title>
<title>@_localizer["ExtraLargeIconsView"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -304,13 +307,13 @@
<div id="navigator-navigation-controls-container">
<!--Navigation-->
<div id="navigator-history">
<img src="~/images/ui/back.svg" id="navigator-navigate-back" class="navigation-icon" alt="Back" title="Back" />
<img src="~/images/ui/forward.svg" id="navigator-navigate-forward" class="navigation-icon" alt="Forward" title="Forward" />
<img src="~/images/ui/up.svg" id="navigator-navigate-up" class="navigation-icon" alt="Up One Level" title="Up One Level" />
<img src="~/images/ui/back.svg" id="navigator-navigate-back" class="navigation-icon" alt="@_localizer["Back"]" title="@_localizer["Back"]" />
<img src="~/images/ui/forward.svg" id="navigator-navigate-forward" class="navigation-icon" alt="@_localizer["Forward"]" title="@_localizer["Forward"]" />
<img src="~/images/ui/up.svg" id="navigator-navigate-up" class="navigation-icon" alt="@_localizer["UpOneLevel"]" title="@_localizer["UpOneLevel"]" />
</div>
<!--Toggle Tree View-->
<svg id="navigator-toggle-tree-view-button" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Toggle Tree View</title>
<title>@_localizer["ToggleTreeView"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -346,7 +349,7 @@
</svg>
<!--Toggle Thumbnails-->
<svg id="navigator-toggle-thumbnails-button" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Toggle Thumbanils</title>
<title>@_localizer["ToggleThumbanils"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -382,7 +385,7 @@
</svg>
<!--Toggle Hidden Elements-->
<svg id="navigator-toggle-hidden-button" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Toggle Hidden Items</title>
<title>@_localizer["ToggleHiddenItems"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -420,7 +423,7 @@
</svg>
<!--Toggle Selection Mode-->
<svg id="navigator-toggle-selection-button" class="navigator-icon" width="30" height="30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Toggle Selection Mode</title>
<title>@_localizer["ToggleSelectionMode"]</title>
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feComponentTransfer in="SourceAlpha" result="adjustedAlpha">
@@ -464,16 +467,16 @@
</div>
</div>
<button id="navigator-edit-path-button" class="navigator-edit-path-button abort-button f-16" style="height:28px; width:35px;">
<img src="~/images/ui/edit.svg" id="navigator-edit-icon" alt="Edit Path" title="Edit Path" />
<img src="~/images/ui/edit.svg" id="navigator-edit-icon" alt="@_localizer["EditPath"]" title="@_localizer["EditPath"]" />
</button>
<button id="navigator-navigate-button" class="navigator-navigate-button confirm-button f-16" style="height:28px; width:35px;">
<img src="~/images/ui/check.svg" id="navigator-navigate-icon" alt="Navigate" title="Navigate" />
<img src="~/images/ui/check.svg" id="navigator-navigate-icon" alt="@_localizer["Navigate"]" title="@_localizer["Navigate"]" />
</button>
<button class="file-system-browser-content-new-directory abort-button f-16" style="height:28px; width:35px;">
<img src="~/images/ui/new-directory.svg" id="navigator-new-directory-icon" alt="New Directory" title="New Directory" />
<img src="~/images/ui/new-directory.svg" id="navigator-new-directory-icon" alt="@_localizer["NewDirectory"]" title="@_localizer["NewDirectory"]" />
</button>
<button class="file-system-browser-content-favorite-directory abort-button f-16" style="height:28px; width:35px;">
<img src="~/images/ui/favorite-star.svg" class="navigation-icon favorite-unselected" alt="Favorite directory" title="Favorite directory" />
<img src="~/images/ui/favorite-star.svg" class="navigation-icon favorite-unselected" alt="@_localizer["FavoriteDirectory"]" title="@_localizer["FavoriteDirectory"]" />
</button>
</div>
<!--End File System Navigator-->
@@ -492,7 +495,7 @@
<div id="file-system-browser-file-system-directories">
<div id="file-system-browser-file-system-explorer-container" class="scroll-horizontal">
<div id="file-system-browser-file-system-explorer-details-header" style="height: 0px;">
<span>Name</span>
<span>@_localizer["Name"]</span>
</div>
<div id="file-system-browser-file-system-explorer">
</div>
@@ -502,20 +505,20 @@
</div>
<div id="file-system-browser-actions-container">
<div id="file-system-browser-actions-path-container">
<label class="text-light-one">Directory</label>
<label class="text-light-one">@_localizer["Directory"]</label>
<input type="text" id="file-system-browser-selected-element" Name="file-system-browser-selected-element" class="enlightenment-input w-100" readonly autocomplete="on" />
</div>
<div id="file-system-browser-actions">
<button id="file-system-browser-cancel-button" class="abort-button w-100px">Cancel</button>
<button id="file-system-browser-confirm-button" class="confirm-button w-100px" disabled>Open</button>
<button id="file-system-browser-cancel-button" class="abort-button w-100px">@_localizer["Cancel"]</button>
<button id="file-system-browser-confirm-button" class="confirm-button w-100px" disabled>@_localizer["Open"]</button>
</div>
</div>
</div>
@* <div id="divModal"></div>
<label class="text-light-one">Enter new directory name:</label>
<label class="text-light-one">@_localizer["EnterNewDirectoryName"]</label>
<EnlightenmentInput Type="text" Name="newDirectoryName" AutoComplete="true" />
<EnlightenmentButton IsConfirmButton="false">Cancel</EnlightenmentButton>
<EnlightenmentButton>Confirm</EnlightenmentButton> *@
<EnlightenmentButton IsConfirmButton="false">@_localizer["Cancel"]</EnlightenmentButton>
<EnlightenmentButton>@_localizer["Confirm"]</EnlightenmentButton> *@
</div>
<div id="visible-selection-rectangle"></div>
<div id="selection-rectangle"></div>
@@ -1,3 +1,7 @@
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer _localizer
<!DOCTYPE html>
<html lang="en">
<head>
@@ -27,7 +31,6 @@
</article>
</main>
@if (User?.Identity?.IsAuthenticated == true)
{
<!--Audio player-->
<div class="audio-player-container">
@@ -36,8 +39,8 @@
height="50" width="600">
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
<a id="audio-player-full-height-toggle">Toggle Full Height</a>
<a id="audio-player-close">Toggle Visibility</a>
<a id="audio-player-full-height-toggle">@_localizer["ToggleFullHeight"]</a>
<a id="audio-player-close">@_localizer["ToggleVisibility"]</a>
</div>
}
</div>
@@ -0,0 +1 @@

@@ -1,6 +1,8 @@
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Mvc.Localization
@inject IUrlService _urlService
@inject IViewLocalizer _localizer
<input type="checkbox" id="hamburger-input" class="burger-shower" />
<label id="hamburger-menu" for="hamburger-input">
@@ -10,68 +12,85 @@
<nav id="mobile-menu">
<div id="mobile-menu-content">
<div class="mobile-menu-heading">
Account
@_localizer["Account"]
</div>
<ul>
@if (User?.Identity?.IsAuthenticated == false)
{
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Login</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Recover Password</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>@_localizer["Login"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>@_localizer["RecoverPassword"]</span></a></li>
}
else
{
<li><a href="@_urlService.GetAbsoluteUrl("Logout", "Auth")"><span>Logout</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Logout", "Auth")"><span>@_localizer["Logout"]</span></a></li>
}
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")" class="nav-link"><span>Register</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")" class="nav-link"><span>Change Password</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")" class="nav-link"><span>Profile</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")" class="nav-link"><span>@_localizer["Register"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")" class="nav-link"><span>@_localizer["ChangePassword"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")" class="nav-link"><span>@_localizer["Profile"]</span></a></li>
}
</ul>
@if (User?.Identity?.IsAuthenticated == true)
{
<div class="mobile-menu-heading">
Tools
@_localizer["Library"]
</div>
<ul>
<li><a href="tools/options"><span>Options</span></a></li>
<li><a href="library/manage" class="nav-link"><span>@_localizer["ManageLibraries"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link"><span>@_localizer["AddNewLibrary"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
Library
@_localizer["WrittenContent"]
</div>
<ul>
<li><a href="library/manage"><span>Manage libraries</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link"><span>Add new library</span></a></li>
<li><a href="library/written-content-library/books-library/books" class="nav-link"><span>@_localizer["Books"]</span></a></li>
<li><a href="library/written-content/magazines" class="nav-link"><span>@_localizer["Magazines"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
Written Content
@_localizer["Audio"]
</div>
<ul>
<li><a href="library/written-content-library/books-library/books" class="nav-link"><span>Books</span></a></li>
<li><a href="library/written-content/magazines"><span>Magazines</span></a></li>
<li><a href="library/audio/music" class="nav-link"><span>@_localizer["Music"]</span></a></li>
<li><a href="library/audio/interviews" class="nav-link"><span>@_localizer["Interviews"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
Audio
@_localizer["Video"]
</div>
<ul>
<li><a href="library/audio/music"><span>Music</span></a></li>
<li><a href="library/audio/interviews"><span>Interviews</span></a></li>
</ul>
<div class="mobile-menu-heading">
Video
</div>
<ul>
<li><a href="library/video/movies"><span>Movies</span></a></li>
<li><a href="library/video/tvshows"><span>TV Shows</span></a></li>
<li><a href="library/video/movies" class="nav-link"><span>@_localizer["Movies"]</span></a></li>
<li><a href="library/video/tvshows" class="nav-link"><span>@_localizer["TvShows"]</span></a></li>
</ul>
}
<div class="mobile-menu-heading">
Help
@_localizer["Language"]
</div>
<ul>
<li><a href="help/documentation"><span>Documentation</span></a></li>
<li><a href="help/about"><span>About</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=zh-cn&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>简体中文</span></a></li><!--CN-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=de-de&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>Deutsch</span></a></li><!--DE-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=en-us&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>English</span></a></li><!--EN-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=es-es&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>Español</span></a></li><!--ES-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=fr-fr&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>Français</span></a></li><!--FR-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=it-it&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>Italiano</span></a></li><!--IT-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=ja-jp&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>日本語</span></a></li><!--JP-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=ro-ro&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>Română</span></a></li><!--RO-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=ru-ru&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)"><span>Русский</span></a></li><!--RU-->
</ul>
@if (User?.Identity?.IsAuthenticated == true)
{
<div class="mobile-menu-heading">
@_localizer["Tools"]
</div>
<ul>
<li><a href="tools/options" class="nav-link"><span>@_localizer["Options"]</span></a></li>
</ul>
}
<div class="mobile-menu-heading">
@_localizer["Help"]
</div>
<ul>
<li><a href="help/documentation" class="nav-link"><span>@_localizer["Documentation"]</span></a></li>
<li><a href="help/about" class="nav-link"><span>@_localizer["About"]</span></a></li>
</ul>
</div>
</nav>
@@ -80,70 +99,87 @@
<ul>
<li tabindex="0">
<input type="radio" id="account-menu" name="menu">
<label for="account-menu">Account</label>
<label for="account-menu">@_localizer["Account"]</label>
<ul>
@if (User?.Identity?.IsAuthenticated == false)
{
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")">Login</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")">Recover Password</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")">@_localizer["Login"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")">@_localizer["RecoverPassword"]</a></li>
}
else
{
<li><a href="@_urlService.GetAbsoluteUrl("Logout", "Auth")">Logout</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Logout", "Auth")">@_localizer["Logout"]</a></li>
}
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")" class="nav-link">Register</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")" class="nav-link">Change Password</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")" class="nav-link">Profile</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")" class="nav-link">@_localizer["Register"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")" class="nav-link">@_localizer["ChangePassword"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")" class="nav-link">@_localizer["Profile"]</a></li>
}
</ul>
</li>
@if (User?.Identity?.IsAuthenticated == true)
{
<li tabindex="0">
<input type="radio" id="tools-menu" name="menu">
<label for="tools-menu">Tools</label>
<ul>
<li><a href="tools/options">Options</a></li>
</ul>
</li>
<li tabindex="0">
<input type="radio" id="library-menu" name="menu">
<label for="library-menu">Library</label>
<label for="library-menu">@_localizer["Library"]</label>
<ul>
<li tabindex="0"><a href="library/manage">Manage libraries</a></li>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link">Add new library</a></li>
<li tabindex="0"><a href="library/manage" class="nav-link">@_localizer["ManageLibraries"]</a></li>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link">@_localizer["AddNewLibrary"]</a></li>
<li class="has-submenu" tabindex="0">
<label>Written Content</label>
<label>@_localizer["WrittenContent"]</label>
<ul>
<li><a href="library/written-content-library/books-library/books" class="nav-link">Books</a></li>
<li><a href="library/written-content/magazines">Magazines</a></li>
<li><a href="library/written-content-library/books-library/books" class="nav-link">@_localizer["Books"]</a></li>
<li><a href="library/written-content/magazines" class="nav-link">@_localizer["Magazines"]</a></li>
</ul>
</li>
<li class="has-submenu" tabindex="0">
<label>Audio</label>
<label>@_localizer["Audio"]</label>
<ul>
<li><a href="library/audio/music">Music</a></li>
<li><a href="library/audio/interviews">Interviews</a></li>
<li><a href="library/audio/music" class="nav-link">@_localizer["Music"]</a></li>
<li><a href="library/audio/interviews" class="nav-link">@_localizer["Interviews"]</a></li>
</ul>
</li>
<li class="has-submenu" tabindex="0">
<label>Video</label>
<label>@_localizer["Video"]</label>
<ul>
<li><a href="library/video/movies">Movies</a></li>
<li><a href="library/video/tvshows">TV Shows</a></li>
<li><a href="library/video/movies" class="nav-link">@_localizer["Movies"]</a></li>
<li><a href="library/video/tvshows" class="nav-link">@_localizer["TvShows"]</a></li>
</ul>
</li>
</ul>
</li>
}
<li tabindex="0">
<input type="radio" id="help-menu" name="menu">
<label for="help-menu">Help</label>
<input type="radio" id="tools-menu" name="menu">
<label for="tools-menu">@_localizer["Tools"]</label>
<ul>
<li><a href="help/documentation">Documentation</a></li>
<li><a href="help/about">About</a></li>
<li class="has-submenu" tabindex="0">
<label>@_localizer["Language"]</label>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=zh-cn&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">简体中文</a></li><!--CN-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=de-de&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">Deutsch</a></li><!--DE-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=en-us&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">English</a></li><!--EN-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=es-es&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">Español</a></li><!--ES-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=fr-fr&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">Français</a></li><!--FR-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=it-it&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">Italiano</a></li><!--IT-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=ja-jp&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">日本語</a></li><!--JP-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=ro-ro&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">Română</a></li><!--RO-->
<li><a href="@_urlService.GetAbsoluteUrl("SetLanguage", "Language")?newCulture=ru-ru&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)">Русский</a></li><!--RU-->
</ul>
</li>
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="tools/options" class="nav-link">@_localizer["Options"]</a></li>
}
</ul>
</li>
<li tabindex="0">
<input type="radio" id="help-menu" name="menu">
<label for="help-menu">@_localizer["Help"]</label>
<ul>
<li><a href="help/documentation" class="nav-link">@_localizer["Documentation"]</a></li>
<li><a href="help/about" class="nav-link">@_localizer["About"]</a></li>
</ul>
</li>
</ul>
@@ -1,2 +0,0 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
@@ -251,6 +251,7 @@ async function updateContent(url, addToHistory) {
history.pushState(state, title, url);
}
} catch (error) {
notificationService.show('Navigation failed', NotificationType.ERROR);
console.error('Navigation failed:', error);
}
}
@@ -529,12 +530,18 @@ document.addEventListener('change', function (e) {
document.addEventListener('click', function (e) {
if (e.target.matches('.enlightenment-option')) {
var text = e.target.textContent;
var value = e.target.getAttribute('data-value');
var combobox = e.target.closest('.enlightenment-combobox');
// update the displayed text
var selectedText = combobox.querySelector('.enlightenment-selected-text');
if (selectedText)
if (selectedText) {
selectedText.textContent = text;
// update the data-value attribute with the actual value
selectedText.setAttribute('data-value', value);
}
// close the dropdown
var toggleCheckbox = combobox.querySelector('.enlightenment-toggle-checkbox');
if (toggleCheckbox)
toggleCheckbox.checked = false;
@@ -142,7 +142,7 @@ public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["ImageQaulityMustBeBetweenZeroAndOneHundred"]);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["ImageQualityMustBeBetweenZeroAndOneHundred"]);
}
[Fact]
@@ -172,7 +172,7 @@ public class AuthLoginTests : IClassFixture<LuminaApiFactory>, IDisposable
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29");
problemDetails["title"].GetString().Should().Be("TooManyRequests");
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
problemDetails["detail"].GetString().Should().Be("TooManyRequests");
problemDetails["retryAfter"].GetString().Should().Be("900");
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
@@ -68,7 +68,7 @@ public class AuthRecoverPasswordTests : IClassFixture<LuminaApiFactory>, IDispos
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29");
problemDetails["title"].GetString().Should().Be("TooManyRequests");
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
problemDetails["detail"].GetString().Should().Be("TooManyRequests");
problemDetails["retryAfter"].GetString().Should().Be("900");
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
@@ -101,7 +101,7 @@ public class AuthRegisterTests : IClassFixture<LuminaApiFactory>, IDisposable
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29");
problemDetails["title"].GetString().Should().Be("TooManyRequests");
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
problemDetails["detail"].GetString().Should().Be("TooManyRequests");
problemDetails["retryAfter"].GetString().Should().Be("900");
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
@@ -72,7 +72,7 @@ public class GetThumbnailQueryValidatorTests
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description);
result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred.Description);
}
[Fact]
@@ -85,7 +85,7 @@ public class GetThumbnailQueryValidatorTests
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description);
result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred.Description);
}
[Fact]
@@ -121,9 +121,8 @@ public class FluentValidationOptionsTests
// Assert
result.Should().BeOfType<ValidateOptionsResult>();
result.Failed.Should().BeTrue();
// TODO: should be modified to account for translation of error messages
result.Failures.Should().ContainSingle()
.Which.Should().Contain("Options validation failed for 'PropertyName' with error: 'Error Message'");
}
}
}