diff --git a/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs b/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs index 0f75f0b3..e6cf4dc8 100644 --- a/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs +++ b/src/Lumina.Contracts/Requests/Authentication/ChangePasswordRequest.cs @@ -1,3 +1,7 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + namespace Lumina.Contracts.Requests.Authentication; /// @@ -7,6 +11,7 @@ namespace Lumina.Contracts.Requests.Authentication; /// The current password of the account. Required. /// The new password of the account. Required. /// The confirmation of the new password of the account. Required. +[DebuggerDisplay("Username: {Username}")] public record ChangePasswordRequest( string? Username, string? CurrentPassword, diff --git a/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs index c7fa452b..5a0b894f 100644 --- a/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using System; +using System.Diagnostics; #endregion namespace Lumina.Contracts.Requests.Authorization; @@ -8,6 +9,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// Represents the request model for retrieving the authorization permissions of a user identified by . /// /// The unique identifier of the user for whom to get the authorization permissions. Required. +[DebuggerDisplay("UserId: {UserId}")] public record GetUserPermissionsRequest( Guid? UserId ); diff --git a/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs index fbb2faf2..3aa541af 100644 --- a/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using System; +using System.Diagnostics; #endregion namespace Lumina.Contracts.Requests.Authorization; @@ -8,6 +9,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// Represents the request model for retrieving the authorization role of a user identified by . /// /// The unique identifier of the user for whom to get the authorization role. Required. +[DebuggerDisplay("UserId: {UserId}")] public record GetUserRoleRequest( Guid? UserId ); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs index 38538c11..23503311 100644 --- a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/GetPathParentRequest.cs @@ -6,9 +6,9 @@ using System.Text.Json.Serialization; namespace Lumina.Contracts.Requests.FileSystemManagement.Path; /// -/// Represents a request to get the root of a file system path. +/// Represents the request for retrieving the parent path of a file system path. /// -/// The file system path for which to get the root. Required. +/// The path for which the parent path is retrieved. [DebuggerDisplay("Path: {Path}")] public record GetPathParentRequest( string? Path diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs index 8d0bd33a..f2989736 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs @@ -42,7 +42,7 @@ public class AddRoleEndpoint : BaseEndpoint } /// - /// Creates a new authorization role. + /// Adds a new authorization role. /// /// The request containing the authorization role to be created. /// Cancellation token that can be used to stop the execution. diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index 350dce6b..f0651b05 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Common.Exceptions; -using Lumina.Presentation.Web.Common.Models.Common; -using Lumina.Presentation.Web.Common.Models.Configuration; -using Lumina.Presentation.Web.Common.Models.FileSystemManagement; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using System; @@ -35,13 +35,13 @@ public class ApiHttpClient : IApiHttpClient /// Injected HttpClient for interacting with the API. /// Injected service for providing the current HTTP context. /// Injected server configuration application settings. - public ApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot serverConfigurationOptions) + public ApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot serverConfigurationOptions) { _httpClient = httpClient; _httpContext = httpContextAccessor.HttpContext; // read the API server configuration values from the configuration, and assign them to the injected client - ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value; - httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/"); + ServerConfigurationDto serverConfiguration = serverConfigurationOptions.Value; + httpClient.BaseAddress = new Uri($"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/api/v{serverConfiguration.ApiVersion}/"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); @@ -101,7 +101,7 @@ public class ApiHttpClient : IApiHttpClient /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. /// A model containing the deserialized blob. - public async Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) + public async Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Get, endpoint); AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); @@ -112,10 +112,10 @@ public class ApiHttpClient : IApiHttpClient { // read the content as a string, for error messages string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - ProblemDetailsModel? problemDetails = null; + ProblemDetailsDto? problemDetails = null; try { - problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } throw new ApiException(problemDetails, response.StatusCode); @@ -123,7 +123,7 @@ public class ApiHttpClient : IApiHttpClient // if the response is successful, read it as a byte array byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); string contentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream"; - return new BlobDataModel { Data = responseContent, ContentType = contentType }; + return new BlobDataDto { Data = responseContent, ContentType = contentType }; } /// @@ -142,12 +142,12 @@ public class ApiHttpClient : IApiHttpClient HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { - ProblemDetailsModel? problemDetails = null; + ProblemDetailsDto? problemDetails = null; string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // attempt to deserialize the response content to ProblemDetailsModel if the request fails + // attempt to deserialize the response content to ProblemDetailsDto if the request fails try { - problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); @@ -194,13 +194,13 @@ public class ApiHttpClient : IApiHttpClient /// /// Sends an HTTP request and deserializes the response into the specified type if the request is successful. - /// If the request fails, it attempts to deserialize the response content into a and throws an . + /// If the request fails, it attempts to deserialize the response content into a and throws an . /// /// The expected type of the response content. /// The to be sent. /// Cancellation token that can be used to stop the execution. /// The deserialized response content as an object of type . - /// Thrown if the response is not successful, with the if available. + /// Thrown if the response is not successful, with the if available. private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // send the HTTP request and read the response @@ -216,11 +216,11 @@ public class ApiHttpClient : IApiHttpClient } else { - ProblemDetailsModel? problemDetails = null; - // attempt to deserialize the response content to ProblemDetailsModel if the request fails + ProblemDetailsDto? problemDetails = null; + // attempt to deserialize the response content to ProblemDetailsDto if the request fails try { - problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index 86a1e71d..cfbb30ad 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.FileSystemManagement; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -36,7 +36,7 @@ public interface IApiHttpClient /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. /// A model containing the deserialized blob. - Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default); + Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a DELETE request to the specified as an asynchronous operation. diff --git a/src/Lumina.Presentation.Web/Common/Attributes/RequirePermissionAttribute.cs b/src/Lumina.Presentation.Web/Common/Attributes/RequirePermissionAttribute.cs deleted file mode 100644 index 177ce393..00000000 --- a/src/Lumina.Presentation.Web/Common/Attributes/RequirePermissionAttribute.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Authorization; -using Lumina.Presentation.Web.Common.Filters.TypeFilters; -using Lumina.Presentation.Web.Common.Models.Authorization; -#endregion - -namespace Lumina.Presentation.Web.Common.Attributes; - -/// -/// Attribute that restricts endpoint access to users with specified permissions. -/// -/// -/// Can be applied to controllers or individual actions. Multiple permissions create an OR condition. -/// -public class RequirePermissionAttribute : ApiAuthorizationAttribute -{ - /// - /// Initializes a new instance of the class. - /// - /// One or more permissions that are allowed to access the endpoint. - public RequirePermissionAttribute(params AuthorizationPermission[] permissions) : base() - { - Arguments = [new AuthorizationRequirementModel { Permissions = permissions }]; - } -} diff --git a/src/Lumina.Presentation.Web/Common/Attributes/RequirePolicyAttribute.cs b/src/Lumina.Presentation.Web/Common/Attributes/RequirePolicyAttribute.cs deleted file mode 100644 index 549a01f7..00000000 --- a/src/Lumina.Presentation.Web/Common/Attributes/RequirePolicyAttribute.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Filters.TypeFilters; -using Lumina.Presentation.Web.Common.Models.Authorization; -using System; -#endregion - -namespace Lumina.Presentation.Web.Common.Attributes; - -/// -/// Attribute that restricts endpoint access based on a custom authorization policy. -/// -/// -/// Can be applied to controllers or individual actions. -/// -public class RequirePolicyAttribute : ApiAuthorizationAttribute -{ - /// - /// Initializes a new instance of the class. - /// - /// The type of the authorization policy to apply. - public RequirePolicyAttribute(Type policyType) : base() - { - Arguments = [new AuthorizationRequirementModel { PolicyType = policyType }]; - } -} diff --git a/src/Lumina.Presentation.Web/Common/Attributes/RequireRoleAttribute.cs b/src/Lumina.Presentation.Web/Common/Attributes/RequireRoleAttribute.cs deleted file mode 100644 index 8221d78d..00000000 --- a/src/Lumina.Presentation.Web/Common/Attributes/RequireRoleAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Filters.TypeFilters; -using Lumina.Presentation.Web.Common.Models.Authorization; -#endregion - -namespace Lumina.Presentation.Web.Common.Attributes; - -/// -/// Attribute that restricts endpoint access to users with specified roles. -/// -/// -/// Can be applied to controllers or individual actions. Multiple roles create an OR condition. -/// -public class RequireRoleAttribute : ApiAuthorizationAttribute -{ - /// - /// Initializes a new instance of the class. - /// - /// One or more roles that are allowed to access the endpoint. - public RequireRoleAttribute(params string[] roles) : base() - { - Arguments = [new AuthorizationRequirementModel { Roles = roles }]; - } -} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationPolicies.cs b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationPolicies.cs new file mode 100644 index 00000000..87034320 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationPolicies.cs @@ -0,0 +1,11 @@ +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Contains the names of the authorization policies defined in the Web application. +/// +public static class AuthorizationPolicies +{ + public const string REQUIRE_ADMIN_ROLE = "RequireAdminRole"; + public const string REQUIRE_CREATE_LIBRARIES_PERMISSION = "RequireCreateLibrariesPermission"; + public const string REQUIRE_INITIALIZATION = "RequireInitialization"; +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs index f6357404..0237af63 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Enums.Authorization; -using Lumina.Presentation.Web.Common.Models.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; using Microsoft.AspNetCore.Http; using System; using System.Linq; @@ -55,42 +55,6 @@ public class AuthorizationService : IAuthorizationService return authorization.Role == role; } - /// - /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy. - /// - /// The type of authorization policy to evaluate. - /// Cancellation token that can be used to stop the execution. - /// if the currently logged in user satisfies the policy, otherwise. - public Task EvaluatePolicyAsync(CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - /// - /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization requirement. - /// - /// The authorization requirements to check. - /// if the currently logged in user satisfies the requirement, otherwise. - public async Task EvaluateAuthorizationAsync(AuthorizationRequirementModel requirement) - { - GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(CancellationToken.None); - - if (requirement.Roles?.Length > 0 && !requirement.Roles.Any(role => authorization.Role?.Contains(role) == true)) - return false; - - if (requirement.Permissions?.Length > 0 && !requirement.Permissions.Any(permission => authorization.Permissions.Contains(permission))) - return false; - - //if (_requirement.PolicyType is not null) - //{ - // bool response = await _apiHttpClient.PostAsync($"auth/evaluate-policy/{_requirement.PolicyType.Name}", null!); - // if (!response) - // return false; - //} - - return true; - } - /// /// Retrieves user authorization details from the authorization service. /// @@ -98,8 +62,10 @@ public class AuthorizationService : IAuthorizationService /// The user's authorization details. private async Task GetUserAuthorizationAsync(CancellationToken cancellationToken) { - // get the id of the currently logged in user - string userId = _httpContextAccessor.HttpContext!.User.FindFirst(ClaimTypes.NameIdentifier)!.Value; - return await _apiHttpClient.GetAsync($"auth/get-authorization?userId={Uri.EscapeDataString(userId.ToString())}", cancellationToken); + // anonymous users and users without an identifier claim have no role or permissions, so deny without querying the API + string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + if (string.IsNullOrEmpty(userId)) + return new GetAuthorizationResponse(Guid.Empty, string.Empty, []); + return await _apiHttpClient.GetAsync($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken); } } diff --git a/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs index 7a0481be..462ab82d 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Enums.Authorization; -using Lumina.Presentation.Web.Common.Models.Authorization; using System.Threading; using System.Threading.Tasks; #endregion @@ -27,19 +26,4 @@ public interface IAuthorizationService /// Cancellation token that can be used to stop the execution. /// if the currently logged in user is in the specified role, otherwise. Task IsInRoleAsync(string role, CancellationToken cancellationToken); - - /// - /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy. - /// - /// The type of authorization policy to evaluate. - /// Cancellation token that can be used to stop the execution. - /// if the currently logged in user satisfies the policy, otherwise. - Task EvaluatePolicyAsync(CancellationToken cancellationToken); - - /// - /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization requirement. - /// - /// The authorization requirements to check. - /// if the currently logged in user satisfies the requirement, otherwise. - Task EvaluateAuthorizationAsync(AuthorizationRequirementModel requirement); } diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationCheckPreProcessor.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationCheckPreProcessor.cs new file mode 100644 index 00000000..3e84c97d --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationCheckPreProcessor.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// FastEndpoints pre-processor that runs the application initialization check before the endpoint handler executes. +/// +/// +/// The check runs the RequireInitialization authorization policy, which queries the remote API and records the pending super admin setup state in the session. +/// Its result is deliberately ignored, because the pages that use this processor must be reachable both before and after the application is initialized. +/// +/// The type of the request of the endpoint to which this pre-processor is applied. +public class InitializationCheckPreProcessor : IPreProcessor where TRequest : notnull +{ + /// + /// Runs the initialization check for the current request. + /// + /// The pre-processor context for the current request. + /// Cancellation token that can be used to stop the execution. + public async Task PreProcessAsync(IPreProcessorContext preProcessorContext, CancellationToken cancellationToken) + { + HttpContext httpContext = preProcessorContext.HttpContext; + Microsoft.AspNetCore.Authorization.IAuthorizationService authorizationService = httpContext.RequestServices.GetRequiredService(); + await authorizationService.AuthorizeAsync(httpContext.User, httpContext, AuthorizationPolicies.REQUIRE_INITIALIZATION).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs index 51dd850c..02788de9 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/InitializationHandler.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Http; -using Lumina.Presentation.Web.Common.Models.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; @@ -28,17 +28,17 @@ public class InitializationHandler : AuthorizationHandler /// Checks the application initialization status and authorizes the requirement if initialized. /// - /// The authorization context. - /// The initialization requirement to be evaluated. - protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement) + /// The authorization context. + /// The initialization requirement to be evaluated. + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, InitializationRequirement initializationRequirement) { - InitializationModel result = await _apiHttpClient.GetAsync("initialization/").ConfigureAwait(false); - HttpContext? httpContext = context.Resource as HttpContext; + InitializationResponse result = await _apiHttpClient.GetAsync("initialization/").ConfigureAwait(false); + HttpContext? httpContext = authorizationHandlerContext.Resource as HttpContext; if (result.IsInitialized) { // admin account was registered, remove this requirement from the session httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); - context.Succeed(requirement); + authorizationHandlerContext.Succeed(initializationRequirement); } else // store in session that super admin setup is needed httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true"); diff --git a/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs new file mode 100644 index 00000000..ce4b912b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Microsoft.AspNetCore.Authorization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Handles the by checking the currently logged in user's permissions against the remote API. +/// +public class PermissionAuthorizationHandler : AuthorizationHandler +{ + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization checks against the remote API. + public PermissionAuthorizationHandler(IAuthorizationService authorizationService) + { + _authorizationService = authorizationService; + } + + /// + /// Succeeds the requirement when the currently logged in user holds any of the required permissions. + /// + /// The authorization context. + /// The permission requirement to evaluate. + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, PermissionRequirement permissionRequirement) + { + foreach (AuthorizationPermission permission in permissionRequirement.Permissions) + { + if (await _authorizationService.HasPermissionAsync(permission, CancellationToken.None).ConfigureAwait(false)) + { + authorizationHandlerContext.Succeed(permissionRequirement); + return; + } + } + } +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/PermissionRequirement.cs b/src/Lumina.Presentation.Web/Common/Authorization/PermissionRequirement.cs new file mode 100644 index 00000000..8eb80a9c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/PermissionRequirement.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Microsoft.AspNetCore.Authorization; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Defines a requirement that the user must hold at least one of the specified permissions. +/// +public class PermissionRequirement : IAuthorizationRequirement +{ + /// + /// Gets the permissions that allow access, of which the user must hold at least one. + /// + public AuthorizationPermission[] Permissions { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The permissions that allow access. + public PermissionRequirement(params AuthorizationPermission[] permissions) + { + Permissions = permissions; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/RoleAuthorizationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/RoleAuthorizationHandler.cs new file mode 100644 index 00000000..30657694 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/RoleAuthorizationHandler.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Handles the by checking the currently logged in user's role against the remote API. +/// +public class RoleAuthorizationHandler : AuthorizationHandler +{ + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization checks against the remote API. + public RoleAuthorizationHandler(IAuthorizationService authorizationService) + { + _authorizationService = authorizationService; + } + + /// + /// Succeeds the requirement when the currently logged in user belongs to any of the required roles. + /// + /// The authorization context. + /// The role requirement to evaluate. + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, RoleRequirement roleRequirement) + { + foreach (string role in roleRequirement.Roles) + { + if (await _authorizationService.IsInRoleAsync(role, CancellationToken.None).ConfigureAwait(false)) + { + authorizationHandlerContext.Succeed(roleRequirement); + return; + } + } + } +} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/RoleRequirement.cs b/src/Lumina.Presentation.Web/Common/Authorization/RoleRequirement.cs new file mode 100644 index 00000000..eb82ef3c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/RoleRequirement.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Defines a requirement that the user must belong to at least one of the specified roles. +/// +public class RoleRequirement : IAuthorizationRequirement +{ + /// + /// Gets the roles that allow access, of which the user must belong to at least one. + /// + public string[] Roles { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The roles that allow access. + public RoleRequirement(params string[] roles) + { + Roles = roles; + } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Authorization/PermissionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Authorization/PermissionDto.cs new file mode 100644 index 00000000..f2c78c77 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Authorization/PermissionDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Authorization; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Authorization; + +/// +/// Data transfer object for an authorization permission. +/// +/// The unique identifier of the permission. +/// The name of the permission. +[DebuggerDisplay("Id: {Id}, PermissionName: {PermissionName}")] +public record PermissionDto( + Guid Id, + AuthorizationPermission PermissionName +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Authorization/RoleDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Authorization/RoleDto.cs new file mode 100644 index 00000000..d815d97f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Authorization/RoleDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Authorization; + +/// +/// Data transfer object for an authorization role. +/// +/// The unique identifier of the role. +/// The name of the role. +[DebuggerDisplay("Id: {Id}, RoleName: {RoleName}")] +public record RoleDto( + Guid Id, + string RoleName +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Authorization/RolePermissionsDto.cs similarity index 55% rename from src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Authorization/RolePermissionsDto.cs index ac0496e4..218bbb79 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Authorization/RolePermissionsDto.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Authorization; +namespace Lumina.Presentation.Web.Common.DTO.Authorization; /// -/// Represents a model for an authorization role with its permissions. +/// Data transfer object for a model for an authorization role with its permissions. /// /// The authorization role. /// The permissions of the authorization role. -public record RolePermissionsModel( - RoleModel Role, - PermissionModel[] Permissions +[DebuggerDisplay("Role: {Role}")] +public record RolePermissionsDto( + RoleDto Role, + PermissionDto[] Permissions ); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/UserPermissionsModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Authorization/UserPermissionsDto.cs similarity index 50% rename from src/Lumina.Presentation.Web/Common/Models/Authorization/UserPermissionsModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Authorization/UserPermissionsDto.cs index 71f0e249..1dc5a417 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/UserPermissionsModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Authorization/UserPermissionsDto.cs @@ -1,15 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.UsersManagement; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Authorization; +namespace Lumina.Presentation.Web.Common.DTO.Authorization; /// -/// Represents a model for a user with its authorization permissions. +/// Data transfer object for a user with its authorization permissions. /// /// The user. /// The authorization permissions of the user. -public record UserPermissionsModel( - UserModel User, - PermissionModel[] Permissions +[DebuggerDisplay("User: {User}")] +public record UserPermissionsDto( + UserDto User, + PermissionDto[] Permissions ); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Common/ErrorViewDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/ErrorViewDto.cs new file mode 100644 index 00000000..2790c5b0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/ErrorViewDto.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; + +namespace Lumina.Presentation.Web.Common.DTO.Common; + +/// +/// Data transfer object for the data shown on the error page. +/// +[DebuggerDisplay("RequestId: {RequestId}, ShowRequestId: {ShowRequestId}")] +public class ErrorViewDto +{ + /// + /// Gets or sets the request identifier to display. + /// + public string? RequestId { get; set; } + + /// + /// Gets a value indicating whether the request identifier should be shown. + /// + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/GenreModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/GenreDto.cs similarity index 74% rename from src/Lumina.Presentation.Web/Common/Models/Common/GenreModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Common/GenreDto.cs index 720293c9..5bda54a8 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/GenreModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/GenreDto.cs @@ -2,16 +2,16 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.DTO.Common; /// -/// Represents a request to get genre information. +/// Data transfer object for a request to get genre information. /// [DebuggerDisplay("{Name}")] -public class GenreModel +public class GenreDto { /// /// Gets the name of the genre element of the media item. /// public string? Name { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/LanguageInfoModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/LanguageInfoDto.cs similarity index 81% rename from src/Lumina.Presentation.Web/Common/Models/Common/LanguageInfoModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Common/LanguageInfoDto.cs index b37f37fa..9d2689a4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/LanguageInfoModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/LanguageInfoDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.DTO.Common; /// -/// Represents a request to get language information. +/// Data transfer object for a request to get language information. /// [DebuggerDisplay("{LanguageName}")] -public class LanguageInfoModel +public class LanguageInfoDto { /// /// Gets the ISO 639-1 two-letter language code. @@ -24,4 +24,4 @@ public class LanguageInfoModel /// Gets an optional native name of the language. /// public string? NativeName { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/NotificationModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/NotificationDto.cs similarity index 71% rename from src/Lumina.Presentation.Web/Common/Models/Common/NotificationModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Common/NotificationDto.cs index 1540d60a..3131e6e3 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/NotificationModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/NotificationDto.cs @@ -1,17 +1,19 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Enums.Notifications; using System; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.DTO.Common; /// -/// Model for notifications. +/// Data transfer object for notifications. /// /// The id of the notification. /// The message of the notification. /// The type of the notification. -public record struct NotificationModel( +[DebuggerDisplay("Id: {Id}, Message: {Message}")] +public record struct NotificationDto( Guid Id, string Message, NotificationType Type diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/ProblemDetailsModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/ProblemDetailsDto.cs similarity index 80% rename from src/Lumina.Presentation.Web/Common/Models/Common/ProblemDetailsModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Common/ProblemDetailsDto.cs index 548d4d91..915399b4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/ProblemDetailsModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/ProblemDetailsDto.cs @@ -1,17 +1,17 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using System.Collections.Generic; using System.Diagnostics; using System.Text.Json; using System.Text.Json.Serialization; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.DTO.Common; /// -/// Model that follows the RFC 7807 standard for problem details in HTTP APIs. +/// Data transfer object that follows the RFC 7807 standard for problem details in HTTP APIs. /// [DebuggerDisplay("{Title} ({Status})")] -public class ProblemDetailsModel +public class ProblemDetailsDto { /// /// Gets or sets the URI reference that identifies the problem type. @@ -49,4 +49,4 @@ public class ProblemDetailsModel /// [JsonExtensionData] public IDictionary? Extensions { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/RatingModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/RatingDto.cs similarity index 77% rename from src/Lumina.Presentation.Web/Common/Models/Common/RatingModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Common/RatingDto.cs index f5058da3..a9202026 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/RatingModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/RatingDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.DTO.Common; /// -/// Represents a rating. +/// Data transfer object for a rating. /// -[DebuggerDisplay("{Value}/{MaxValue}")] -public abstract class RatingModel +[DebuggerDisplay("Value: {Value}, MaxValue: {MaxValue}")] +public abstract class RatingDto { /// /// Gets the numeric value of the rating. @@ -24,4 +24,4 @@ public abstract class RatingModel /// Gets the optional number of votes or reviews this rating is based on. /// public int? VoteCount { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/ReleaseInfoModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/ReleaseInfoDto.cs similarity index 85% rename from src/Lumina.Presentation.Web/Common/Models/Common/ReleaseInfoModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Common/ReleaseInfoDto.cs index 8aa2881d..9050347c 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/ReleaseInfoModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/ReleaseInfoDto.cs @@ -3,13 +3,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.DTO.Common; /// -/// Represents a request to get release information. +/// Data transfer object for a request to get release information. /// -[DebuggerDisplay("{OriginalReleaseDate}")] -public class ReleaseInfoModel +[DebuggerDisplay("OriginalReleaseDate: {OriginalReleaseDate}")] +public class ReleaseInfoDto { /// /// Gets the optional original release date of the media item. @@ -41,4 +41,4 @@ public class ReleaseInfoModel /// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0") /// public string? ReleaseVersion { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponse.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponse.cs new file mode 100644 index 00000000..b776c4e1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponse.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Common; + +/// +/// Response data transfer object for the JSON responses of the web application that do not carry a payload. +/// +/// Whether the operation succeeded or not. +public record SuccessResponse( + [property: JsonPropertyName("success")] bool Success +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponseOfT.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponseOfT.cs new file mode 100644 index 00000000..70e8e767 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponseOfT.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Common; + +/// +/// Response data transfer object for the JSON responses of the web application that carry a payload. +/// +/// The type of the payload of the response. +/// Whether the operation succeeded or not. +/// The payload of the response. +public record SuccessResponse( + [property: JsonPropertyName("success")] bool Success, + [property: JsonPropertyName("data")] TData? Data +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/TagModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/TagDto.cs similarity index 68% rename from src/Lumina.Presentation.Web/Common/Models/Common/TagModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Common/TagDto.cs index d4df4e14..ebb1b0f2 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/TagModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/TagDto.cs @@ -2,16 +2,16 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.DTO.Common; /// -/// Represents a request to get tag information. +/// Data transfer object for a request to get tag information. /// -[DebuggerDisplay("{Name}")] -public class TagModel +[DebuggerDisplay("Name: {Name}")] +public class TagDto { /// /// Gets the name of the tag element of the media item. /// public string? Name { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Configuration/EncryptionSettingsDto.cs similarity index 69% rename from src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Configuration/EncryptionSettingsDto.cs index 7f8ebbbf..50c288b1 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Configuration/EncryptionSettingsModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Configuration/EncryptionSettingsDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Configuration; +namespace Lumina.Presentation.Web.Common.DTO.Configuration; /// -/// Model for deserializing media settings. +/// Data transfer object for deserializing media settings. /// -[DebuggerDisplay("{SECTION_NAME}")] -public class EncryptionSettingsModel +[DebuggerDisplay("Section name: {SECTION_NAME}")] +public class EncryptionSettingsDto { public const string SECTION_NAME = "EncryptionSettings"; diff --git a/src/Lumina.Presentation.Web/Common/Models/Configuration/ServerConfigurationModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Configuration/ServerConfigurationDto.cs similarity index 76% rename from src/Lumina.Presentation.Web/Common/Models/Configuration/ServerConfigurationModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Configuration/ServerConfigurationDto.cs index 14810584..43dbc4f1 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Configuration/ServerConfigurationModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Configuration/ServerConfigurationDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Configuration; +namespace Lumina.Presentation.Web.Common.DTO.Configuration; /// -/// Model for deserializing server configuration settings. +/// Data transfer object for deserializing server configuration settings. /// -[DebuggerDisplay("{SECTION_NAME}")] -public class ServerConfigurationModel +[DebuggerDisplay("Section name: {SECTION_NAME}")] +public class ServerConfigurationDto { public const string SECTION_NAME = "ServerConfiguration"; diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/BlobDataModel.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/BlobDataDto.cs similarity index 52% rename from src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/BlobDataModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/BlobDataDto.cs index 2811b0b4..d88611f4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/BlobDataModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/BlobDataDto.cs @@ -1,14 +1,14 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; /// -/// Represents a model for storing binary data (blob). +/// Data transfer object for a model for storing binary data (blob). /// -[DebuggerDisplay("{ContentType} (Data.Length)")] -public class BlobDataModel +[DebuggerDisplay("ContentType: {ContentType} (Data.Length)")] +public class BlobDataDto { /// /// Gets or sets the binary data as a byte array. @@ -19,4 +19,4 @@ public class BlobDataModel /// Gets or sets the content type (MIME type) of the blob data, such as "image/png" for an image or "application/pdf" for a PDF document. /// public string ContentType { get; set; } = null!; -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/DirectoryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/DirectoryDto.cs new file mode 100644 index 00000000..831c2ccb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/DirectoryDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; + +/// +/// Data transfer object for directories displayed in custom directory/file browser dialogs. +/// +[DebuggerDisplay("Path: {Path}")] +public class DirectoryDto : FileSystemItemDto +{ + /// + /// Gets or sets the children items of the directory. + /// + public List Items { get; set; } = []; +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileDto.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileDto.cs new file mode 100644 index 00000000..690451ea --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; + +/// +/// Data transfer object for files displayed in custom directory/file browser dialogs. +/// +[DebuggerDisplay("Path: {Path}")] +public class FileDto : FileSystemItemDto +{ + /// + /// Gets or sets the size of the file, in bytes + /// + public long Size { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemItemModel.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemItemDto.cs similarity index 60% rename from src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemItemModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemItemDto.cs index 4b2d334f..e5cad9fd 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemItemModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemItemDto.cs @@ -1,15 +1,15 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; /// -/// Base model for files and directories displayed in custom directory/file browser dialogs. +/// Base data transfer object for files and directories displayed in custom directory/file browser dialogs. /// -[DebuggerDisplay("{Path}")] -public abstract class FileSystemItemModel +[DebuggerDisplay("Path: {Path}")] +public abstract class FileSystemItemDto { /// /// Gets or sets the full path to the file system item. @@ -30,4 +30,4 @@ public abstract class FileSystemItemModel /// Gets or sets the modification date of the file system item. /// public DateTime DateModified { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTreeNodeModel.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemTreeNodeDto.cs similarity index 70% rename from src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTreeNodeModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemTreeNodeDto.cs index fec72137..1188fda8 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTreeNodeModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemTreeNodeDto.cs @@ -1,16 +1,16 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Enums.FileSystem; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; /// -/// Generic file system node. +/// Data transfer object for a file system node. /// -[DebuggerDisplay("{Path}")] -public class FileSystemTreeNodeModel +[DebuggerDisplay("Path: {Path}")] +public class FileSystemTreeNodeDto { /// /// Gets or sets the full path of the file or directory. @@ -40,5 +40,5 @@ public class FileSystemTreeNodeModel /// /// Gets or sets the list of child nodes. /// - public List Children { get; set; } = []; -} \ No newline at end of file + public List Children { get; set; } = []; +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemTypeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemTypeDto.cs new file mode 100644 index 00000000..3f7e83b3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/FileSystemTypeDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; + +/// +/// Data transfer object containing the file system platform type. +/// ` +[DebuggerDisplay("PlatformType: {PlatformType}")] +public class FileSystemTypeDto +{ + /// + /// Gets or sets the file system platform type. + /// + public PlatformType PlatformType { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathExistsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathExistsDto.cs new file mode 100644 index 00000000..ed2d13da --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathExistsDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; + +/// +/// Data transfer object for a response to the inquiry about the existence of a file system path. +/// +/// Whether a file system path exists or not. +[DebuggerDisplay("Exists: {Exists}")] +public record PathExistsDto( + bool Exists +); diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSegmentModel.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathSegmentDto.cs similarity index 64% rename from src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSegmentModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathSegmentDto.cs index 82da26d3..12a5cdb9 100644 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSegmentModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathSegmentDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; /// -/// Represents a response containing a file system path. +/// Data transfer object for a response containing a file system path. /// -[DebuggerDisplay("{Path}")] -public class PathSegmentModel +[DebuggerDisplay("Path: {Path}")] +public class PathSegmentDto { /// /// Gets or sets the returned path. diff --git a/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathSeparatorDto.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathSeparatorDto.cs new file mode 100644 index 00000000..1db9134e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathSeparatorDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; + +/// +/// Data transfer object for a file system path separator. +/// +/// The system's path separator. +[DebuggerDisplay("Separator: {Separator}")] +public record PathSeparatorDto( + string Separator +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathValidDto.cs b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathValidDto.cs new file mode 100644 index 00000000..c29d4085 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/FileSystemManagement/PathValidDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement; + +/// +/// Data transfer object for a response to the inquiry about the validity of a file system path. +/// +/// Whether a file system path is valid or not. +[DebuggerDisplay("IsValid: {IsValid}")] +public record PathValidDto( + bool IsValid +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/BookLiteModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/BookLiteDto.cs similarity index 80% rename from src/Lumina.Presentation.Web/Common/Models/Libraries/BookLiteModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Libraries/BookLiteDto.cs index ee124a74..091bd10e 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/BookLiteModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/BookLiteDto.cs @@ -3,13 +3,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Libraries; +namespace Lumina.Presentation.Web.Common.DTO.Libraries; /// -/// Represents a lightweight book element, containing only the properties needed by the client for card-style navigation. +/// Data transfer object for a lightweight book element, containing only the properties needed by the client for card-style navigation. /// [DebuggerDisplay("Title: {Title}")] -public class BookLiteModel +public class BookLiteDto { /// /// Gets or sets the Id of the book. diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs similarity index 94% rename from src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs index e52dfb97..bc43dad9 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs @@ -5,13 +5,13 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Libraries; +namespace Lumina.Presentation.Web.Common.DTO.Libraries; /// -/// Represents a library element. +/// Data transfer object for a library element. /// -[DebuggerDisplay("{Title}")] -public class LibraryModel +[DebuggerDisplay("Title: {Title}")] +public class LibraryDto { /// /// Gets or sets the unique identifier of the media library. diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanJobProgressModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryScanJobProgressDto.cs similarity index 86% rename from src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanJobProgressModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryScanJobProgressDto.cs index b961d4d9..bdf38653 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanJobProgressModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryScanJobProgressDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Libraries; +namespace Lumina.Presentation.Web.Common.DTO.Libraries; /// -/// Represents a media library scan job progress model. +/// Data transfer object for a media library scan job progress model. /// [DebuggerDisplay("CompletedItems: {CompletedItems}; TotalItems: {TotalItems}")] -public class LibraryScanJobProgressModel +public class LibraryScanJobProgressDto { /// /// Gets or sets the number of completed items of the media library scan job. diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanProgressModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryScanProgressDto.cs similarity index 87% rename from src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanProgressModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryScanProgressDto.cs index d9a8462e..579a5cc4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanProgressModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryScanProgressDto.cs @@ -3,13 +3,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Libraries; +namespace Lumina.Presentation.Web.Common.DTO.Libraries; /// -/// Represents a media library scan progress model. +/// Data transfer object for a media library scan progress model. /// [DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}; LibraryId: {LibraryId}")] -public class LibraryScanProgressModel +public class LibraryScanProgressDto { /// /// Gets or sets the unique identifier of the media library scan. @@ -39,7 +39,7 @@ public class LibraryScanProgressModel /// /// Gets or sets the optional current job progress of the media library scan. /// - public LibraryScanJobProgressModel? CurrentJobProgress { get; set; } + public LibraryScanJobProgressDto? CurrentJobProgress { get; set; } /// /// Gets or sets the status of the media library scan. diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/PaginatedBookLiteModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/PaginatedBookLiteDto.cs similarity index 80% rename from src/Lumina.Presentation.Web/Common/Models/Libraries/PaginatedBookLiteModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Libraries/PaginatedBookLiteDto.cs index daed24fd..763276e0 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/PaginatedBookLiteModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/PaginatedBookLiteDto.cs @@ -3,18 +3,18 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Libraries; +namespace Lumina.Presentation.Web.Common.DTO.Libraries; /// -/// Represents a paginated collection of lightweight book elements, together with pagination metadata. +/// Data transfer object for a paginated collection of lightweight book elements, together with pagination metadata. /// [DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")] -public class PaginatedBookLiteModel +public class PaginatedBookLiteDto { /// /// Gets or sets the collection of lightweight book elements associated with this instance. /// - public IReadOnlyList Data { get; set; } = []; + public IReadOnlyList Data { get; set; } = []; /// /// Gets or sets the current page number in a paginated collection. diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/ScanLibraryModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/ScanLibraryDto.cs similarity index 80% rename from src/Lumina.Presentation.Web/Common/Models/Libraries/ScanLibraryModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Libraries/ScanLibraryDto.cs index eadddf2d..2f99ef7b 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/ScanLibraryModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/ScanLibraryDto.cs @@ -3,13 +3,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Libraries; +namespace Lumina.Presentation.Web.Common.DTO.Libraries; /// -/// Represents a media library scan response. +/// Data transfer object for a media library scan response. /// [DebuggerDisplay("ScanId: {ScanId} LibraryId: {LibraryId}")] -public class ScanLibraryModel +public class ScanLibraryDto { /// /// Gets or sets the Id of the media library scan. diff --git a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs similarity index 58% rename from src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs index c1e3a418..97587776 100644 --- a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs @@ -2,21 +2,21 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.MediaContributors; +namespace Lumina.Presentation.Web.Common.DTO.MediaContributors; /// -/// Represents a media contributor. +/// Data transfer object for a media contributor. /// -[DebuggerDisplay("{Name}")] -public class MediaContributorModel +[DebuggerDisplay("Name: {Name}")] +public class MediaContributorDto { /// /// Gets the name of the contributor. /// - public MediaContributorNameModel? Name { get; set; } + public MediaContributorNameDto? Name { get; set; } /// /// Gets the role of the contributor. /// - public MediaContributorRoleModel? Role { get; set; } + public MediaContributorRoleDto? Role { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorNameModel.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorNameDto.cs similarity index 71% rename from src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorNameModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorNameDto.cs index 37b211c4..23831e71 100644 --- a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorNameModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorNameDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.MediaContributors; +namespace Lumina.Presentation.Web.Common.DTO.MediaContributors; /// -/// Represents a media contributor name. +/// Data transfer object for a media contributor name. /// -[DebuggerDisplay("{DisplayName}")] -public class MediaContributorNameModel +[DebuggerDisplay("DisplayName: {DisplayName}")] +public class MediaContributorNameDto { /// /// Gets the name by which the contributor is popularly known. @@ -19,4 +19,4 @@ public class MediaContributorNameModel /// Gets the legal name of the contributor. /// public string? LegalName { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorRoleModel.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorRoleDto.cs similarity index 71% rename from src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorRoleModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorRoleDto.cs index a735b674..74eaf370 100644 --- a/src/Lumina.Presentation.Web/Common/Models/MediaContributors/MediaContributorRoleModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorRoleDto.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.MediaContributors; +namespace Lumina.Presentation.Web.Common.DTO.MediaContributors; /// -/// Represents a media contributor role. +/// Data transfer object for a media contributor role. /// -[DebuggerDisplay("{Name}")] -public class MediaContributorRoleModel +[DebuggerDisplay("Name: {Name}")] +public class MediaContributorRoleDto { /// /// Gets the value representing this object. @@ -19,4 +19,4 @@ public class MediaContributorRoleModel /// Gets the category of this object. /// public string? Category { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Plugins/LibraryMetadataProviderModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Plugins/LibraryMetadataProviderDto.cs similarity index 84% rename from src/Lumina.Presentation.Web/Common/Models/Plugins/LibraryMetadataProviderModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Plugins/LibraryMetadataProviderDto.cs index 04f5e442..787e8562 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Plugins/LibraryMetadataProviderModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Plugins/LibraryMetadataProviderDto.cs @@ -3,13 +3,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Plugins; +namespace Lumina.Presentation.Web.Common.DTO.Plugins; /// -/// Represents a metadata provider configured for a media library. +/// Data transfer object for a metadata provider configured for a media library. /// [DebuggerDisplay("Name: {Name}")] -public class LibraryMetadataProviderModel +public class LibraryMetadataProviderDto { /// /// Gets or sets the unique identifier of the plugin providing the metadata. diff --git a/src/Lumina.Presentation.Web/Common/Models/Plugins/PluginModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginDto.cs similarity index 92% rename from src/Lumina.Presentation.Web/Common/Models/Plugins/PluginModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginDto.cs index 3b1bbbfa..9c67faae 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Plugins/PluginModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginDto.cs @@ -5,13 +5,13 @@ using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Plugins; +namespace Lumina.Presentation.Web.Common.DTO.Plugins; /// -/// Represents a detected plugin. +/// Data transfer object for a detected plugin. /// [DebuggerDisplay("Name: {Name}")] -public class PluginModel +public class PluginDto { /// /// Gets or sets the unique identifier of the plugin. diff --git a/src/Lumina.Presentation.Web/Common/Models/Plugins/PluginSettingDescriptorModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginSettingDescriptorDto.cs similarity index 82% rename from src/Lumina.Presentation.Web/Common/Models/Plugins/PluginSettingDescriptorModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginSettingDescriptorDto.cs index 3bc6a917..a5e4c206 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Plugins/PluginSettingDescriptorModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginSettingDescriptorDto.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Enums.Plugins; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Plugins; +namespace Lumina.Presentation.Web.Common.DTO.Plugins; /// -/// Describes a single setting of a plugin. +/// Data transfer object for a single setting of a plugin. /// -public class PluginSettingDescriptorModel +[DebuggerDisplay("Key: {Key}, Label: {Label}")] +public class PluginSettingDescriptorDto { /// /// Gets or sets the unique key of the setting. diff --git a/src/Lumina.Presentation.Web/Common/Models/Plugins/PluginSettingsModel.cs b/src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginSettingsDto.cs similarity index 69% rename from src/Lumina.Presentation.Web/Common/Models/Plugins/PluginSettingsModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginSettingsDto.cs index ac6ea9ad..75fd0900 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Plugins/PluginSettingsModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Plugins/PluginSettingsDto.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using System; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Plugins; +namespace Lumina.Presentation.Web.Common.DTO.Plugins; /// -/// Represents the settings of a plugin and their schema. +/// Data transfer object for the settings of a plugin and their schema. /// -public class PluginSettingsModel +[DebuggerDisplay("PluginId: {PluginId}")] +public class PluginSettingsDto { /// /// Gets or sets the unique identifier of the plugin. @@ -18,7 +20,7 @@ public class PluginSettingsModel /// /// Gets or sets the schema of the plugin settings. /// - public List Schema { get; set; } = []; + public List Schema { get; set; } = []; /// /// Gets or sets the current values of the plugin settings. diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserModel.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserDto.cs similarity index 66% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserDto.cs index bee24edf..4a2abdd0 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserDto.cs @@ -1,15 +1,17 @@ #region ========================================================================= USING ===================================================================================== using System; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.DTO.UsersManagement; /// -/// Represents a model for a user. +/// Data transfer object for a user. /// /// The unique identifier of the user. /// The username of the user. -public record UserModel( +[DebuggerDisplay("Id: {Id}, Username: {Username}")] +public record UserDto( Guid Id, string Username ); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserSettingsModel.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs similarity index 88% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserSettingsModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index e72cc0d8..ad009888 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/UserSettingsModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -3,13 +3,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.DTO.UsersManagement; /// -/// Represents the settings of a user. +/// Data transfer object for the settings of a user. /// [DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] -public class UserSettingsModel +public class UserSettingsDto { /// /// Gets or sets the unique identifier of the user that owns these settings. diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookModel.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs similarity index 93% rename from src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs index d5780444..b746cff9 100644 --- a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs @@ -1,17 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.Common; +using Lumina.Presentation.Web.Common.DTO.Common; using System; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Represents a book. +/// Data transfer object for a book. /// -[DebuggerDisplay("{Title}")] -public class BookModel +[DebuggerDisplay("Title: {Title}")] +public class BookDto { /// /// Gets the Id of the media item. @@ -107,12 +107,12 @@ public class BookModel /// /// Gets the list of tags associated with the media item. /// - public HashSet Tags { get; set; } = []; + public HashSet Tags { get; set; } = []; /// /// Gets the list of genres associated with the media item. /// - public HashSet Genres { get; set; } = []; + public HashSet Genres { get; set; } = []; /// /// Gets the publisher of the written content. @@ -192,7 +192,7 @@ public class BookModel /// /// Gets the list of ISBN (International Standard Book Number) of the book. /// - public List ISBNs { get; set; } = []; + public List ISBNs { get; set; } = []; /// /// Gets the list of media contributors (actors, directors, etc) starring in this book. @@ -202,7 +202,7 @@ public class BookModel /// /// Gets the list of ratings for this book. /// - public List Ratings { get; init; } = []; + public List Ratings { get; init; } = []; /// /// Gets the time and date when the entity was added. @@ -213,4 +213,4 @@ public class BookModel /// Gets the optional time and date when the entity was updated. /// public DateTime? Updated { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookRatingModel.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDto.cs similarity index 63% rename from src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookRatingModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDto.cs index 3370d93a..488dfa33 100644 --- a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookRatingModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookRatingDto.cs @@ -1,19 +1,19 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Enums.BookLibrary; -using Lumina.Presentation.Web.Common.Models.Common; using System.Diagnostics; +using Lumina.Presentation.Web.Common.DTO.Common; #endregion -namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Represents a book rating. +/// Data transfer object for a book rating. /// -[DebuggerDisplay("{Value}/{MaxValue}")] -public class BookRatingModel : RatingModel +[DebuggerDisplay("Value: {Value}, MaxValue: {MaxValue}")] +public class BookRatingDto : RatingDto { /// /// Gets or sets the source of the book rating (e.g., a specific website or platform). /// public BookRatingSource? Source { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDto.cs similarity index 63% rename from src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDto.cs index ef9ba60c..70d36931 100644 --- a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BookSeriesModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookSeriesDto.cs @@ -2,16 +2,16 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Represents a request to get book series information. +/// Data transfer object for a request to get book series information. /// -[DebuggerDisplay("{Title}")] -public class BookSeriesModel +[DebuggerDisplay("Title: {Title}")] +public class BookSeriesDto { /// /// Gets or sets the title of the book series. /// public string? Title { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/IsbnModel.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDto.cs similarity index 72% rename from src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/IsbnModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDto.cs index f0defca0..8df5e093 100644 --- a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/IsbnModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/IsbnDto.cs @@ -3,13 +3,13 @@ using Lumina.Presentation.Web.Common.Enums.BookLibrary; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Represents a request to get ISBN information. +/// Data transfer object for a request to get ISBN information. /// -[DebuggerDisplay("{Value} ({Format})")] -public class IsbnModel +[DebuggerDisplay("Value: {Value} ({Format})")] +public class IsbnDto { /// /// Gets or sets the ISBN value. @@ -20,4 +20,4 @@ public class IsbnModel /// Gets or sets the format of the ISBN (e.g., ISBN-10 or ISBN-13). /// public IsbnFormat? Format { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/LightBookModel.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/LightBookDto.cs similarity index 80% rename from src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/LightBookModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/LightBookDto.cs index 0da7e882..047a8dd4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/LightBookModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/LightBookDto.cs @@ -3,13 +3,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; /// -/// Represents a preview of important properties of a book. +/// Data transfer object for a preview of important properties of a book. /// -[DebuggerDisplay("{Title}")] -public class LightBookModel +[DebuggerDisplay("Title: {Title}")] +public class LightBookDto { /// /// Gets the Id of the media item. diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/WrittenContentMetadataModel.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDto.cs similarity index 76% rename from src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/WrittenContentMetadataModel.cs rename to src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDto.cs index 36e33e09..49ebd592 100644 --- a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/WrittenContentMetadataModel.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/WrittenContentMetadataDto.cs @@ -1,16 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.Common; +using Lumina.Presentation.Web.Common.DTO.Common; using System.Collections.Generic; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary; +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; /// -/// Represents written content metadata. +/// Data transfer object for written content metadata. /// -[DebuggerDisplay("{Title}")] -public class WrittenContentMetadataModel +[DebuggerDisplay("Title: {Title}")] +public class WrittenContentMetadataDto { /// /// Gets or sets the title of the written content. @@ -30,27 +30,27 @@ public class WrittenContentMetadataModel /// /// Gets or sets the release information, including release date and other relevant details. /// - public ReleaseInfoModel? ReleaseInfo { get; set; } + public ReleaseInfoDto? ReleaseInfo { get; set; } /// /// Gets or sets the list of genres associated with the written content. /// - public List? Genres { get; set; } + public List? Genres { get; set; } /// /// Gets or sets the list of tags that further describe or categorize the written content. /// - public List? Tags { get; set; } + public List? Tags { get; set; } /// /// Gets or sets the language in which the written content is written. /// - public LanguageInfoModel? Language { get; set; } + public LanguageInfoDto? Language { get; set; } /// /// Gets or sets the original language of the written content, if it has been translated. /// - public LanguageInfoModel? OriginalLanguage { get; set; } + public LanguageInfoDto? OriginalLanguage { get; set; } /// /// Gets or sets the name of the publisher of the written content. @@ -61,4 +61,4 @@ public class WrittenContentMetadataModel /// Gets or sets the number of pages in the written content. /// public int? PageCount { get; set; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs index d0dc667e..8bea5b86 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.Configuration; +using Lumina.Presentation.Web.Common.DTO.Configuration; using Lumina.Presentation.Web.Common.Utilities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -26,13 +26,13 @@ internal static class PresentationWebLayerConfiguration configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true); - serviceCollection.AddOptions() - .Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME)) + serviceCollection.AddOptions() + .Bind(configuration.GetRequiredSection(ServerConfigurationDto.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); - serviceCollection.AddOptions() - .Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME)) + serviceCollection.AddOptions() + .Bind(configuration.GetRequiredSection(EncryptionSettingsDto.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 1264f93d..b2f52ee7 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FastEndpoints.Swagger; using FluentValidation; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Common.Exceptions; -using Lumina.Presentation.Web.Common.Filters.ActionFilters; -using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters; using Lumina.Presentation.Web.Common.Http; -using Lumina.Presentation.Web.Common.MiddlewareFilters; -using Lumina.Presentation.Web.Common.Models.Authorization; +using Lumina.Presentation.Web.Common.Localization; using Lumina.Presentation.Web.Common.Security; using Lumina.Presentation.Web.Common.Services; using Microsoft.AspNetCore.Authentication.Cookies; @@ -18,6 +18,7 @@ using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization.Routing; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.DependencyInjection; using Polly; @@ -49,11 +50,7 @@ public static class PresentationWebLayerServices /// The updated . public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) { - services.AddControllersWithViews(mvcOptions => - { - mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter - mvcOptions.Filters.Add(); - }) + services.AddControllersWithViews() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization() .AddJsonOptions(jsonOptions => @@ -62,11 +59,50 @@ public static class PresentationWebLayerServices jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); + + // configure the locations where the Razor view engine looks for views and layouts, since the views live under the Core directory + services.Configure(razorViewEngineOptions => + { + razorViewEngineOptions.ViewLocationFormats.Clear(); + razorViewEngineOptions.ViewLocationFormats.Add("/Core/Views/{1}/{0}.cshtml"); + razorViewEngineOptions.ViewLocationFormats.Add("/Core/Views/Shared/{0}.cshtml"); + }); + + // configure the JSON serialization settings used by Results.Json, so that the JSON responses of the endpoints match the MVC responses they replace + services.Configure(jsonOptions => + { + jsonOptions.SerializerOptions.MaxDepth = 256; + jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); + + // register the FastEndpoints library, which replaces the MVC controllers for handling the application routes + services.AddFastEndpoints(); + // add OpenAPI document generation, so that the endpoints exposed by the web application are discoverable and their contracts are visible + services.AddOpenApi(); + services.SwaggerDocument(documentOptions => + { + documentOptions.SerializerSettings = jsonSerializerOptions => + { + jsonSerializerOptions.PropertyNamingPolicy = null; + jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + }; + documentOptions.DocumentSettings = aspNetCoreOpenApiDocumentGeneratorSettings => + { + aspNetCoreOpenApiDocumentGeneratorSettings.DocumentName = "v1"; + aspNetCoreOpenApiDocumentGeneratorSettings.Title = "Lumina Web"; + aspNetCoreOpenApiDocumentGeneratorSettings.Version = "v1"; + }; + documentOptions.RemoveEmptyRequestSchema = true; + documentOptions.ShortSchemaNames = true; + }); // configure URL-based localization services.AddLocalization(localizationOptions => { - localizationOptions.ResourcesPath = "Resources"; + localizationOptions.ResourcesPath = "Core/Resources"; }); + // resolve the resources of the views that live under the Core/Views directory + services.AddSingleton(); services.Configure(requestLocalizationOptions => { @@ -190,9 +226,20 @@ public static class PresentationWebLayerServices }; }); - // add an authorization policy that ensures application is initialized with super admin account before allowing access + // add authorization policies that ensure the application is initialized with the super admin account before allowing access, + // and that restrict access based on the roles and permissions retrieved from the remote API services.AddAuthorizationBuilder() - .AddPolicy("RequireInitialization", authorizationPolicyBuilder => authorizationPolicyBuilder.Requirements.Add(new InitializationRequirement())); + .AddPolicy(AuthorizationPolicies.REQUIRE_INITIALIZATION, authorizationPolicyBuilder => authorizationPolicyBuilder.Requirements.Add(new InitializationRequirement())) + .AddPolicy(AuthorizationPolicies.REQUIRE_ADMIN_ROLE, authorizationPolicyBuilder => + { + authorizationPolicyBuilder.Requirements.Add(new RoleRequirement("Admin")); + authorizationPolicyBuilder.RequireAuthenticatedUser(); + }) + .AddPolicy(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION, authorizationPolicyBuilder => + { + authorizationPolicyBuilder.Requirements.Add(new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)); + authorizationPolicyBuilder.RequireAuthenticatedUser(); + }); // add forwarded headers middleware to handle reverse proxy scenarios services.Configure(forwardedHeadersOptions => @@ -237,13 +284,13 @@ public static class PresentationWebLayerServices .AddPolicyHandler(circuitBreakerPolicy); services.AddScoped(); - services.AddScoped(); - services.AddScoped(); // enable access to the current HTTP context in non-controller classes services.AddHttpContextAccessor(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs b/src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs index 5557f482..95c75ae9 100644 --- a/src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs +++ b/src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.Common; +using Lumina.Presentation.Web.Common.DTO.Common; using System; using System.Net; #endregion @@ -19,7 +19,7 @@ public class ApiException : Exception /// /// Gets or sets the problem details represented by this exception. /// - public ProblemDetailsModel? ProblemDetails { get; } + public ProblemDetailsDto? ProblemDetails { get; } /// /// Gets or sets the absolute path of the API endpoint that produced this exception. @@ -32,7 +32,7 @@ public class ApiException : Exception /// The problem details object returned by the API. /// The HTTP status code returned by the API. /// The absolute path of the API endpoint that produced this exception. - public ApiException(ProblemDetailsModel? problemDetails, HttpStatusCode httpStatusCode, string? requestPath = null) : base(problemDetails?.Title ?? "An error occurred.") + public ApiException(ProblemDetailsDto? problemDetails, HttpStatusCode httpStatusCode, string? requestPath = null) : base(problemDetails?.Title ?? "An error occurred.") { ProblemDetails = problemDetails; HttpStatusCode = httpStatusCode; diff --git a/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/InitializationCheckAttribute.cs b/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/InitializationCheckAttribute.cs deleted file mode 100644 index d19083da..00000000 --- a/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/InitializationCheckAttribute.cs +++ /dev/null @@ -1,26 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.DependencyInjection; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Common.Filters.ActionFilters; - -/// -/// Attribute that enforces application initialization checks on controller actions. -/// -public class InitializationCheckAttribute : ActionFilterAttribute -{ - /// - /// Asynchronously executes the initialization check before the action executes. - /// - /// The context for the action being executed. - /// Delegate to execute the next action filter in the pipeline. - public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { - IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService(); - await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization").ConfigureAwait(false); - await next().ConfigureAwait(false); - } -} diff --git a/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/StoreLastViewFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/StoreLastViewFilter.cs deleted file mode 100644 index 0f4bb8a0..00000000 --- a/src/Lumina.Presentation.Web/Common/Filters/ActionFilters/StoreLastViewFilter.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Http; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -#endregion - -namespace Lumina.Presentation.Web.Common.Filters.ActionFilters; - -/// -/// Stores the current view path in session, for actions that return ViewResult. This is needed because when JWT expires, user is redirected to Login view, with a returnUrl. -/// This returnUrl needs to be that of the last displayed view, not of the call that triggered the re-authentication request, which can be an API call for data. -/// -public class StoreLastViewFilter : IActionFilter -{ - /// - /// Executes before the action method is called. - /// - /// The action executing context. - public void OnActionExecuting(ActionExecutingContext context) - { - // no action needed before execution - } - - /// - /// Executes after the action method is called. - /// - /// The action executed context containing the action result. - public void OnActionExecuted(ActionExecutedContext context) - { - if (context.Result is ViewResult) - { - HttpContext httpContext = context.HttpContext; - // ignore the login endpoint, because it is incorrect to be redirected to the login URL, with the login URL as the return URL - if (httpContext.Request.Path != "/en-us/auth/login") - httpContext.Session.SetString(HttpContextItemKeys.LAST_DISPLAYED_VIEW, $"{httpContext.Request.PathBase}{httpContext.Request.Path}{httpContext.Request.QueryString}"); - } - } -} diff --git a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs deleted file mode 100644 index 0375fb54..00000000 --- a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Authorization; -using Lumina.Presentation.Web.Common.Exceptions; -using Lumina.Presentation.Web.Common.Models.Authorization; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Common.Filters.AuthorizationFilters; - -/// -/// Implements authorization filter logic for API endpoints by validating user roles, permissions, and policies. -/// -public class ApiAuthorizationFilter : IAsyncAuthorizationFilter -{ - private readonly IAuthorizationService _authorizationService; - private readonly AuthorizationRequirementModel _requirement; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - /// Authorization requirements to evaluate. - public ApiAuthorizationFilter(IAuthorizationService authorizationService, AuthorizationRequirementModel requirement) - { - _authorizationService = authorizationService; - _requirement = requirement; - } - - /// - /// Performs authorization for the current request. - /// - /// The authorization filter context. - public async Task OnAuthorizationAsync(AuthorizationFilterContext context) - { - try - { - if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement)) - context.Result = new ForbidResult(); - } - catch (ApiException ex) // TODO: check if it should really catch exceptions here - { - if (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized) - { - await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false); - context.HttpContext.Response.Cookies.Delete("Token"); - throw; - } - } - } -} diff --git a/src/Lumina.Presentation.Web/Common/Filters/TypeFilters/ApiAuthorizationAttribute.cs b/src/Lumina.Presentation.Web/Common/Filters/TypeFilters/ApiAuthorizationAttribute.cs deleted file mode 100644 index 6d9838a6..00000000 --- a/src/Lumina.Presentation.Web/Common/Filters/TypeFilters/ApiAuthorizationAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters; -using Microsoft.AspNetCore.Mvc; -using System; -#endregion - -namespace Lumina.Presentation.Web.Common.Filters.TypeFilters; - -/// -/// Authorization filter for API endpoints. -/// -/// -/// This attribute can be applied to both classes and methods and supports multiple instances on the same target. -/// -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] -public class ApiAuthorizationAttribute : TypeFilterAttribute -{ - /// - /// Initializes a new instance of the class. - /// - public ApiAuthorizationAttribute() : base(typeof(ApiAuthorizationFilter)) - { - } -} diff --git a/src/Lumina.Presentation.Web/Common/Http/RazorViewResult.cs b/src/Lumina.Presentation.Web/Common/Http/RazorViewResult.cs new file mode 100644 index 00000000..cdb5bd98 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Http/RazorViewResult.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Http; + +/// +/// that renders a Razor view through the MVC view engine, enabling FastEndpoints endpoints to serve the Razor views of the application. +/// +/// +/// The class does not expose a method for rendering Razor views, so this custom result reuses the MVC +/// execution machinery, which preserves layouts, sections, view components and tag helpers. +/// +public sealed class RazorViewResult : IResult +{ + private readonly string _viewName; + private readonly object? _model; + private readonly IReadOnlyDictionary _viewData; + + /// + /// Initializes a new instance of the class. + /// + /// The name or path of the view to render. + /// The model to pass to the view. + /// Optional additional view data entries made available to the view via ViewData. + public RazorViewResult(string viewName, object? model = null, IReadOnlyDictionary? viewData = null) + { + _viewName = viewName; + _model = model; + _viewData = viewData ?? new Dictionary(); + } + + /// + /// Renders the configured Razor view to the response. + /// + /// The for the current request. + public async Task ExecuteAsync(HttpContext httpContext) + { + // the only accessible ViewDataDictionary constructors require either a model state or an existing dictionary, so start from an empty one and assign the model + // through the Model setter; the setter rebases the model metadata on the runtime type of the value, which is what makes the asp-for tag helpers resolve the + // properties of the actual model type instead of a plain object + IModelMetadataProvider metadataProvider = httpContext.RequestServices.GetRequiredService(); + ViewDataDictionary viewData = new(metadataProvider, new ModelStateDictionary()) { Model = _model }; + foreach ((string key, object? value) in _viewData) + viewData[key] = value; + + // delegate to the MVC view execution machinery instead of rendering the view manually: it discovers the layout and _ViewStart, evaluates the sections, + // and resolves the view components and tag helpers, none of which the Results class can do since it has no view rendering support + ViewResult viewResult = new() { ViewName = _viewName, ViewData = viewData }; + IActionResultExecutor executor = httpContext.RequestServices.GetRequiredService>(); + // the view engine needs an ActionContext, which FastEndpoints does not provide; synthesize one that carries over the current route data, so that the + // culture route value (and therefore the URL-based localization) keeps working while the view is rendered + ActionContext actionContext = new(httpContext, httpContext.GetRouteData() ?? new RouteData(), new ActionDescriptor()); + await executor.ExecuteAsync(actionContext, viewResult).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Localization/CoreHtmlLocalizerFactory.cs b/src/Lumina.Presentation.Web/Common/Localization/CoreHtmlLocalizerFactory.cs new file mode 100644 index 00000000..f560d7b5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Localization/CoreHtmlLocalizerFactory.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Mvc.Localization; +using Microsoft.Extensions.Localization; +using System; +#endregion + +namespace Lumina.Presentation.Web.Common.Localization; + +/// +/// that resolves the resources of the views that live under the Core/Views directory. +/// +/// +/// The view localizer derives the resource base name from the executing view path, so a view at /Core/Views/Auth/Login.cshtml produces the base name +/// {ApplicationName}.Core.Views.Auth.Login. Because the Core segment is only the directory that hosts the views and not part of the resource path, +/// it is stripped here, so that the resources are looked up at {ApplicationName}.Core.Resources.Views.Auth.Login, matching the resource files under +/// Core/Resources/Views/Auth. +/// +public class CoreHtmlLocalizerFactory : IHtmlLocalizerFactory +{ + private readonly HtmlLocalizerFactory _innerFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory used to create the underlying string localizers. + public CoreHtmlLocalizerFactory(IStringLocalizerFactory stringLocalizerFactory) + { + _innerFactory = new HtmlLocalizerFactory(stringLocalizerFactory); + } + + /// + /// Creates an for the specified base name and location. + /// + /// The base name of the resource to load strings from. + /// The location to load resources from. + /// The created . + public IHtmlLocalizer Create(string baseName, string location) + { + string prefix = location + ".Core."; + string resourceBaseName = baseName.StartsWith(prefix, StringComparison.Ordinal) + ? location + "." + baseName.Substring(prefix.Length) + : baseName; + return _innerFactory.Create(resourceBaseName, location); + } + + /// + /// Creates an for the specified resource source type. + /// + /// The type of the resource to load strings from. + /// The created . + public IHtmlLocalizer Create(Type resourceSource) + { + return _innerFactory.Create(resourceSource); + } +} diff --git a/src/Lumina.Presentation.Web/Common/MiddlewareFilters/LocalizationPipeline.cs b/src/Lumina.Presentation.Web/Common/MiddlewareFilters/LocalizationPipeline.cs deleted file mode 100644 index a10a2dfb..00000000 --- a/src/Lumina.Presentation.Web/Common/MiddlewareFilters/LocalizationPipeline.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Localization; -using Microsoft.Extensions.Options; -#endregion - -namespace Lumina.Presentation.Web.Common.MiddlewareFilters; - -/// -/// Defines a pipeline for configuring middleware to handle localization. -/// -/// -/// To use a MiddlewareFilter, you first need to create a pipeline. This acts as a mini startup configuration where you define an -/// to specify the middleware that should run as part of the pipeline. Multiple middleware can be configured in this way. -/// -public class LocalizationPipeline -{ - /// - /// Configures the middleware pipeline to include the for handling localization. - /// - /// The used to configure the middleware pipeline. - /// The instance for , containing localization settings to be applied. - public void Configure(IApplicationBuilder app, IOptions options) - { - // runs the RequestLocalizationMiddleware with the provided options - app.UseRequestLocalization(options.Value); - } -} diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationRequirementModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationRequirementModel.cs deleted file mode 100644 index 139981e2..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationRequirementModel.cs +++ /dev/null @@ -1,27 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Authorization; -using System; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.Authorization; - -/// -/// Model for storing the authorization requirements for accessing a resource. -/// -public class AuthorizationRequirementModel -{ - /// - /// The collection of roles required for accessing the resource. - /// - public string[]? Roles { get; set; } - - /// - /// The collection of permissions required for accessing the resource. - /// - public AuthorizationPermission[]? Permissions { get; set; } - - /// - /// The type of the policy required for accessing the resource. - /// - public Type? PolicyType { get; set; } -} diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs deleted file mode 100644 index 7ace0b3d..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Authorization; -using System; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.Authorization; - -/// -/// Represents a model for an authorization permission. -/// -/// The unique identifier of the authorization permission. -/// The authorization permission. -public record PermissionModel( - Guid Id, - AuthorizationPermission PermissionName -); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs deleted file mode 100644 index bc1a3ac4..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.Authorization; - -/// -/// Represents a model for an authorization role. -/// -/// The unique identifier of the authorization role. -/// The authorization role. -public record RoleModel( - Guid Id, - string RoleName -); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs deleted file mode 100644 index f70a2f1f..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.Authorization; - -/// -/// Represents the request model for updating an existing authorization role. -/// -/// The unique identifier of the role. -/// The name of the role. -/// The collection of Ids of the permissions of the role. -public record UpdateRoleRequestModel( - Guid RoleId, - string? RoleName, - List? Permissions -); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs deleted file mode 100644 index a76ce7aa..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.Authorization; - -/// -/// Represents the request model for updating the authorization role and permissions of a user. -/// -/// The unique identifier of the user. -/// The unique identifier of the role. -/// The collection of Ids of the permissions of the user. -public record UpdateUserRoleAndPermissionsRequestModel( - Guid UserId, - Guid? RoleId, - List? Permissions -); diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/EmptyModel.cs b/src/Lumina.Presentation.Web/Common/Models/Common/EmptyModel.cs deleted file mode 100644 index 3bd1ef69..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/Common/EmptyModel.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Lumina.Presentation.Web.Common.Models.Common; - -/// -/// Record used for empty requests and responses. -/// -public record struct EmptyModel(); diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/DirectoryModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/DirectoryModel.cs deleted file mode 100644 index a5cacc18..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/DirectoryModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; - -/// -/// Model for directories displayed in custom directory/file browser dialogs. -/// -[DebuggerDisplay("{Path}")] -public class DirectoryModel : FileSystemItemModel -{ - /// - /// Gets or sets the children items of the directory. - /// - public List Items { get; set; } = []; -} diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileModel.cs deleted file mode 100644 index ff4fa39f..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileModel.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; - -/// -/// Model for files displayed in custom directory/file browser dialogs. -/// -[DebuggerDisplay("{Path}")] -public class FileModel : FileSystemItemModel -{ - /// - /// Gets or sets the size of the file, in bytes - /// - public long Size { get; set; } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTypeModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTypeModel.cs deleted file mode 100644 index 21794b67..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/FileSystemTypeModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.FileSystem; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; - -/// -/// Model containing the file system platform type. -/// ` -[DebuggerDisplay("{PlatformType}")] -public class FileSystemTypeModel -{ - /// - /// Gets or sets the file system platform type. - /// - public PlatformType PlatformType { get; set; } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathExistsModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathExistsModel.cs deleted file mode 100644 index 5eb3caee..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathExistsModel.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; - -/// -/// Represents a response to the inquiry about the existence of a file system path. -/// -/// Whether a file system path exists or not. -[DebuggerDisplay("{Exists}")] -public record PathExistsModel( - bool Exists -); \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSeparatorModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSeparatorModel.cs deleted file mode 100644 index d778bea0..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathSeparatorModel.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; - -/// -/// A model representing a file system path separator. -/// -/// The system's path separator. -[DebuggerDisplay("{Separator}")] -public record PathSeparatorModel( - string Separator -); \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathValidModel.cs b/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathValidModel.cs deleted file mode 100644 index 1954f357..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/FileSystemManagement/PathValidModel.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.FileSystemManagement; - -/// -/// Represents a response to the inquiry about the validity of a file system path. -/// -/// Whether a file system path is valid or not. -[DebuggerDisplay("{IsValid}")] -public record PathValidModel( - bool IsValid -); \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs deleted file mode 100644 index 85b51598..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordRequestModel.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; - -/// -/// Represents the request model for account password change. -/// -/// The username of the account. -/// The current password of the account. -/// The new password of the account. -/// The confirmation of the new password of the account. -public record ChangePasswordRequestModel( - string? Username, - string? CurrentPassword, - string? NewPassword, - string? NewPasswordConfirm -); diff --git a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BooksModel.cs b/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BooksModel.cs deleted file mode 100644 index 96565d6e..00000000 --- a/src/Lumina.Presentation.Web/Common/Models/WrittenContentLibrary/BookLibrary/BooksModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.Common; -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary; - -/// -/// Represents a book. -/// -[DebuggerDisplay("{Title}")] -public class BooksModel -{ -} diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/AddRoleRequestModel.cs b/src/Lumina.Presentation.Web/Common/Requests/Authorization/AddRoleRequest.cs similarity index 54% rename from src/Lumina.Presentation.Web/Common/Models/Authorization/AddRoleRequestModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/Authorization/AddRoleRequest.cs index 76b9c855..55d34f76 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/AddRoleRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Authorization/AddRoleRequest.cs @@ -1,16 +1,18 @@ #region ========================================================================= USING ===================================================================================== using System; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Authorization; +namespace Lumina.Presentation.Web.Common.Requests.Authorization; /// -/// Represents the request model for adding an authorization role. +/// Represents a request for adding an authorization role. /// -/// The name of the role. -/// The collection or permissions of the role. -public record AddRoleRequestModel( +/// The name of the role. Required. +/// The collection or permissions of the role. Required. +[DebuggerDisplay("RoleName: {RoleName}")] +public record AddRoleRequest( string? RoleName, List? Permissions ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Authorization/DeleteRoleRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Authorization/DeleteRoleRequest.cs new file mode 100644 index 00000000..4becd239 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Authorization/DeleteRoleRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Authorization; + +/// +/// Represents a request for deleting an authorization role. +/// +/// The unique identifier of the role. Required. +[DebuggerDisplay("RoleId: {RoleId}")] +public record DeleteRoleRequest( + Guid RoleId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetRolePermissionsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetRolePermissionsRequest.cs new file mode 100644 index 00000000..738e1b4e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetRolePermissionsRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Authorization; + +/// +/// Represents a request to get the authorization permissions of a role identified by . +/// +/// The Id of authorization role. Required. +[DebuggerDisplay("RoleId: {RoleId}")] +public record GetRolePermissionsRequest( + Guid RoleId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetUserPermissionsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetUserPermissionsRequest.cs new file mode 100644 index 00000000..25758d63 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetUserPermissionsRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Authorization; + +/// +/// Represents the request model for retrieving the authorization permissions of a user identified by . +/// +/// The unique identifier of the user for whom to get the authorization permissions. Required. +[DebuggerDisplay("UserId: {UserId}")] +public record GetUserPermissionsRequest( + Guid UserId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetUserRoleRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetUserRoleRequest.cs new file mode 100644 index 00000000..6080ba49 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Authorization/GetUserRoleRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Authorization; + +/// +/// Represents the request model for retrieving the authorization role of a user identified by . +/// +/// The unique identifier of the user for whom to get the authorization role. Required. +[DebuggerDisplay("UserId: {UserId}")] +public record GetUserRoleRequest( + Guid UserId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Authorization/UpdateRoleRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Authorization/UpdateRoleRequest.cs new file mode 100644 index 00000000..de8d4c45 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Authorization/UpdateRoleRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Authorization; + +/// +/// Represents a request for updating an existing authorization role. +/// +/// The unique identifier of the role. Required. +/// The name of the role. Required. +/// The collection of Ids of the permissions of the role. Required. +[DebuggerDisplay("RoleName: {RoleName}")] +public record UpdateRoleRequest( + Guid RoleId, + string? RoleName, + List? Permissions +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs new file mode 100644 index 00000000..21e9ad06 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Authorization; + +/// +/// Represents a request for updating the authorization role and permissions of a user. +/// +/// The unique identifier of the user. Required. +/// The unique identifier of the role. Optional. +/// The collection of Ids of the permissions of the role. Optional. +[DebuggerDisplay("UserId: {UserId}")] +public record UpdateUserRoleAndPermissionsRequest( + Guid UserId, + Guid? RoleId, + List? Permissions +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs new file mode 100644 index 00000000..12334e34 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs @@ -0,0 +1,6 @@ +namespace Lumina.Presentation.Web.Common.Requests.Common; + +/// +/// Record used for empty requests and responses. +/// +public record struct EmptyRequest(); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs new file mode 100644 index 00000000..6319e090 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; + +/// +/// Represents a request to get the directories of a file system path. +/// +/// The file system path for which to get the directories. Required. +/// Whether to include hidden file system elements or not. Optional. +[DebuggerDisplay("Path: {Path}")] +public record GetDirectoriesRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetFilesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetFilesRequest.cs new file mode 100644 index 00000000..0448d103 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetFilesRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; + +/// +/// Represents a request to get the files at a file system path. +/// +/// The file system path for which to get the files. Required. +/// Whether to include hidden file system elements or not. Optional. +[DebuggerDisplay("Path: {Path}")] +public record GetFilesRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs new file mode 100644 index 00000000..f78a9dcc --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; + +/// +/// Represents a request to get the files of a file system path. +/// +/// The file system path for which to get the tree files. Required. +/// Whether to include hidden file system elements or not. Optional. +[DebuggerDisplay("Path: {Path}")] +public record GetTreeFilesRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs new file mode 100644 index 00000000..78fb23a8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to check the existence of a file system path. +/// +/// The file system path to check the exitence of. Required. +/// Whether to include hidden elements in the search results, or not. Optional. +[DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")] +public record CheckPathExistsRequest( + string? Path, + bool IncludeHiddenElements +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathParentRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathParentRequest.cs new file mode 100644 index 00000000..c3bb5a7c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathParentRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; + +/// +/// Represents the request for retrieving the parent path of a file system path. +/// +/// The path for which the parent path is retrieved. +[DebuggerDisplay("Path: {Path}")] +public record GetPathParentRequest( + string? Path +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathRootRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathRootRequest.cs new file mode 100644 index 00000000..6c2660ae --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathRootRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to get the root of a file system path. +/// +/// The file system path for which to get the root. Required. +[DebuggerDisplay("Path: {Path}")] +public record GetPathRootRequest( + string? Path +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/SplitPathRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/SplitPathRequest.cs new file mode 100644 index 00000000..f8454901 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/SplitPathRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to split a file system path. +/// +/// The file system path for which to get the path segments. Required. +[DebuggerDisplay("Path: {Path}")] +public record SplitPathRequest( + string? Path +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/ValidatePathRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/ValidatePathRequest.cs new file mode 100644 index 00000000..b8664b9e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/ValidatePathRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; + +/// +/// Represents a request to check the validity of a file system path. +/// +/// The file system path to validate. Required. +[DebuggerDisplay("Path: {Path}")] +public record ValidatePathRequest( + string? Path +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/BookLibraryItemsQueryModel.cs b/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs similarity index 90% rename from src/Lumina.Presentation.Web/Common/Models/Libraries/BookLibraryItemsQueryModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs index 3cfe6f3e..d6ccbcd7 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/BookLibraryItemsQueryModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs @@ -4,13 +4,13 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Libraries; +namespace Lumina.Presentation.Web.Common.Requests.Libraries; /// -/// Represents the query parameters used to retrieve the lightweight details of the books of a media library. +/// Represents a request to get the lightweight details of the books of a media library. /// [DebuggerDisplay("LibraryId: {LibraryId}")] -public class BookLibraryItemsQueryModel +public class GetBooksLiteRequest { /// /// Gets or sets the Id of the media library whose books are retrieved. diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/CancelLibraryScanRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/CancelLibraryScanRequest.cs new file mode 100644 index 00000000..bd358060 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/CancelLibraryScanRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request to cancel the scan of a media library. +/// +/// The unique identifier of the media library whose scan is cancelled. Required. +/// The Id of scan to cancel. Required. +[DebuggerDisplay("LibraryId: {LibraryId}; ScanId: {ScanId}")] +public record CancelLibraryScanRequest( + Guid LibraryId, + Guid ScanId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/DeleteLibraryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/DeleteLibraryRequest.cs new file mode 100644 index 00000000..928c8ce7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/DeleteLibraryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request to delete a media library by its Id. +/// +/// The unique identifier of the media library to be deleted. Required. +[DebuggerDisplay("Id: {Id}")] +public record DeleteLibraryRequest( + Guid Id +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/EditLibraryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/EditLibraryRequest.cs new file mode 100644 index 00000000..93b666b7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/EditLibraryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents the request for displaying the media library editing view. +/// +/// The unique identifier of the media library to edit. +[DebuggerDisplay("Id: {Id}")] +public record EditLibraryRequest( + Guid Id +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetMetadataProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetMetadataProvidersRequest.cs new file mode 100644 index 00000000..ca866ef0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetMetadataProvidersRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents the request for retrieving the metadata providers of a media library. +/// +/// The unique identifier of the media library whose metadata providers are retrieved. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetMetadataProvidersRequest( + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/ScanLibraryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/ScanLibraryRequest.cs new file mode 100644 index 00000000..dbb07d0f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/ScanLibraryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request to scan a media library. +/// +/// The unique identifier of the media library to be scanned. Required. +[DebuggerDisplay("Id: {Id}")] +public record ScanLibraryRequest( + Guid Id +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs new file mode 100644 index 00000000..79725234 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a request to get a book by the specified Id. +/// +/// The unique identifier of the book to retrieve. +[DebuggerDisplay("Id: {Id}")] +public record GetBookRequest( + Guid Id +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequest.cs new file mode 100644 index 00000000..7ec4de40 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents the request for displaying the books browsing view. +/// +/// The unique identifier of the media library whose books are browsed. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetBooksViewRequest( + Guid? LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/GetPluginSettingsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/GetPluginSettingsRequest.cs new file mode 100644 index 00000000..cdbbe52a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Plugins/GetPluginSettingsRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Plugins; + +/// +/// Represents a request to get the settings of a plugin. +/// +/// The unique identifier of the plugin. Required. +[DebuggerDisplay("PluginId: {PluginId}")] +public record GetPluginSettingsRequest( + Guid PluginId +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Plugins/ReorderLibraryMetadataProvidersModel.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs similarity index 79% rename from src/Lumina.Presentation.Web/Common/Models/Plugins/ReorderLibraryMetadataProvidersModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs index f4331250..a88953b3 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Plugins/ReorderLibraryMetadataProvidersModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using System; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Plugins; +namespace Lumina.Presentation.Web.Common.Requests.Plugins; /// /// Represents a request to reorder the metadata providers of a media library. /// -public class ReorderLibraryMetadataProvidersModel +[DebuggerDisplay("LibraryId: {LibraryId}")] +public class ReorderLibraryMetadataProvidersRequest { /// /// Gets or sets the Id of the media library whose metadata providers are reordered. diff --git a/src/Lumina.Presentation.Web/Common/Models/Plugins/SetLibraryMetadataProviderEnabledModel.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs similarity index 80% rename from src/Lumina.Presentation.Web/Common/Models/Plugins/SetLibraryMetadataProviderEnabledModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs index 7d7a4eae..38046da0 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Plugins/SetLibraryMetadataProviderEnabledModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using System; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Plugins; +namespace Lumina.Presentation.Web.Common.Requests.Plugins; /// /// Represents a request to enable or disable a metadata provider for a media library. /// -public class SetLibraryMetadataProviderEnabledModel +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public class SetLibraryMetadataProviderEnabledRequest { /// /// Gets or sets the Id of the media library whose metadata provider is enabled or disabled. diff --git a/src/Lumina.Presentation.Web/Common/Models/Plugins/UpdatePluginSettingsModel.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/UpdatePluginSettingsRequest.cs similarity index 78% rename from src/Lumina.Presentation.Web/Common/Models/Plugins/UpdatePluginSettingsModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/Plugins/UpdatePluginSettingsRequest.cs index 246211a4..c48bac46 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Plugins/UpdatePluginSettingsModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Plugins/UpdatePluginSettingsRequest.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== using System; using System.Collections.Generic; +using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Plugins; +namespace Lumina.Presentation.Web.Common.Requests.Plugins; /// /// Represents a request to update the settings of a plugin. /// -public class UpdatePluginSettingsModel +[DebuggerDisplay("PluginId: {PluginId}")] +public class UpdatePluginSettingsRequest { /// /// Gets or sets the unique identifier of the plugin. diff --git a/src/Lumina.Presentation.Web/Common/Requests/Tools/SetLanguageRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Tools/SetLanguageRequest.cs new file mode 100644 index 00000000..2db72ecc --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Tools/SetLanguageRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Tools; + +/// +/// Represents the request for setting the culture used by the application. +/// +/// The new culture to set. +/// The URL to return to, after setting the new culture. +[DebuggerDisplay("NewCulture: {NewCulture}, ReturnUrl: {ReturnUrl}")] +public record SetLanguageRequest( + string? NewCulture, + string? ReturnUrl +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/Authentication/LoginViewRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/Authentication/LoginViewRequest.cs new file mode 100644 index 00000000..a9dda6d5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/Authentication/LoginViewRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; + +/// +/// Represents the request for displaying the account login view. +/// +/// The URL to return to, after login. +[DebuggerDisplay("ReturnUrl: {ReturnUrl}")] +public record LoginViewRequest( + string? ReturnUrl = null +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/ChangePasswordRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/ChangePasswordRequest.cs new file mode 100644 index 00000000..b899d829 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/ChangePasswordRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.UsersManagement; + +/// +/// Represents the request model for account password change. +/// +/// The username of the account. Required. +/// The current password of the account. Required. +/// The new password of the account. Required. +/// The confirmation of the new password of the account. Required. +[DebuggerDisplay("Username: {Username}")] +public record ChangePasswordRequest( + string? Username, + string? CurrentPassword, + string? NewPassword, + string? NewPasswordConfirm +); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/LoginRequest.cs similarity index 64% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/UsersManagement/LoginRequest.cs index 650ff42c..bca229e8 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/LoginRequest.cs @@ -2,17 +2,17 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Requests.UsersManagement; /// /// Represents the request model for user authentication. /// -/// The username used to authenticate. -/// The password used to authenticate. -/// The TOTP (Time-Based One-Time Password) code used for two-factor authentication. +/// The username of the account to authenticate. Required. +/// The password of the account to authenticate. Required. +/// The TOTP (Time-Based One-Time Password) of the account to authenticate. Optional. /// The URL to return to, after login. [DebuggerDisplay("Username: {Username}")] -public record LoginRequestModel( +public record LoginRequest( string? Username = null, string? Password = null, string? TotpCode = null, diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/RecoverPasswordRequest.cs similarity index 70% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/UsersManagement/RecoverPasswordRequest.cs index 1668a464..e41f7e8a 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/RecoverPasswordRequest.cs @@ -2,15 +2,15 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Requests.UsersManagement; /// /// Represents the request model for account password recovery. /// -/// The username of the account for which to recover the password. -/// The TOTP (Time-Based One-Time Password) code used to recover the password. +/// The username of the account for which to recover the password. Required. +/// The TOTP (Time-Based One-Time Password) of the account for which to recover the password. Required. [DebuggerDisplay("Username: {Username}")] -public record RecoverPasswordRequestModel( +public record RecoverPasswordRequest( string? Username, string? TotpCode ); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/RegisterRequest.cs similarity index 65% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs rename to src/Lumina.Presentation.Web/Common/Requests/UsersManagement/RegisterRequest.cs index 082b8108..9aa1c105 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/RegisterRequest.cs @@ -2,18 +2,18 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Requests.UsersManagement; /// /// Represents the request model for user registration. /// -/// The desired username for the new account. -/// The password for the new account. -/// The confirmation of the entered password, used to ensure consistency. -/// Specifies the type of registration, e.g., "Admin" or "User". -/// Indicates whether two-factor authentication (2FA) should be enabled for the new account. +/// The desired username for the new account. Required. +/// The password for the new account. Required. +/// The confirmation of the entered password, used to ensure consistency. Required. +/// Specifies the type of registration, e.g., "Admin" or "User". Required. +/// Indicates whether two-factor authentication (2FA) should be enabled for the new account. Optional. [DebuggerDisplay("Username: {Username}")] -public record RegisterRequestModel( +public record RegisterRequest( string? Username, string? Password, string? PasswordConfirm, diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs b/src/Lumina.Presentation.Web/Common/Responses/Authorization/GetAuthorizationResponse.cs similarity index 92% rename from src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs rename to src/Lumina.Presentation.Web/Common/Responses/Authorization/GetAuthorizationResponse.cs index 4436f3a9..3190ff2d 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Responses/Authorization/GetAuthorizationResponse.cs @@ -4,7 +4,7 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.Authorization; +namespace Lumina.Presentation.Web.Common.Responses.Authorization; /// /// Represents the response model for an account authorization request. diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/ChangePasswordResponse.cs similarity index 81% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs rename to src/Lumina.Presentation.Web/Common/Responses/UsersManagement/ChangePasswordResponse.cs index 4befdb83..7bd05bf6 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/ChangePasswordResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/ChangePasswordResponse.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Responses.UsersManagement; /// /// Represents the response model for an account password change request. /// /// Whether the password was changed or not. [DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")] -public record ChangePasswordResponseModel( +public record ChangePasswordResponse( bool IsPasswordChanged ); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/InitializationResponse.cs similarity index 84% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs rename to src/Lumina.Presentation.Web/Common/Responses/UsersManagement/InitializationResponse.cs index 68a0dc52..6f4582d7 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/InitializationModel.cs +++ b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/InitializationResponse.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Responses.UsersManagement; /// /// Model for verifying the initialization status of the application. /// [DebuggerDisplay("IsInitialized: {IsInitialized}")] -public class InitializationModel +public class InitializationResponse { /// /// Gets or sets a value indicating whether the application has been run before, and the super admin account has been created. diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/LoginResponse.cs similarity index 89% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs rename to src/Lumina.Presentation.Web/Common/Responses/UsersManagement/LoginResponse.cs index 18989cb0..0cd2dc7a 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/LoginResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/LoginResponse.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Responses.UsersManagement; /// /// Represents the response model for a user authentication. @@ -13,7 +13,7 @@ namespace Lumina.Presentation.Web.Common.Models.UsersManagement; /// The JWT authentication token, if authentication failed or TOTP is required. /// Indicates whether the user has Two-Factor Authentication enabled, or not. [DebuggerDisplay("Username: {Username}")] -public record LoginResponseModel( +public record LoginResponse( Guid Id, string? Username, string? Token, diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/RecoverPasswordResponse.cs similarity index 81% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs rename to src/Lumina.Presentation.Web/Common/Responses/UsersManagement/RecoverPasswordResponse.cs index 4a5703f1..514fc5dc 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RecoverPasswordResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/RecoverPasswordResponse.cs @@ -2,13 +2,13 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Responses.UsersManagement; /// /// Represents the response model for an account password reset request. /// /// Whether the password was reset or not. [DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")] -public record RecoverPasswordResponseModel( +public record RecoverPasswordResponse( bool IsPasswordReset ); diff --git a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/RegisterResponse.cs similarity index 85% rename from src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs rename to src/Lumina.Presentation.Web/Common/Responses/UsersManagement/RegisterResponse.cs index 7a43ba88..be3fbf96 100644 --- a/src/Lumina.Presentation.Web/Common/Models/UsersManagement/RegisterResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Responses/UsersManagement/RegisterResponse.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.Models.UsersManagement; +namespace Lumina.Presentation.Web.Common.Responses.UsersManagement; /// /// Represents the response model for a successful registration. @@ -11,7 +11,7 @@ namespace Lumina.Presentation.Web.Common.Models.UsersManagement; /// The username of the registered user. /// The TOTP (Time-Based One-Time Password) secret used for two-factor authentication. [DebuggerDisplay("Username: {Username}")] -public record RegisterResponseModel( +public record RegisterResponse( string? Username, string? TotpSecret ); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Authentication.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Authentication.cs new file mode 100644 index 00000000..0d17674c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Authentication.cs @@ -0,0 +1,19 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the authentication endpoints of the remote API. + /// + public static class Authentication + { + public const string REGISTER_ACCOUNT = "auth/register"; + public const string LOGIN_ACCOUNT = "auth/login"; + public const string RECOVER_PASSWORD = "auth/recover-password"; + public const string CHANGE_PASSWORD = "auth/change-password"; + public const string USERS = "auth/users"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Authorization.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Authorization.cs new file mode 100644 index 00000000..d1b2a239 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Authorization.cs @@ -0,0 +1,18 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the authorization endpoints of the remote API. + /// + public static class Authorization + { + public const string UPDATE_USER_ROLE_AND_PERMISSIONS_BY_USER_ID = "auth/users/{userId}/role-and-permissions"; + public const string GET_USER_PERMISSIONS_BY_USER_ID = "auth/users/{userId}/permissions"; + public const string GET_USER_ROLE_BY_USER_ID = "auth/users/{userId}/role"; + public const string GET_AUTHORIZATION = "auth/get-authorization"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs new file mode 100644 index 00000000..c3aa70eb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the books endpoints of the remote API. + /// + public static class Books + { + public const string GET_BOOKS_LITE = "books/lite"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Directories.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Directories.cs new file mode 100644 index 00000000..f79175fb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Directories.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the directories endpoints of the remote API. + /// + public static class Directories + { + public const string GET_DIRECTORIES = "directories/get-directories"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Drives.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Drives.cs new file mode 100644 index 00000000..288d9d14 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Drives.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the drives endpoints of the remote API. + /// + public static class Drives + { + public const string GET_DRIVES = "drives/get-drives"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.FileSystem.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.FileSystem.cs new file mode 100644 index 00000000..b317b02b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.FileSystem.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the file system endpoints of the remote API. + /// + public static class FileSystem + { + public const string GET_TYPES = "file-system/get-type"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Files.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Files.cs new file mode 100644 index 00000000..2d5d3c78 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Files.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the files endpoints of the remote API. + /// + public static class Files + { + public const string GET_TREE_FILES = "files/get-tree-files"; + public const string GET_FILES = "files/get-files"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Initialization.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Initialization.cs new file mode 100644 index 00000000..7f7921c0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Initialization.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the initialization endpoint of the remote API. + /// + public static class Initialization + { + public const string SETUP_APPLICATION = "initialization"; + public const string CHECK_INITIALIZATION = "initialization"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs new file mode 100644 index 00000000..ceef0553 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs @@ -0,0 +1,28 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the media libraries endpoints of the remote API. + /// + public static class Libraries + { + public const string GET_LIBRARY_BY_ID = "libraries/{id}"; + public const string GET_LIBRARIES = "libraries"; + public const string GET_ENABLED_LIBRARIES = "libraries/enabled"; + public const string ADD_LIBRARY = "libraries"; + public const string UPDATE_LIBRARY = "libraries/{id}"; + public const string DELETE_LIBRARY = "libraries/{id}"; + public const string SCAN_LIBRARIES = "libraries/scans"; + public const string SCAN_LIBRARY = "libraries/{id}/scans"; + public const string GET_RUNNING_LIBRARIES_SCAN = "libraries/scans/running"; + public const string CANCEL_LIBRARIES_SCAN = "libraries/scans/cancel"; + public const string CANCEL_LIBRARY_SCAN = "libraries/{libraryId}/scans/{scanId}/cancel"; + public const string GET_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers"; + public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; + public const string REORDER_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers/reorder"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Path.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Path.cs new file mode 100644 index 00000000..4e056a6a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Path.cs @@ -0,0 +1,20 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the paths endpoints of the remote API. + /// + public static class Path + { + public const string GET_PATH_ROOT = "path/get-path-root"; + public const string GET_PATH_SEPARATOR = "path/get-path-separator"; + public const string GET_PATH_PARENT = "path/get-path-parent"; + public const string SPLIT = "path/split"; + public const string VALIDATE = "path/validate"; + public const string CHECK_PATH_EXISTS = "path/check-path-exists"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Permissions.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Permissions.cs new file mode 100644 index 00000000..5ccaf316 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Permissions.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the permissions endpoints of the remote API. + /// + public static class Permissions + { + public const string GET_PERMISSIONS = "auth/permissions"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Plugins.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Plugins.cs new file mode 100644 index 00000000..1371d505 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Plugins.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the plugins endpoints of the remote API. + /// + public static class Plugins + { + public const string GET_PLUGINS = "plugins"; + public const string GET_PLUGIN_SETTINGS = "plugins/{pluginId}/settings"; + public const string UPDATE_PLUGIN_SETTINGS = "plugins/{pluginId}/settings"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Roles.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Roles.cs new file mode 100644 index 00000000..09691d9b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Roles.cs @@ -0,0 +1,19 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the roles endpoints of the remote API. + /// + public static class Roles + { + public const string GET_ROLE_PERMISSIONS_BY_ROLE_ID = "auth/roles/{roleId}/permissions"; + public const string GET_ROLES = "auth/roles"; + public const string CREATE_ROLE = "auth/roles"; + public const string UPDATE_ROLE = "auth/roles"; + public const string DELETE_ROLE = "auth/roles/{roleId}"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs new file mode 100644 index 00000000..7ef9fa39 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Users.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the users endpoints of the remote API. + /// + public static class Users + { + public const string GET_USER_SETTINGS = "users/me/settings"; + public const string UPDATE_USER_SETTINGS = "users/me/settings"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Admin.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Admin.cs new file mode 100644 index 00000000..618d0b55 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Admin.cs @@ -0,0 +1,24 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the administrator pages. + /// + public static class Admin + { + public const string MANAGE_ROLES = "{culture}/admin/manage-roles"; + public const string MANAGE_PERMISSIONS = "{culture}/admin/manage-permissions"; + public const string GET_PERMISSIONS_BY_ROLE_ID = "{culture}/admin/api-get-permissions-by-role-id/{roleId}"; + public const string GET_PERMISSIONS_BY_USER_ID = "{culture}/admin/api-get-permissions-by-user-id/{userId}"; + public const string GET_ROLE_BY_USER_ID = "{culture}/admin/api-get-role-by-user-id/{userId}"; + public const string GET_ROLES = "{culture}/admin/api-get-roles"; + public const string CREATE_ROLE = "{culture}/admin/api-create-role"; + public const string UPDATE_ROLE = "{culture}/admin/api-update-role"; + public const string DELETE_ROLE = "{culture}/admin/api-delete-role/{roleId}"; + public const string UPDATE_USER_AUTHORIZATION = "{culture}/admin/api-update-user-authorization"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Authentication.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Authentication.cs new file mode 100644 index 00000000..60cb1ced --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Authentication.cs @@ -0,0 +1,25 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the authentication pages. + /// + public static class Authentication + { + public const string REGISTER_VIEW = "{culture}/auth/register"; + public const string LOGIN_VIEW = "{culture}/auth/login/{returnUrl?}"; + public const string RECOVER_PASSWORD_VIEW = "{culture}/auth/recover-password"; + public const string CHANGE_PASSWORD_VIEW = "{culture}/auth/change-password"; + public const string PROFILE_VIEW = "{culture}/auth/profile"; + public const string ACCESS_DENIED_VIEW = "{culture}/auth/access-denied"; + public const string LOGOUT = "{culture}/auth/logout"; + public const string REGISTER = "{culture}/auth/api-register"; + public const string LOGIN = "{culture}/auth/api-login"; + public const string RECOVER_PASSWORD = "{culture}/auth/api-recover-password"; + public const string CHANGE_PASSWORD = "{culture}/auth/api-change-password"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs new file mode 100644 index 00000000..1b5c58c2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the books pages. + /// + public static class Books + { + public const string INDEX = "{culture}/library/written-content-library/books-library/books"; + public const string GET_LIBRARY_ITEMS = "{culture}/library/written-content-library/books-library/books/api-get-library-items"; + public const string EDIT_BOOK = "{culture}/library/written-content-library/books-library/books/{id}"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Directories.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Directories.cs new file mode 100644 index 00000000..921c3392 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Directories.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the file system directories endpoints. + /// + public static class Directories + { + public const string GET_DIRECTORIES = "directories/api-get-directories"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Drives.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Drives.cs new file mode 100644 index 00000000..23a36942 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Drives.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the file system drives endpoints. + /// + public static class Drives + { + public const string GET_DRIVES = "drives/api-get-drives"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.FileSystem.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.FileSystem.cs new file mode 100644 index 00000000..e1b550de --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.FileSystem.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the file system endpoints. + /// + public static class FileSystem + { + public const string GET_TYPE = "file-system/api-get-type"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Files.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Files.cs new file mode 100644 index 00000000..9756c9c7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Files.cs @@ -0,0 +1,16 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the file system files endpoints. + /// + public static class Files + { + public const string GET_TREE_FILES = "files/api-get-tree-files"; + public const string GET_FILES = "files/api-get-files"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Home.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Home.cs new file mode 100644 index 00000000..9cde8458 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Home.cs @@ -0,0 +1,19 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the home pages. + /// + public static class Home + { + public const string INDEX = "/"; + public const string INDEX_CULTURED = "{culture}"; + public const string PRIVACY = "{culture}/privacy"; + public const string ERROR = "{culture}/error"; + public const string NOT_FOUND = "{culture}/not-found"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Language.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Language.cs new file mode 100644 index 00000000..5c2938e8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Language.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the language tool pages. + /// + public static class Language + { + public const string SET_LANGUAGE = "{culture}/tools/language/set-language"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs new file mode 100644 index 00000000..3a54fc3a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs @@ -0,0 +1,29 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the media libraries management pages. + /// + public static class LibraryManagement + { + public const string INDEX = "{culture}/libraries/manage"; + public const string ADD_LIBRARY = "{culture}/libraries/manage/item"; + public const string EDIT_LIBRARY = "{culture}/libraries/manage/item/{id}"; + public const string GET_LIBRARIES = "{culture}/libraries/manage/api-get-libraries"; + public const string GET_ENABLED_LIBRARIES = "{culture}/libraries/manage/api-get-enabled-libraries"; + public const string SAVE_LIBRARY = "{culture}/libraries/manage/api-item"; + public const string DELETE_LIBRARY = "{culture}/libraries/manage/api-item/{id}"; + public const string GET_RUNNING_LIBRARY_SCANS = "{culture}/libraries/manage/api-get-running-library-scans"; + public const string SCAN_LIBRARIES = "{culture}/libraries/manage/api-scan-libraries"; + public const string SCAN_LIBRARY = "{culture}/libraries/manage/api-scan-library/{id}"; + public const string CANCEL_LIBRARIES_SCAN = "{culture}/libraries/manage/api-cancel-libraries-scan"; + public const string CANCEL_LIBRARY_SCAN = "{culture}/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"; + public const string GET_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-metadata-providers/{libraryId}"; + public const string SET_METADATA_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-metadata-provider-enabled"; + public const string REORDER_METADATA_PROVIDERS = "{culture}/libraries/manage/api-reorder-metadata-providers"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Path.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Path.cs new file mode 100644 index 00000000..ebc7bab3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Path.cs @@ -0,0 +1,20 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the file system paths endpoints. + /// + public static class Path + { + public const string GET_PATH_ROOT = "path/api-get-path-root"; + public const string GET_PATH_SEPARATOR = "path/api-get-path-separator"; + public const string GET_PATH_PARENT = "path/api-get-path-parent"; + public const string SPLIT_PATH = "path/api-split"; + public const string VALIDATE_PATH = "path/api-validate"; + public const string CHECK_PATH_EXISTS = "path/api-check-path-exists"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Plugins.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Plugins.cs new file mode 100644 index 00000000..6008922e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Plugins.cs @@ -0,0 +1,18 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the plugins pages. + /// + public static class Plugins + { + public const string INDEX = "{culture}/plugins"; + public const string GET_PLUGINS = "{culture}/plugins/api-get-plugins"; + public const string GET_PLUGIN_SETTINGS = "{culture}/plugins/api-get-plugin-settings/{pluginId}"; + public const string UPDATE_PLUGIN_SETTINGS = "{culture}/plugins/api-update-plugin-settings"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs new file mode 100644 index 00000000..267383c8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Settings.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the user settings tool pages. + /// + public static class Settings + { + public const string INDEX = "{culture}/tools/settings"; + public const string GET_USER_SETTINGS = "{culture}/tools/settings/api-get-user-settings"; + public const string UPDATE_USER_SETTINGS = "{culture}/tools/settings/api-update-user-settings"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs b/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs index b8480404..ac298e1f 100644 --- a/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs +++ b/src/Lumina.Presentation.Web/Common/Security/CryptographyService.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.Configuration; +using Lumina.Presentation.Web.Common.DTO.Configuration; using Microsoft.Extensions.Options; using System; using System.Security.Cryptography; @@ -18,10 +18,10 @@ public sealed class CryptographyService : ICryptographyService, IDisposable /// /// Initializes a new instance of the class. /// - /// Injected service for retrieving . - public CryptographyService(IOptions encryptionSettingsModelOptions) + /// Injected service for retrieving . + public CryptographyService(IOptions encryptionSettingsOptions) { - _key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey); + _key = Convert.FromBase64String(encryptionSettingsOptions.Value.SecretKey); } /// diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs b/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs index fe999290..da8a46b5 100644 --- a/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Models.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Caching.Hybrid; using System; @@ -53,7 +52,7 @@ public class CachedAuthorizationHandler : DelegatingHandler return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } // otherwise, check the hybrid cache to see if there is a cached authorization - CachedResponseModel response = await _hybridCache.GetOrCreateAsync( + CachedResponse response = await _hybridCache.GetOrCreateAsync( cacheKey, async (cancellationToken) => { @@ -61,7 +60,7 @@ public class CachedAuthorizationHandler : DelegatingHandler HttpResponseMessage result = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); string content = await result.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); // cache both status code and content - return new CachedResponseModel + return new CachedResponse { Content = content, StatusCode = result.StatusCode diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/CachedResponseModel.cs b/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs similarity index 88% rename from src/Lumina.Presentation.Web/Common/Models/Common/CachedResponseModel.cs rename to src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs index 3c02aabe..156cc880 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Common/CachedResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs @@ -3,13 +3,13 @@ using System.Diagnostics; using System.Net; #endregion -namespace Lumina.Presentation.Web.Common.Models.Common; +namespace Lumina.Presentation.Web.Common.Services; /// /// Represents a cached HTTP response, including its content and status code. /// [DebuggerDisplay("StatusCode: {StatusCode}")] -public class CachedResponseModel +public class CachedResponse { /// /// Gets or sets the content of the cached HTTP response. diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs index 7542a8dd..93663e4d 100644 --- a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -1,16 +1,15 @@ namespace Lumina.Presentation.Web.Common.Services; /// -/// Interface for the service for generating URLs from action and controller names, with URL localization. +/// Interface for the service for generating absolute URLs from the application route templates, with URL localization. /// public interface IUrlService { /// - /// Generates an absolute URL for the specified controller action. + /// Generates an absolute URL for the specified route template. /// - /// The action name within the controller. - /// The controller name. - /// Optional additional route values, like query parameters. - /// An absolute URL to the specified action. - string? GetAbsoluteUrl(string action, string controller, object? additionalRouteValues = null); + /// The route template of the target page or endpoint, taken from the constants. + /// Optional additional route values, like route parameters. + /// An absolute URL to the specified route. + string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null); } diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs index 1f3cfd9f..acc29775 100644 --- a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -1,71 +1,73 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Routes; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Microsoft.AspNetCore.Routing; using System; -using System.Linq; +using System.Collections.Generic; using System.Reflection; #endregion namespace Lumina.Presentation.Web.Common.Services; /// -/// Service for generating URLs from action and controller names, with URL localization. +/// Service for generating absolute URLs for the application routes, with URL localization. /// public class UrlService : IUrlService { - private readonly LinkGenerator _linkGenerator; private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; + + /// + /// The collection of route templates defined in the constants, used to validate the requested routes. + /// + private static readonly HashSet s_knownRouteTemplates = GetKnownRouteTemplates(); /// /// Initializes a new instance of the class. /// - /// The ASP.NET Core link generator service. /// Provides access to the current HTTP context. - /// The used to retrieve information about the application's routes and actions. - public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) + public UrlService(IHttpContextAccessor httpContextAccessor) { - _linkGenerator = linkGenerator; _httpContextAccessor = httpContextAccessor; - _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; } /// - /// Generates an absolute URL for the specified controller action. + /// Generates an absolute URL for the specified route template. /// - /// The action name within the controller. - /// The controller name. - /// Optional additional route values, like query parameters. - /// An absolute URL to the specified action. - public string? GetAbsoluteUrl(string action, string controller, object? additionalRouteValues = null) + /// The route template of the target page or endpoint, taken from the constants. + /// Optional additional route values, like route parameters. + /// An absolute URL to the specified route. + /// Thrown when is not one of the route templates defined in the constants. + public string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null) { + // fail fast when the route template is not one of the ones defined in the WebRoutes constants, instead of silently generating a broken URL + if (!s_knownRouteTemplates.Contains(routeTemplate)) + throw new ArgumentException($"The route template '{routeTemplate}' is not defined in the WebRoutes constants.", nameof(routeTemplate)); + HttpContext? httpContext = _httpContextAccessor.HttpContext; if (httpContext is null) return null; - string scheme = httpContext.Request.Scheme; string culture = httpContext.Request.RouteValues["culture"]?.ToString() ?? "en-US"; - // find the controller's route template - ControllerActionDescriptor? controllerActionDescriptor = _actionDescriptorCollectionProvider - .ActionDescriptors.Items - .OfType() - .FirstOrDefault(controllerActionDescription => - controllerActionDescription.ControllerName.Equals(controller, StringComparison.OrdinalIgnoreCase) && - controllerActionDescription.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; - // merge culture and additional values - RouteValueDictionary routeValues = []; - if (needsCulture) - routeValues.Add("culture", culture); + string path = routeTemplate.Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase); if (additionalRouteValues is not null) - foreach (PropertyInfo prop in additionalRouteValues.GetType().GetProperties()) - routeValues.Add(prop.Name, prop.GetValue(additionalRouteValues)); + foreach (PropertyInfo property in additionalRouteValues.GetType().GetProperties()) + path = path.Replace($"{{{property.Name}}}", property.GetValue(additionalRouteValues)?.ToString(), StringComparison.OrdinalIgnoreCase); + // ensure the path starts with a slash, so that it is relative to the server root when concatenated with the host and the path base + if (!path.StartsWith('/')) + path = "/" + path; + // build the absolute URL from the request's scheme, host and path base + return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.PathBase}{path}"; + } - return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: routeValues, scheme: scheme); + /// + /// Collects the values of all route template constants defined in the class. + /// + /// The set of the route templates defined in the constants. + private static HashSet GetKnownRouteTemplates() + { + HashSet routeTemplates = []; + foreach (Type nestedType in typeof(WebRoutes).GetNestedTypes()) + foreach (FieldInfo field in nestedType.GetFields(BindingFlags.Public | BindingFlags.Static)) + if (field.IsLiteral && field.FieldType == typeof(string)) + routeTemplates.Add((string)field.GetValue(null)!); + return routeTemplates; } } diff --git a/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs index b05311bc..d08fbd42 100644 --- a/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs +++ b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; -using Lumina.Presentation.Web.Common.Models.Configuration; +using Lumina.Presentation.Web.Common.DTO.Configuration; using System; using System.Buffers.Text; #endregion @@ -10,7 +10,7 @@ namespace Lumina.Presentation.Web.Common.Validators; /// /// Validates the needed validation rules for the EncryptionSettings application configuration settings section. /// -public class EncryptionSettingsModelValidator : AbstractValidator +public class EncryptionSettingsModelValidator : AbstractValidator { /// /// Initializes a new instance of the class. diff --git a/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationModelValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationModelValidator.cs index 17dcb612..8d8281f8 100644 --- a/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationModelValidator.cs +++ b/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationModelValidator.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; -using Lumina.Presentation.Web.Common.Models.Configuration; +using Lumina.Presentation.Web.Common.DTO.Configuration; #endregion namespace Lumina.Presentation.Web.Common.Validators; @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Validators; /// /// Validates the needed validation rules for the ServerConfiguration application configuration settings section. /// -public class ServerConfigurationModelValidator : AbstractValidator +public class ServerConfigurationModelValidator : AbstractValidator { /// /// Initializes a new instance of the class. diff --git a/src/Lumina.Presentation.Web/Controllers/AdminController.cs b/src/Lumina.Presentation.Web/Controllers/AdminController.cs deleted file mode 100644 index d09fc47d..00000000 --- a/src/Lumina.Presentation.Web/Controllers/AdminController.cs +++ /dev/null @@ -1,154 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Attributes; -using Lumina.Presentation.Web.Common.Models.Authorization; -using Lumina.Presentation.Web.Common.Models.UsersManagement; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers; - -/// -/// Controller for administrator related operations. -/// -[Authorize] -[RequireRole("Admin")] -[Route("{culture}/admin")] -public class AdminController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public AdminController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Displays the view for managing authorization roles. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("manage-roles")] - public async Task ManageRoles(CancellationToken cancellationToken) - { - // get the list of roles and permissions from the API - ViewData["roles"] = await _apiHttpClient.GetAsync($"auth/roles/", cancellationToken).ConfigureAwait(false); - ViewData["permissions"] = await _apiHttpClient.GetAsync($"auth/permissions/", cancellationToken).ConfigureAwait(false); - return View(); - } - - /// - /// Displays the view for managing authorization permissions. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("manage-permissions")] - public async Task ManagePermissions(CancellationToken cancellationToken) - { - ViewData["users"] = await _apiHttpClient.GetAsync($"auth/users", cancellationToken).ConfigureAwait(false); - ViewData["roles"] = await _apiHttpClient.GetAsync($"auth/roles/", cancellationToken).ConfigureAwait(false); - ViewData["permissions"] = await _apiHttpClient.GetAsync($"auth/permissions/", cancellationToken).ConfigureAwait(false); - return View(); - } - - /// - /// Gets the authorization permissions of a role identified by . - /// - /// The unique identifier of the role for which to get the list of permissions. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-permissions-by-role-id/{roleId}")] - public async Task GetPermissionsByRoleId(Guid roleId, CancellationToken cancellationToken) - { - RolePermissionsModel response = await _apiHttpClient.GetAsync($"auth/roles/{roleId}/permissions", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Gets the authorization permissions of a user identified by . - /// - /// The unique identifier of the user for whom to get the list of permissions. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-permissions-by-user-id/{userId}")] - public async Task GetPermissionsByUserId(Guid userId, CancellationToken cancellationToken) - { - PermissionModel[] response = await _apiHttpClient.GetAsync($"auth/users/{userId}/permissions", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Gets the authorization role of a user identified by . - /// - /// The unique identifier of the user for whom to get the role. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-role-by-user-id/{userId}")] - public async Task GetRoleByUserId(Guid userId, CancellationToken cancellationToken) - { - RoleModel? response = await _apiHttpClient.GetAsync($"auth/users/{userId}/role", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Gets the collection of authorization roles. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-roles")] - public async Task GetRoles(CancellationToken cancellationToken) - { - RoleModel[] response = await _apiHttpClient.GetAsync($"auth/roles/", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Creates an authorization role with the specified name and associated permissions. - /// - /// The model containing the data of the role to be created. - /// Cancellation token that can be used to stop the execution. - [HttpPost("api-create-role")] - public async Task CreateRole([FromBody] AddRoleRequestModel model, CancellationToken cancellationToken) - { - RolePermissionsModel response = await _apiHttpClient.PostAsync($"auth/roles/", model, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Updates an authorization role with the specified name and associated permissions. - /// - /// The model containing the data of the role to be updated. - /// Cancellation token that can be used to stop the execution. - [HttpPut("api-update-role")] - public async Task UpdateRole([FromBody] UpdateRoleRequestModel model, CancellationToken cancellationToken) - { - RolePermissionsModel response = await _apiHttpClient.PutAsync($"auth/roles/", model, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Deletes an authorization role. - /// - /// The unique identifier of the role to be deleted. - /// Cancellation token that can be used to stop the execution. - [HttpDelete("api-delete-role/{roleId}")] - public async Task DeleteRole(Guid roleId, CancellationToken cancellationToken) - { - await _apiHttpClient.DeleteAsync($"auth/roles/{roleId}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true }); - } - - /// - /// Updates an authorization role with the specified name and associated permissions. - /// - /// The model containing the data of the role to be updated. - /// Cancellation token that can be used to stop the execution. - [HttpPut("api-update-user-authorization")] - public async Task UpdateUserAuthorization([FromBody] UpdateUserRoleAndPermissionsRequestModel model, CancellationToken cancellationToken) - { - GetAuthorizationResponse response = await _apiHttpClient.PutAsync($"auth/users/{model.UserId}/role-and-permissions", model, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs deleted file mode 100644 index d81b169d..00000000 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileSystemManagement; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; - -/// -/// Controller for managing file system directories. -/// -[Authorize] -[Route("directories")] -public class DirectoriesController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public DirectoriesController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Gets the directories of . - /// - /// The path for which to get the directories. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-directories")] - public async Task GetDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) - { - IEnumerable response = await _apiHttpClient.GetAsync( - $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs deleted file mode 100644 index b3b5efe9..00000000 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DrivesController.cs +++ /dev/null @@ -1,40 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileSystemManagement; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; - -/// -/// Controller for managing file system drives. -/// -[Authorize] -[Route("drives")] -public class DrivesController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public DrivesController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Controller action for getting the list of all file system drives. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-drives")] - public async Task GetDrives(CancellationToken cancellationToken) - { - FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync($"drives/get-drives", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { drives = response } }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs deleted file mode 100644 index 3844edaf..00000000 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FileSystemController.cs +++ /dev/null @@ -1,40 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileSystemManagement; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; - -/// -/// Controller for managing file systems. -/// -[Authorize] -[Route("file-system")] -public class FileSystemController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public FileSystemController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Gets the type of the file system. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-type")] - public async Task GetType(CancellationToken cancellationToken) - { - FileSystemTypeModel response = await _apiHttpClient.GetAsync($"file-system/get-type", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { platformType = response.PlatformType.ToString() } }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs deleted file mode 100644 index ab1a5517..00000000 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/FilesController.cs +++ /dev/null @@ -1,60 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileSystemManagement; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; - -/// -/// Controller for managing file system files. -/// -[Authorize] -[Route("files")] -public class FilesController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public FilesController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Gets the files of . - /// - /// The path for which to get the files. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-tree-files")] - public async Task GetTreeFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) - { - IEnumerable response = await _apiHttpClient.GetAsync( - $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Gets the files of . - /// - /// The path for which to get the files. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-files")] - public async Task GetFiles([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) - { - // TODO: check if it's really used - IEnumerable response = await _apiHttpClient.GetAsync( - $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs deleted file mode 100644 index 177a63a8..00000000 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/PathController.cs +++ /dev/null @@ -1,104 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.FileSystemManagement; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.FileSystemManagement; - -/// -/// Controller for managing file system paths. -/// -[Authorize] -[Route("path")] -public class PathController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public PathController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Gets the root of . - /// - /// The path for which to get the root. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-path-root")] - public async Task GetPathRoot([FromQuery] string path, CancellationToken cancellationToken) - { - // TODO: check if it's really used - PathSegmentModel response = await _apiHttpClient.GetAsync($"path/get-path-root?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { root = response } }); - } - - /// - /// Gets the path separator character of the file system. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-path-separator")] - public async Task GetPathSeparator(CancellationToken cancellationToken) - { - PathSeparatorModel response = await _apiHttpClient.GetAsync($"path/get-path-separator", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { pathSeparator = response.Separator } }); - } - - /// - /// Gets the path separator character of the file system. - /// - /// The path for which to get the parent path. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-path-parent")] - public async Task GetPathParent([FromQuery] string path, CancellationToken cancellationToken) - { - PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/get-path-parent?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { pathSegments = response } }); - } - - /// - /// Gets the path components of . - /// - /// The path for which to get the path segments. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-split")] - public async Task SplitPath([FromQuery] string path, CancellationToken cancellationToken) - { - PathSegmentModel[] response = await _apiHttpClient.GetAsync($"path/split?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { pathSegments = response } }); - } - - /// - /// Validates the validity of . - /// - /// The path to be validated. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-validate")] - public async Task ValidatePath([FromQuery] string path, CancellationToken cancellationToken) - { - PathValidModel response = await _apiHttpClient.GetAsync($"path/validate?path={Uri.EscapeDataString(path)}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { isValid = response.IsValid } }); - } - - /// - /// Checks whether exists or not. - /// - /// The path to be checked. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-check-path-exists")] - public async Task CheckPathExists([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) - { - PathExistsModel response = await _apiHttpClient.GetAsync( - $"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { exists = response.Exists } }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/HomeController.cs b/src/Lumina.Presentation.Web/Controllers/HomeController.cs deleted file mode 100644 index fd9dcf02..00000000 --- a/src/Lumina.Presentation.Web/Controllers/HomeController.cs +++ /dev/null @@ -1,66 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Models; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Controllers; - -/// -/// Controller for home page. -/// -[Authorize] -[Route("")] // handle 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; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for logging. - public HomeController(ILogger logger) - { - _logger = logger; - } - - /// - /// Displays the view for the home page. - /// - [HttpGet("")] - public IActionResult Index() - { - return View(); - } - - /// - /// Displays the view for privacy. - /// - [HttpGet("privacy")] - public IActionResult Privacy() - { - return View(); - } - - /// - /// Displays the view for errors. - /// - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - [HttpGet("error")] - public IActionResult Error() - { - return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); - } - - /// - /// Displays the view for errors. - /// - [HttpGet("not-found")] - public IActionResult NotFoundView() - { - return View("/Views/Shared/NotFound.cshtml"); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs deleted file mode 100644 index 57d511b9..00000000 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ /dev/null @@ -1,212 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Attributes; -using Lumina.Presentation.Web.Common.Enums.Authorization; -using Lumina.Presentation.Web.Common.Models.Common; -using Lumina.Presentation.Web.Common.Models.Libraries; -using Lumina.Presentation.Web.Common.Models.Plugins; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.Library.Management; - -/// -/// Controller for media libraries related operations. -/// -[Authorize] -[Route("{culture}/libraries/manage")] -public class LibraryManagementController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public LibraryManagementController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Displays the view for displaying the list of media libraries. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("")] - public IActionResult Index() - { - return View("/Views/Library/Management/Index.cshtml"); - } - - /// - /// Displays the view for adding a media library. - /// - [HttpGet("item")] - public IActionResult AddLibrary() - { - LibraryModel library = new(); - return View("/Views/Library/Management/Item.cshtml", library); - } - - /// - /// Displays the view for editing a media library. - /// - /// The id of the media library to edit. - /// Cancellation token that can be used to stop the execution. - [HttpGet("item/{id}")] - public async Task EditLibrary(Guid id, CancellationToken cancellationToken = default) - { - LibraryModel response = await _apiHttpClient.GetAsync($"libraries/{id}", cancellationToken).ConfigureAwait(false); - return View("/Views/Library/Management/Item.cshtml", response); - } - - /// - /// Gets the list of media libraries. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-libraries")] - public async Task GetLibraries(CancellationToken cancellationToken = default) - { - LibraryModel[] response = await _apiHttpClient.GetAsync($"libraries/", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Gets the list of enabled media libraries. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-enabled-libraries")] - public async Task GetEnabledLibraries(CancellationToken cancellationToken = default) - { - LibraryModel[] response = await _apiHttpClient.GetAsync($"libraries/enabled/", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Adds a new media library, or updates an existing one. - /// - /// The model containing the new library data. - /// Cancellation token that can be used to stop the execution. - [ValidateAntiForgeryToken] - [HttpPost("api-item")] - [RequirePermission(AuthorizationPermission.CanCreateLibraries)] - public async Task SaveLibrary([FromBody] LibraryModel data, CancellationToken cancellationToken) - { - // TODO: 1. this also needs to send the image files themselves to the API, since the server could be remote; for now, it assumes local paths which it can later read, which works only if the server is local too - // call different API endpoints based on whether this is a new library or an existing one - LibraryModel response = data.Id.HasValue - ? await _apiHttpClient.PutAsync($"libraries/{data.Id}", data, cancellationToken).ConfigureAwait(false) - : await _apiHttpClient.PostAsync("libraries", data, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Deletes a media library. - /// - /// The id of the media library to delete. - /// Cancellation token that can be used to stop the execution. - [HttpDelete("api-item/{id}")] - public async Task DeleteLibrary(Guid id, CancellationToken cancellationToken = default) - { - await _apiHttpClient.DeleteAsync($"libraries/{id}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true }); - } - - /// - /// Gets the list of ongoing media library scans. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-running-library-scans")] - public async Task GetRunningLibraryScans(CancellationToken cancellationToken = default) - { - LibraryScanProgressModel[] response = await _apiHttpClient.GetAsync($"libraries/scans/running/", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Initiates the scan of all media libraries. - /// - /// Cancellation token that can be used to stop the execution. - [HttpPost("api-scan-libraries")] - public async Task ScanAllLibraries(CancellationToken cancellationToken = default) - { - ScanLibraryModel[] response = await _apiHttpClient.PostAsync($"libraries/scans", new EmptyModel(), cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Initiates the scan of a media library. - /// - /// The id of the media library whose scan is started. - /// Cancellation token that can be used to stop the execution. - [HttpPost("api-scan-library/{id}")] - public async Task ScanLibrary(Guid id, CancellationToken cancellationToken = default) - { - ScanLibraryModel response = await _apiHttpClient.PostAsync($"libraries/{id}/scans", new EmptyModel(), cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Cancels the previously started scan of all media libraries. - /// - /// Cancellation token that can be used to stop the execution. - [HttpPost("api-cancel-libraries-scan")] - public async Task CancelLibrariesScan(CancellationToken cancellationToken = default) - { - await _apiHttpClient.PostAsync($"libraries/scans/cancel", new EmptyModel(), cancellationToken).ConfigureAwait(false); - return Json(new { success = true }); - } - - /// - /// Cancels the previously started scan of a media library. - /// - /// The id of the media library whose scan is cancelled. - /// The id of the scan to cancel. - /// Cancellation token that can be used to stop the execution. - [HttpPost("{libraryId:guid}/api-cancel-library-scan/{scanId:guid}")] - public async Task CancelLibraryScan(Guid libraryId, Guid scanId, CancellationToken cancellationToken = default) - { - await _apiHttpClient.PostAsync($"libraries/{libraryId}/scans/{scanId}/cancel", new EmptyModel(), cancellationToken).ConfigureAwait(false); - return Json(new { success = true }); - } - - /// - /// Gets the metadata providers configured for the media library identified by . - /// - /// The id of the media library whose metadata providers are retrieved. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-metadata-providers/{libraryId}")] - public async Task GetMetadataProviders(Guid libraryId, CancellationToken cancellationToken = default) - { - LibraryMetadataProviderModel[] response = await _apiHttpClient.GetAsync($"libraries/{libraryId}/metadata-providers", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Enables or disables the metadata provider for the media library described by . - /// - /// The model containing the Ids of the media library and of the metadata provider. - /// Cancellation token that can be used to stop the execution. - [HttpPut("api-set-metadata-provider-enabled")] - public async Task SetMetadataProviderEnabled([FromBody] SetLibraryMetadataProviderEnabledModel model, CancellationToken cancellationToken = default) - { - await _apiHttpClient.PutAsync($"libraries/{model.LibraryId}/metadata-providers/{model.PluginId}/enabled", model, cancellationToken).ConfigureAwait(false); - return Json(new { success = true }); - } - - /// - /// Reorders the metadata providers of the media library described by . - /// - /// The model containing the Id of the media library and the plugin Ids in the new order. - /// Cancellation token that can be used to stop the execution. - [HttpPut("api-reorder-metadata-providers")] - public async Task ReorderMetadataProviders([FromBody] ReorderLibraryMetadataProvidersModel model, CancellationToken cancellationToken = default) - { - await _apiHttpClient.PutAsync($"libraries/{model.LibraryId}/metadata-providers/reorder", model, cancellationToken).ConfigureAwait(false); - return Json(new { success = true }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs b/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs deleted file mode 100644 index fa138956..00000000 --- a/src/Lumina.Presentation.Web/Controllers/Library/WrittenContentLibrary/BookLibrary/BooksController.cs +++ /dev/null @@ -1,92 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.Libraries; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.Library.WrittenContentLibrary.BookLibrary; - -/// -/// Controller for books related operations. -/// -[Authorize] -[Route("{culture}/library/written-content-library/books-library/books")] -public class BooksController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public BooksController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Displays the view for browsing the books of a media library. - /// - /// The Id of the media library whose books are browsed. - /// Cancellation token that can be used to stop the execution. - [HttpGet("")] - public async Task Index(Guid? libraryId, CancellationToken cancellationToken = default) - { - if (libraryId is null) - return RedirectToAction("Index", "Home"); - - LibraryModel library = await _apiHttpClient.GetAsync($"libraries/{libraryId}", cancellationToken).ConfigureAwait(false); - return View("/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml", library); - } - - /// - /// Gets the lightweight details of the books of a media library. - /// - /// The model containing the parameters used to retrieve the books. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-library-items")] - public async Task GetLibraryItems([FromQuery] BookLibraryItemsQueryModel query, CancellationToken cancellationToken = default) - { - PaginatedBookLiteModel response = await _apiHttpClient.GetAsync(BuildItemsEndpoint(query), cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Displays the view for a single book. - /// - /// The Id of the book to display. - [HttpGet("{id}")] - public IActionResult EditBook(Guid id) - { - return View("/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml"); - } - - /// - /// Builds the API endpoint used to retrieve the lightweight details of the books of a media library, from the provided . - /// - /// The model containing the parameters used to retrieve the books. - /// The API endpoint to which the retrieval request is sent. - private static string BuildItemsEndpoint(BookLibraryItemsQueryModel query) - { - StringBuilder endpoint = new($"books/lite?libraryId={query.LibraryId}"); - if (query.CurrentPage is not null) - endpoint.Append($"¤tPage={query.CurrentPage}"); - if (query.PerPage is not null) - endpoint.Append($"&perPage={query.PerPage}"); - if (!string.IsNullOrWhiteSpace(query.SearchTerm)) - endpoint.Append($"&searchTerm={Uri.EscapeDataString(query.SearchTerm)}"); - if (!string.IsNullOrWhiteSpace(query.FilterAlphaKey)) - endpoint.Append($"&filterAlphaKey={Uri.EscapeDataString(query.FilterAlphaKey)}"); - endpoint.Append($"&ignoreThePrefixForAlphaPicker={query.IgnoreThePrefixForAlphaPicker}"); - if (!string.IsNullOrWhiteSpace(query.SortBy)) - endpoint.Append($"&sortBy={Uri.EscapeDataString(query.SortBy)}"); - if (query.SortOrder is not null) - endpoint.Append($"&sortOrder={query.SortOrder}"); - return endpoint.ToString(); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/Plugins/PluginsController.cs b/src/Lumina.Presentation.Web/Controllers/Plugins/PluginsController.cs deleted file mode 100644 index 4bfaff8b..00000000 --- a/src/Lumina.Presentation.Web/Controllers/Plugins/PluginsController.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Attributes; -using Lumina.Presentation.Web.Common.Enums.Plugins; -using Lumina.Presentation.Web.Common.Models.Common; -using Lumina.Presentation.Web.Common.Models.Plugins; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.Plugins; - -/// -/// Controller for the plugin management related operations. -/// -[Authorize] -[RequireRole("Admin")] -[Route("{culture}/plugins")] -public class PluginsController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public PluginsController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Displays the view for managing the plugins and their settings. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("")] - public async Task Index(CancellationToken cancellationToken) - { - PluginModel[] plugins = await _apiHttpClient.GetAsync("plugins", cancellationToken).ConfigureAwait(false); - - // load the settings of the loaded plugins, so that the settings forms can be rendered on the server - Dictionary settingsByPluginId = []; - foreach (PluginModel plugin in plugins) - if (plugin.LoadStatus == PluginLoadStatus.Loaded) - settingsByPluginId[plugin.Id] = await _apiHttpClient.GetAsync($"plugins/{plugin.Id}/settings", cancellationToken).ConfigureAwait(false); - - ViewData["pluginSettings"] = settingsByPluginId; - return View(plugins); - } - - /// - /// Gets the list of the detected plugins. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-plugins")] - public async Task GetPlugins(CancellationToken cancellationToken = default) - { - PluginModel[] response = await _apiHttpClient.GetAsync("plugins/", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Gets the settings and their schema of the plugin identified by . - /// - /// The unique identifier of the plugin. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-plugin-settings/{pluginId}")] - public async Task GetPluginSettings(Guid pluginId, CancellationToken cancellationToken = default) - { - PluginSettingsModel response = await _apiHttpClient.GetAsync($"plugins/{pluginId}/settings", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Updates the settings of the plugin identified by . - /// - /// The model containing the Id of the plugin and its settings. - /// Cancellation token that can be used to stop the execution. - [HttpPut("api-update-plugin-settings")] - public async Task UpdatePluginSettings([FromBody] UpdatePluginSettingsModel model, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync($"plugins/{model.PluginId}/settings", model, cancellationToken).ConfigureAwait(false); - return Json(new { success = true }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/Tools/LanguageController.cs b/src/Lumina.Presentation.Web/Controllers/Tools/LanguageController.cs deleted file mode 100644 index 6d40f560..00000000 --- a/src/Lumina.Presentation.Web/Controllers/Tools/LanguageController.cs +++ /dev/null @@ -1,72 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Services; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Localization; -using Microsoft.AspNetCore.Mvc; -using System; -#endregion - -namespace Lumina.Presentation.Web.Controllers.Tools; - -/// -/// Controller for language related operations. -/// -[Route("{culture}/tools/language")] -public class LanguageController : Controller -{ - private readonly IUrlService _urlService; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for generating URLs from action and controller names, with localization. - public LanguageController(IUrlService urlService) - { - _urlService = urlService; - } - - /// - /// Sets the culture used in the application. - /// - /// The new culture to set. - /// The URL to return to after setting the new culture. - [HttpGet("set-language")] - public IActionResult SetLanguage(string newCulture, string returnUrl) - { - // store culture preference in cookie - Response.Cookies.Append( - CookieRequestCultureProvider.DefaultCookieName, - CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(newCulture)), - new CookieOptions - { - Expires = DateTimeOffset.UtcNow.AddYears(1), - IsEssential = true, - SameSite = SameSiteMode.Lax, - Path = "/" // ensure cookie works across all paths - } - ); - // ensure returnUrl includes the correct culture - if (string.IsNullOrEmpty(returnUrl)) - returnUrl = _urlService.GetAbsoluteUrl("Index", "Home")!; // default fallback URL - // handle culture replacement in return URL - string? currentCulture = HttpContext.Request.RouteValues["culture"]?.ToString() ?? "en-us"; - if (currentCulture != null) - { - // ensure we handle both with and without trailing slashes - string culturePath = $"/{currentCulture.ToLower()}/"; - string newCulturePath = $"/{newCulture.ToLower()}/"; - - // Handle base path if present - if (!string.IsNullOrEmpty(Request.PathBase)) - returnUrl = returnUrl.Replace(Request.PathBase.Value!, "", StringComparison.OrdinalIgnoreCase); - // replace culture in URL - returnUrl = returnUrl.Replace(culturePath, newCulturePath, StringComparison.OrdinalIgnoreCase); - - // re-apply base path if present - if (!string.IsNullOrEmpty(Request.PathBase)) - returnUrl = Request.PathBase.Value + returnUrl; - } - // redirect to the original page - return LocalRedirect(returnUrl); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/Tools/SettingsController.cs b/src/Lumina.Presentation.Web/Controllers/Tools/SettingsController.cs deleted file mode 100644 index c61b2196..00000000 --- a/src/Lumina.Presentation.Web/Controllers/Tools/SettingsController.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Models.Common; -using Lumina.Presentation.Web.Common.Models.UsersManagement; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.Tools; - -/// -/// Controller for the settings of the current user. -/// -[Authorize] -[Route("{culture}/tools/settings")] -public class SettingsController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public SettingsController(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Displays the view for editing the settings of the current user. - /// - [HttpGet("")] - public IActionResult Index() - { - UserSettingsModel settings = new(); - return View("/Views/Tools/Settings.cshtml", settings); - } - - /// - /// Gets the settings of the current user. - /// - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-user-settings")] - public async Task GetUserSettings(CancellationToken cancellationToken = default) - { - UserSettingsModel response = await _apiHttpClient.GetAsync("users/me/settings", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Updates the settings of the current user. - /// - /// The model containing the new settings of the current user. - /// Cancellation token that can be used to stop the execution. - [ValidateAntiForgeryToken] - [HttpPost("api-update-user-settings")] - public async Task UpdateUserSettings([FromBody] UserSettingsModel data, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync("users/me/settings", data, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = new { isUpdated = true } }); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs b/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs deleted file mode 100644 index 59b689de..00000000 --- a/src/Lumina.Presentation.Web/Controllers/UsersManagement/AuthController.cs +++ /dev/null @@ -1,260 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Exceptions; -using Lumina.Presentation.Web.Common.Filters.ActionFilters; -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.Logging; -using Microsoft.Extensions.Primitives; -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Controllers.UsersManagement; - -/// -/// Controller for authentication related operations. -/// -[Authorize] -[Route("{culture}/auth")] -public class AuthController : Controller -{ - private readonly IApiHttpClient _apiHttpClient; - private readonly ICryptographyService _cryptographyService; - private readonly IUrlService _urlService; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - /// Injected service for cryptographic functionality. - /// Injected service for generating URLs from action and controller names, with localization. - public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService, IUrlService urlService) - { - _apiHttpClient = apiHttpClient; - _cryptographyService = cryptographyService; - _urlService = urlService; - } - - /// - /// Displays the view for registering a new account. - /// - [AllowAnonymous] - [InitializationCheck] - [HttpGet("register")] - public IActionResult Register() - { - // check if this is the initial super admin setup - string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); - ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User"; - return View(); - } - - /// - /// Displays the view for logging in. - /// - /// The url to return to, after login (if any). - [AllowAnonymous] - [InitializationCheck] - [HttpGet("login/{returnUrl?}")] - public IActionResult Login(string? returnUrl = null) - { - ViewData["ReturnUrl"] = returnUrl; - // if the user is already logged in, redirect them to the home page - if (User?.Identity?.IsAuthenticated == true) - 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 Redirect(_urlService.GetAbsoluteUrl("Register", "Auth")!); - return View(new LoginRequestModel()); - } - - /// - /// Displays the view for recovering the password of an account. - /// - [AllowAnonymous] - [InitializationCheck] - [HttpGet("recover-password")] - public IActionResult RecoverPassword() - { - // if the user is already logged in, redirect them to the home page - if (User?.Identity?.IsAuthenticated == true) - return Redirect(_urlService.GetAbsoluteUrl("Index", "Home")!); - return View(); - } - - /// - /// Displays the view for changing the password of an account. - /// - [HttpGet("change-password")] - public IActionResult ChangePassword() - { - return View(); - } - - /// - /// Displays the view for registering a new account. - /// - [HttpGet("profile")] - public IActionResult Profile() - { - return View(); - } - - /// - /// Displays the view for registering a new account. - /// - [AllowAnonymous] - [HttpGet("access-denied")] - public IActionResult AccessDenied() - { - return View(); - } - - /// - /// Registers a new account. - /// - /// User credentials used for registration. - /// Cancellation token that can be used to stop the execution. - [AllowAnonymous] - [ValidateAntiForgeryToken] - [HttpPost("api-register")] - public async Task RegisterPost([FromBody] RegisterRequestModel data, CancellationToken cancellationToken) - { - // call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup - string endpoint = data.RegistrationType == "Admin" ? "initialization" : "auth/register"; - // attempt API registration - RegisterResponseModel response = await _apiHttpClient.PostAsync(endpoint, data, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Logs in an account. - /// - /// User credentials used for login. - /// Cancellation token that can be used to stop the execution. - [AllowAnonymous] - [ValidateAntiForgeryToken] - [HttpPost("api-login")] - public async Task LoginPost([FromBody] LoginRequestModel data, CancellationToken cancellationToken) - { - try - { - // attempt API registration - LoginResponseModel response = await _apiHttpClient.PostAsync("auth/login", data, cancellationToken).ConfigureAwait(false); - // store the received token in a secure cookie - Response.Cookies.Delete("Token"); - Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions - { - Expires = DateTimeOffset.UtcNow.AddMonths(1), - Path = "/", - HttpOnly = true, - Secure = true, - IsEssential = true, - SameSite = SameSiteMode.Strict - }); - // tell asp.net we are logged in - List claims = - [ - new Claim(ClaimTypes.Name, response.Username!), - new Claim(ClaimTypes.NameIdentifier, response.Id.ToString()!), - new Claim("Token", response.Token!), - ]; - ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); - 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 = redirectUrl }); - } - catch (ApiException ex) - { - // in this particular case, we DO NOT want to let the ApiExceptionFilter take care of this exception, because when the user has 2FA enabled, the first auth step involves sending - // only the username and password, in which case the server API will respond with a validation error, that TOTP code is not valid (empty); it is then that we catch this error here - // and display the form that asks the user for the TOTP code - if (ex.ProblemDetails is not null && ex.ProblemDetails.Extensions?.Count > 0 && ex.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj)) - if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object) - foreach (JsonProperty error in jsonElement.EnumerateObject()) - if (error.Value.ValueKind == JsonValueKind.Array) - foreach (JsonElement errorValue in error.Value.EnumerateArray()) - if (errorValue.ValueKind == JsonValueKind.String && errorValue.GetString() == "InvalidTotpCode" && string.IsNullOrEmpty(data.TotpCode)) - return Json(new { success = true, data = new { isTotpRequired = true } }); // only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error - throw; - } - } - - /// - /// Logs out an account and redirects to the login page. - /// - [HttpGet("logout")] - public async Task Logout() - { - // if the user is not logged in, redirect them to the home page - if (User?.Identity?.IsAuthenticated == false) - return Redirect(_urlService.GetAbsoluteUrl("Index", "Home")!); - Response.Cookies.Delete("Token"); - await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false); - return Redirect(_urlService.GetAbsoluteUrl("Login", "Auth")!); - } - - /// - /// Recovers the password of an account. - /// - /// User credentials used for password recovery. - /// Cancellation token that can be used to stop the execution. - [AllowAnonymous] - [ValidateAntiForgeryToken] - [HttpPost("api-recover-password")] - public async Task RecoverPasswordPost([FromBody] RecoverPasswordRequestModel data, CancellationToken cancellationToken) - { - RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync("auth/recover-password", data, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Changes the password of an account. - /// - /// User credentials used for password change. - /// Cancellation token that can be used to stop the execution. - [ValidateAntiForgeryToken] - [HttpPost("api-change-password")] - public async Task ChangePasswordPost([FromBody] ChangePasswordRequestModel data, CancellationToken cancellationToken) - { - data = data with { Username = User?.Identity?.Name }; // assign the currently logged in user as the user for which to change the password - ChangePasswordResponseModel response = await _apiHttpClient.PostAsync("auth/change-password", data, cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs new file mode 100644 index 00000000..24c559d0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; + +/// +/// API endpoint for the /{culture}/admin/api-create-role route. +/// +public class AddRoleEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddRoleEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Admin.CREATE_ROLE); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Adds an authorization role. + /// + /// The request containing the details of the authorization role to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddRoleRequest request, CancellationToken cancellationToken) + { + RolePermissionsDto response = await _apiHttpClient.PostAsync(ApiRoutes.Roles.CREATE_ROLE, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointSummary.cs new file mode 100644 index 00000000..d0ce5710 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddRoleEndpointSummary() + { + Summary = "Adds a new role."; + Description = "Creates a new authorization role with the specified permissions."; + RequestParam(r => r.RoleName, "The name of the role. Required."); + RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Required."); + + ExampleRequest = new AddRoleRequest( + RoleName: "Editor", + Permissions: [ + Guid.NewGuid(), + Guid.NewGuid(), + ] + ); + + Response(200, "The role is created.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs new file mode 100644 index 00000000..d88725ac --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// API endpoint for the /{culture}/admin/api-delete-role/{roleId} route. +/// +public class DeleteRoleEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DeleteRoleEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Admin.DELETE_ROLE); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Deletes the authorization role identified by the request. + /// + /// The request containing the unique identifier of the authorization role to delete. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteRoleRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.DeleteAsync(ApiRoutes.Roles.DELETE_ROLE.Replace("{roleId}", request.RoleId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs new file mode 100644 index 00000000..22a50431 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteRoleEndpointSummary() + { + Summary = "Deletes a role."; + Description = "Deletes an existing authorization role identified by its unique identifier."; + + RequestParam(r => r.RoleId, "The unique identifier of the role to delete."); + + Response(200, "The role is deleted.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs new file mode 100644 index 00000000..dbaccd27 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// API endpoint for the /{culture}/admin/api-get-permissions-by-role-id/{roleId} route. +/// +public class GetRolePermissionsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetRolePermissionsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Admin.GET_PERMISSIONS_BY_ROLE_ID); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the permissions of the authorization role identified by the request. + /// + /// The request containing the unique identifier of the role whose permissions are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetRolePermissionsRequest request, CancellationToken cancellationToken) + { + RolePermissionsDto response = await _apiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLE_PERMISSIONS_BY_ROLE_ID.Replace("{roleId}", request.RoleId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs new file mode 100644 index 00000000..759f99f4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetRolePermissionsEndpointSummary() + { + Summary = "Gets the permissions of a role."; + Description = "Retrieves the permissions of an existing authorization role identified by its unique identifier."; + + RequestParam(r => r.RoleId, "The unique identifier of the role whose permissions are retrieved."); + + Response(200, "The permissions of the role are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs new file mode 100644 index 00000000..940c1420 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// API endpoint for the /{culture}/admin/api-get-roles route. +/// +public class GetRolesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetRolesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Admin.GET_ROLES); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the authorization roles. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + RoleDto[] roles = await _apiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLES, cancellationToken).ConfigureAwait(false); + return JsonSuccess(roles); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs new file mode 100644 index 00000000..12eb37e9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.Common; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetRolesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetRolesEndpointSummary() + { + Summary = "Gets all roles."; + Description = "Retrieves the collection of existing authorization roles."; + + Response(200, "The collection of authorization roles is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs new file mode 100644 index 00000000..a5dd223e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; + +/// +/// API endpoint for the /{culture}/admin/api-update-role route. +/// +public class UpdateRoleEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdateRoleEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Admin.UPDATE_ROLE); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Updates an existing authorization role. + /// + /// The request containing the updated details of the authorization role. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateRoleRequest request, CancellationToken cancellationToken) + { + RolePermissionsDto response = await _apiHttpClient.PutAsync(ApiRoutes.Roles.UPDATE_ROLE, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs new file mode 100644 index 00000000..d514eb18 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateRoleEndpointSummary() + { + Summary = "Updates a role."; + Description = "Updates the name and the permissions of an existing authorization role."; + RequestParam(r => r.RoleId, "The unique identifier of the role. Required."); + RequestParam(r => r.RoleName, "The name of the role. Required."); + RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Required."); + + ExampleRequest = new UpdateRoleRequest( + RoleId: Guid.NewGuid(), + RoleName: "Editor", + Permissions: [ + Guid.NewGuid(), + Guid.NewGuid(), + ] + ); + + Response(200, "The role is updated.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpoint.cs new file mode 100644 index 00000000..4bcc95a4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.ManagePermissions; + +/// +/// API endpoint for the /{culture}/admin/manage-permissions route. +/// +public class ManagePermissionsViewEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ManagePermissionsViewEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Admin.MANAGE_PERMISSIONS); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Displays the authorization permissions management view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + UserDto[] users = await _apiHttpClient.GetAsync(ApiRoutes.Authentication.USERS, cancellationToken).ConfigureAwait(false); + RoleDto[] roles = await _apiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLES, cancellationToken).ConfigureAwait(false); + PermissionDto[] permissions = await _apiHttpClient.GetAsync(ApiRoutes.Permissions.GET_PERMISSIONS, cancellationToken).ConfigureAwait(false); + Dictionary viewData = new() { ["users"] = users, ["roles"] = roles, ["permissions"] = permissions }; + return View("/Core/Views/Admin/ManagePermissions.cshtml", viewData: viewData); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointSummary.cs new file mode 100644 index 00000000..abe4724f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.ManagePermissions; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ManagePermissionsViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ManagePermissionsViewEndpointSummary() + { + Summary = "Renders the manage permissions view."; + Description = "Renders the view for managing the authorization permissions."; + + Response(200, "The view for managing the authorization permissions is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpoint.cs new file mode 100644 index 00000000..3203bd0c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.ManageRoles; + +/// +/// API endpoint for the /{culture}/admin/manage-roles route. +/// +public class ManageRolesViewEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ManageRolesViewEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Admin.MANAGE_ROLES); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Displays the authorization roles management view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + RoleDto[] roles = await _apiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLES, cancellationToken).ConfigureAwait(false); + PermissionDto[] permissions = await _apiHttpClient.GetAsync(ApiRoutes.Permissions.GET_PERMISSIONS, cancellationToken).ConfigureAwait(false); + Dictionary viewData = new() { ["roles"] = roles, ["permissions"] = permissions }; + return View("/Core/Views/Admin/ManageRoles.cshtml", viewData: viewData); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointSummary.cs new file mode 100644 index 00000000..91bca01d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.ManageRoles; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ManageRolesViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ManageRolesViewEndpointSummary() + { + Summary = "Renders the manage roles view."; + Description = "Renders the view for managing the authorization roles."; + + Response(200, "The view for managing the authorization roles is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs new file mode 100644 index 00000000..65bced26 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; + +/// +/// API endpoint for the /{culture}/admin/api-get-permissions-by-user-id/{userId} route. +/// +public class GetUserPermissionsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetUserPermissionsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Admin.GET_PERMISSIONS_BY_USER_ID); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the permissions of the user identified by the request. + /// + /// The request containing the unique identifier of the user whose permissions are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetUserPermissionsRequest request, CancellationToken cancellationToken) + { + PermissionDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Authorization.GET_USER_PERMISSIONS_BY_USER_ID.Replace("{userId}", request.UserId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs new file mode 100644 index 00000000..d9646c0e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserPermissionsEndpointSummary() + { + Summary = "Gets the permissions of a user."; + Description = "Retrieves the authorization permissions of a user identified by its unique identifier."; + + RequestParam(r => r.UserId, "The unique identifier of the user for whom to get the authorization permissions."); + + Response(200, "The permissions of the user are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs new file mode 100644 index 00000000..872fb48c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; + +/// +/// API endpoint for the /{culture}/admin/api-get-role-by-user-id/{userId} route. +/// +public class GetUserRoleEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetUserRoleEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Admin.GET_ROLE_BY_USER_ID); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the authorization role of the user identified by the request. + /// + /// The request containing the unique identifier of the user whose authorization role is retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetUserRoleRequest request, CancellationToken cancellationToken) + { + RoleDto? response = await _apiHttpClient.GetAsync(ApiRoutes.Authorization.GET_USER_ROLE_BY_USER_ID.Replace("{userId}", request.UserId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs new file mode 100644 index 00000000..4711f3e7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserRoleEndpointSummary() + { + Summary = "Gets the role of a user."; + Description = "Retrieves the authorization role of a user identified by its unique identifier."; + + RequestParam(r => r.UserId, "The unique identifier of the user for whom to get the authorization role."); + + Response(200, "The role of the user is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs new file mode 100644 index 00000000..4d9fdfb4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// API endpoint for the /{culture}/admin/api-update-user-authorization route. +/// +public class UpdateUserRoleAndPermissionsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdateUserRoleAndPermissionsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Admin.UPDATE_USER_AUTHORIZATION); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Updates the authorization role and permissions of the user identified by the request. + /// + /// The request containing the updated authorization role and permissions of the user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateUserRoleAndPermissionsRequest request, CancellationToken cancellationToken) + { + GetAuthorizationResponse response = await _apiHttpClient.PutAsync(ApiRoutes.Authorization.UPDATE_USER_ROLE_AND_PERMISSIONS_BY_USER_ID.Replace("{userId}", request.UserId.ToString()), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs new file mode 100644 index 00000000..1bfb975a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateUserRoleAndPermissionsEndpointSummary() + { + Summary = "Updates the role and the permissions of a user."; + Description = "Updates the authorization role and the permissions of a user identified by its unique identifier."; + RequestParam(r => r.UserId, "The unique identifier of the user. Required."); + RequestParam(r => r.RoleId, "The unique identifier of the role. Optional."); + RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Optional."); + + ExampleRequest = new UpdateUserRoleAndPermissionsRequest( + UserId: Guid.NewGuid(), + RoleId: Guid.NewGuid(), + Permissions: [ + Guid.NewGuid(), + Guid.NewGuid(), + ] + ); + + Response(200, "The role and the permissions of the user are updated.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs new file mode 100644 index 00000000..62ca2828 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Http; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Common; + +/// +/// Base class for Web endpoints. +/// +/// The type of the request object. +/// The type of the response object. +public abstract class BaseEndpoint : Endpoint where TRequest : notnull + where TResponse : notnull +{ + /// + /// Gets the current culture taken from the culture route value. + /// + protected string Culture => HttpContext.Request.RouteValues["culture"]?.ToString() ?? "en-US"; + + /// + /// Configures the endpoint. + /// + /// + /// All exceptions are propagated to the application's exception handling middleware instead of being converted to error responses by the library. + /// + public override void Configure() + { + DontCatchExceptions(); + } + + /// + /// Renders a Razor view to the response. + /// + /// The name or path of the view to render. + /// The model to pass to the view. + /// Optional additional view data entries made available to the view via ViewData. + /// An that renders the view. + protected IResult View(string viewName, object? model = null, IReadOnlyDictionary? viewData = null) + { + // store the path of the displayed view in the session, so that the login redirect after the JWT token expires points to it; ignore the login endpoint, + // because it is incorrect to be redirected to the login URL, with the login URL as the return URL + if (HttpContext.Request.Path != "/en-us/auth/login") + HttpContext.Session.SetString(HttpContextItemKeys.LAST_DISPLAYED_VIEW, $"{HttpContext.Request.PathBase}{HttpContext.Request.Path}{HttpContext.Request.QueryString}"); + return new RazorViewResult(viewName, model, viewData); + } + + /// + /// Creates a JSON response indicating a successful operation, optionally wrapping . + /// + /// The payload of the successful response. + /// An containing the success JSON payload. + protected IResult JsonSuccess(object? data) + { + return Results.Json(new { success = true, data }); + } + + /// + /// Creates a JSON response indicating a successful operation without a payload. + /// + /// An containing the success JSON payload. + protected IResult JsonSuccess() + { + return Results.Json(new { success = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs new file mode 100644 index 00000000..4ef4680a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// API endpoint for the /directories/api-get-directories route. +/// +public class GetDirectoriesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetDirectoriesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Directories.GET_DIRECTORIES); + DontAutoTag(); + Options(options => options.WithTags("Directories")); + } + + /// + /// Retrieves the directories of the file system path identified by the request. + /// + /// The request containing the file system path whose directories are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetDirectoriesRequest request, CancellationToken cancellationToken) + { + DirectoryDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs new file mode 100644 index 00000000..acdde3fd --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesEndpointSummary() + { + Summary = "Retrieves the directories of a file system path."; + Description = "Retrieves the directories of the file system path identified by the request."; + + RequestParam(r => r.Path, "The file system path for which to get the directories."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response(200, "The directories of the file system path are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs new file mode 100644 index 00000000..e113f456 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Drives.GetDrives; + +/// +/// API endpoint for the /drives/api-get-drives route. +/// +public class GetDrivesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetDrivesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Drives.GET_DRIVES); + DontAutoTag(); + Options(options => options.WithTags("Drives")); + } + + /// + /// Retrieves the file system drives. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + FileSystemTreeNodeDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Drives.GET_DRIVES, cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { drives = response }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs new file mode 100644 index 00000000..15107bd2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Drives.GetDrives; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDrivesEndpointSummary() + { + Summary = "Retrieves the file system drives."; + Description = "Retrieves the list of file system drives of the machine."; + + Response(200, "The list of file system drives is returned.", example: new { success = true, data = new { drives = new FileSystemTreeNodeDto[] { } } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs new file mode 100644 index 00000000..bb304648 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.FileSystem.GetType; + +/// +/// API endpoint for the /file-system/api-get-type route. +/// +public class GetTypeEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetTypeEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.FileSystem.GET_TYPE); + DontAutoTag(); + Options(options => options.WithTags("FileSystem")); + } + + /// + /// Retrieves the file system platform type. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + FileSystemTypeDto response = await _apiHttpClient.GetAsync(ApiRoutes.FileSystem.GET_TYPES, cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { platformType = response.PlatformType.ToString() }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs new file mode 100644 index 00000000..c56308e2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.FileSystem.GetType; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTypeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTypeEndpointSummary() + { + Summary = "Retrieves the file system platform type."; + Description = "Retrieves the platform type of the file system of the machine."; + + Response(200, "The type of the file system is returned.", example: new { success = true, data = new { platformType = "Windows" } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs new file mode 100644 index 00000000..3339abf9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// API endpoint for the /files/api-get-files route. +/// +public class GetFilesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetFilesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Files.GET_FILES); + DontAutoTag(); + Options(options => options.WithTags("Files")); + } + + /// + /// Retrieves the files of the file system path identified by the request. + /// + /// The request containing the file system path whose files are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetFilesRequest request, CancellationToken cancellationToken) + { + FileDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Files.GET_FILES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs new file mode 100644 index 00000000..b1f4bbb7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetFilesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetFilesEndpointSummary() + { + Summary = "Retrieves the files of a file system path."; + Description = "Retrieves the files of the file system path identified by the request."; + + RequestParam(r => r.Path, "The file system path for which to get the files."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response(200, "The files of the file system path are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs new file mode 100644 index 00000000..983877ef --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; + +/// +/// API endpoint for the /files/api-get-tree-files route. +/// +public class GetTreeFilesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetTreeFilesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Files.GET_TREE_FILES); + DontAutoTag(); + Options(options => options.WithTags("Files")); + } + + /// + /// Retrieves the file system tree of the file system path identified by the request. + /// + /// The request containing the file system path whose file system tree is retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetTreeFilesRequest request, CancellationToken cancellationToken) + { + FileSystemTreeNodeDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Files.GET_TREE_FILES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs new file mode 100644 index 00000000..da341087 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTreeFilesEndpointSummary() + { + Summary = "Retrieves the file system tree of a file system path."; + Description = "Retrieves the file system tree of the file system path identified by the request."; + + RequestParam(r => r.Path, "The file system path for which to get the tree files."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + + Response(200, "The file system tree of the file system path is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs new file mode 100644 index 00000000..db41a478 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// API endpoint for the /path/api-check-path-exists route. +/// +public class CheckPathExistsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public CheckPathExistsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Path.CHECK_PATH_EXISTS); + DontAutoTag(); + Options(options => options.WithTags("Path")); + } + + /// + /// Checks whether the file system path identified by the request exists. + /// + /// The request containing the file system path whose existence is checked. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken) + { + PathExistsDto response = await _apiHttpClient.GetAsync($"{ApiRoutes.Path.CHECK_PATH_EXISTS}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { exists = response.Exists }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs new file mode 100644 index 00000000..6868b07c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsEndpointSummary() + { + Summary = "Checks the existence of a file system path."; + Description = "Checks whether the file system path identified by the request exists."; + + RequestParam(r => r.Path, "The file system path to check the existence of."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not."); + + Response(200, "Whether the file system path exists is returned.", example: new { success = true, data = new { exists = true } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs new file mode 100644 index 00000000..b98013d9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// API endpoint for the /path/api-get-path-parent route. +/// +public class GetPathParentEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPathParentEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Path.GET_PATH_PARENT); + DontAutoTag(); + Options(options => options.WithTags("Path")); + } + + /// + /// Retrieves the parent path of the file system path identified by the request. + /// + /// The request containing the file system path whose parent path is retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPathParentRequest request, CancellationToken cancellationToken) + { + PathSegmentDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Path.GET_PATH_PARENT}?path={Uri.EscapeDataString(request.Path!)}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { pathSegments = response }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs new file mode 100644 index 00000000..8403b28e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPathParentEndpointSummary() + { + Summary = "Retrieves the parent path of a file system path."; + Description = "Retrieves the path segments of the parent path of the file system path identified by the request."; + + RequestParam(r => r.Path, "The path for which the parent path is retrieved."); + + Response(200, "The path segments of the parent path are returned.", example: new { success = true, data = new { pathSegments = new PathSegmentDto[] { } } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs new file mode 100644 index 00000000..0b053d0f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// API endpoint for the /path/api-get-path-root route. +/// +public class GetPathRootEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPathRootEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Path.GET_PATH_ROOT); + DontAutoTag(); + Options(options => options.WithTags("Path")); + } + + /// + /// Retrieves the root of the file system path identified by the request. + /// + /// The request containing the file system path whose root is retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPathRootRequest request, CancellationToken cancellationToken) + { + PathSegmentDto response = await _apiHttpClient.GetAsync($"{ApiRoutes.Path.GET_PATH_ROOT}?path={Uri.EscapeDataString(request.Path!)}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { root = response }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs new file mode 100644 index 00000000..19ffc881 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPathRootEndpointSummary() + { + Summary = "Retrieves the root of a file system path."; + Description = "Retrieves the root of the file system path identified by the request."; + + RequestParam(r => r.Path, "The file system path for which to get the root."); + + Response(200, "The root of the file system path is returned.", example: new { success = true, data = new { root = new PathSegmentDto() } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs new file mode 100644 index 00000000..d62c5666 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; + +/// +/// API endpoint for the /path/api-get-path-separator route. +/// +public class GetPathSeparatorEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPathSeparatorEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Path.GET_PATH_SEPARATOR); + DontAutoTag(); + Options(options => options.WithTags("Path")); + } + + /// + /// Retrieves the file system path separator. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + PathSeparatorDto response = await _apiHttpClient.GetAsync(ApiRoutes.Path.GET_PATH_SEPARATOR, cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { pathSeparator = response.Separator }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs new file mode 100644 index 00000000..a8c70ab7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPathSeparatorEndpointSummary() + { + Summary = "Retrieves the file system path separator."; + Description = "Retrieves the path separator of the file system of the machine."; + + Response(200, "The file system path separator is returned.", example: new { success = true, data = new { pathSeparator = "\\" } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs new file mode 100644 index 00000000..db585f37 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// API endpoint for the /path/api-split route. +/// +public class SplitPathEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public SplitPathEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Path.SPLIT_PATH); + DontAutoTag(); + Options(options => options.WithTags("Path")); + } + + /// + /// Splits the file system path identified by the request into its segments. + /// + /// The request containing the file system path to split. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SplitPathRequest request, CancellationToken cancellationToken) + { + PathSegmentDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Path.SPLIT}?path={Uri.EscapeDataString(request.Path!)}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { pathSegments = response }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs new file mode 100644 index 00000000..79708895 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SplitPathEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SplitPathEndpointSummary() + { + Summary = "Splits a file system path into its segments."; + Description = "Splits the file system path identified by the request into its path segments."; + + RequestParam(r => r.Path, "The file system path for which to get the path segments."); + + Response(200, "The path segments of the file system path are returned.", example: new { success = true, data = new { pathSegments = new PathSegmentDto[] { } } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs new file mode 100644 index 00000000..7adc0ffa --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// API endpoint for the /path/api-validate route. +/// +public class ValidatePathEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ValidatePathEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Path.VALIDATE_PATH); + DontAutoTag(); + Options(options => options.WithTags("Path")); + } + + /// + /// Validates the file system path identified by the request. + /// + /// The request containing the file system path to validate. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ValidatePathRequest request, CancellationToken cancellationToken) + { + PathValidDto response = await _apiHttpClient.GetAsync($"{ApiRoutes.Path.VALIDATE}?path={Uri.EscapeDataString(request.Path!)}", cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isValid = response.IsValid }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs new file mode 100644 index 00000000..d27cf78d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ValidatePathEndpointSummary() + { + Summary = "Validates a file system path."; + Description = "Validates the file system path identified by the request."; + + RequestParam(r => r.Path, "The file system path to validate."); + + Response(200, "Whether the file system path is valid is returned.", example: new { success = true, data = new { isValid = true } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeErrorEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeErrorEndpoint.cs new file mode 100644 index 00000000..48b3be2a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeErrorEndpoint.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// API endpoint for the /{culture}/error route. +/// +public class HomeErrorEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Home.ERROR); + DontAutoTag(); + Options(options => options.WithTags("Home")); + } + + /// + /// Displays the error page. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + ErrorViewDto errorViewDto = new() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }; + return Task.FromResult(View("/Core/Views/Shared/Error.cshtml", errorViewDto)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeErrorEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeErrorEndpointSummary.cs new file mode 100644 index 00000000..93cab65c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeErrorEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class HomeErrorEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public HomeErrorEndpointSummary() + { + Summary = "Renders the error view."; + Description = "Renders the error page of the application."; + + Response(200, "The error view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeIndexEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeIndexEndpoint.cs new file mode 100644 index 00000000..3650c1fc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeIndexEndpoint.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// API endpoint for the / and /{culture} routes. +/// +public class HomeIndexEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Home.INDEX, WebRoutes.Home.INDEX_CULTURED); + DontAutoTag(); + Options(options => options.WithTags("Home")); + } + + /// + /// Displays the home page. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Home/Index.cshtml")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeIndexEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeIndexEndpointSummary.cs new file mode 100644 index 00000000..ef423cbd --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeIndexEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class HomeIndexEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public HomeIndexEndpointSummary() + { + Summary = "Renders the home page."; + Description = "Renders the home page of the application."; + + Response(200, "The home page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs new file mode 100644 index 00000000..25e9853a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// API endpoint for the /{culture}/not-found route. +/// +public class HomeNotFoundViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Home.NOT_FOUND); + DontAutoTag(); + Options(options => options.WithTags("Home")); + } + + /// + /// Displays the not-found page. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Shared/NotFound.cshtml")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpointSummary.cs new file mode 100644 index 00000000..167bb51d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class HomeNotFoundViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public HomeNotFoundViewEndpointSummary() + { + Summary = "Renders the not-found view."; + Description = "Renders the page displayed when a requested resource is not found."; + + Response(200, "The not-found view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomePrivacyEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomePrivacyEndpoint.cs new file mode 100644 index 00000000..32059fb3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomePrivacyEndpoint.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// API endpoint for the /{culture}/privacy route. +/// +public class HomePrivacyEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Home.PRIVACY); + DontAutoTag(); + Options(options => options.WithTags("Home")); + } + + /// + /// Displays the privacy page. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Home/Privacy.cshtml")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomePrivacyEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomePrivacyEndpointSummary.cs new file mode 100644 index 00000000..c6f5d5fe --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomePrivacyEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Home; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class HomePrivacyEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public HomePrivacyEndpointSummary() + { + Summary = "Renders the privacy view."; + Description = "Renders the privacy policy page of the application."; + + Response(200, "The privacy view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs new file mode 100644 index 00000000..0396bf28 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; + +/// +/// API endpoint for the /{culture}/libraries/manage/item route. +/// +public class AddLibraryViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.ADD_LIBRARY); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Displays the media library adding view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + LibraryDto library = new(); + return Task.FromResult(View("/Core/Views/Library/Management/Item.cshtml", library)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointSummary.cs new file mode 100644 index 00000000..c47497e5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddLibraryViewEndpointSummary() + { + Summary = "Renders the add library view."; + Description = "Renders the view for adding a media library."; + + Response(200, "The view for adding a media library is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs new file mode 100644 index 00000000..fac161df --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-cancel-libraries-scan route. +/// +public class CancelLibrariesScanEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public CancelLibrariesScanEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.LibraryManagement.CANCEL_LIBRARIES_SCAN); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Cancels the running scans of all the media libraries. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PostAsync(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN, new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs new file mode 100644 index 00000000..f5abed3d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CancelLibrariesScanEndpointSummary() + { + Summary = "Cancels the scan of all the media libraries."; + Description = "Cancels the running scans of all the media libraries."; + + Response(200, "The scan of all media libraries is cancelled.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs new file mode 100644 index 00000000..e3ccb02d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// API endpoint for the /{culture}/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId} route. +/// +public class CancelLibraryScanEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public CancelLibraryScanEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.LibraryManagement.CANCEL_LIBRARY_SCAN); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Cancels a running scan of a media library. + /// + /// The request containing the Ids of the media library and of the scan to cancel. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PostAsync(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs new file mode 100644 index 00000000..eca5a54c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CancelLibraryScanEndpointSummary() + { + Summary = "Cancels the scan of a media library."; + Description = "Cancels a running scan of the media library identified by the request."; + + RequestParam(r => r.LibraryId, "The unique identifier of the media library whose scan is cancelled."); + RequestParam(r => r.ScanId, "The Id of the scan to cancel."); + + Response(200, "The scan of the media library is cancelled.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs new file mode 100644 index 00000000..b84ee688 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-item/{id} route. +/// +public class DeleteLibraryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DeleteLibraryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.LibraryManagement.DELETE_LIBRARY); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Deletes a media library. + /// + /// The request containing the Id of the media library to delete. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteLibraryRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.DeleteAsync(ApiRoutes.Libraries.DELETE_LIBRARY.Replace("{id}", request.Id.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs new file mode 100644 index 00000000..7b5d012d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteLibraryEndpointSummary() + { + Summary = "Deletes a media library."; + Description = "Deletes the media library identified by the request."; + + RequestParam(r => r.Id, "The unique identifier of the media library to delete."); + + Response(200, "The media library is deleted.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs new file mode 100644 index 00000000..b0106ea2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; + +/// +/// API endpoint for the /{culture}/libraries/manage/item/{id} route. +/// +public class EditLibraryViewEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public EditLibraryViewEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.EDIT_LIBRARY); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Displays the media library editing view. + /// + /// The request containing the Id of the media library to edit. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EditLibraryRequest request, CancellationToken cancellationToken) + { + LibraryDto library = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.Id.ToString()), cancellationToken).ConfigureAwait(false); + return View("/Core/Views/Library/Management/Item.cshtml", library); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs new file mode 100644 index 00000000..b4db6b5e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class EditLibraryViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public EditLibraryViewEndpointSummary() + { + Summary = "Renders the edit library view."; + Description = "Renders the view for editing the media library identified by the request."; + + RequestParam(r => r.Id, "The unique identifier of the media library to edit."); + + Response(200, "The view for editing the media library is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs new file mode 100644 index 00000000..44c011ff --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetEnabledLibraries; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-enabled-libraries route. +/// +public class GetEnabledLibrariesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetEnabledLibrariesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the enabled media libraries. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + LibraryDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_ENABLED_LIBRARIES, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointSummary.cs new file mode 100644 index 00000000..66e41840 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetEnabledLibraries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetEnabledLibrariesEndpointSummary() + { + Summary = "Retrieves the enabled media libraries."; + Description = "Retrieves the collection of enabled media libraries."; + + Response(200, "The collection of enabled media libraries is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs new file mode 100644 index 00000000..6faa7a4a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-libraries route. +/// +public class GetLibrariesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibrariesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARIES); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the media libraries. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + LibraryDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARIES, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointSummary.cs new file mode 100644 index 00000000..c6072e51 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibrariesEndpointSummary() + { + Summary = "Retrieves the media libraries."; + Description = "Retrieves the collection of media libraries."; + + Response(200, "The collection of media libraries is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..c5f67185 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetMetadataProviders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-metadata-providers/{libraryId} route. +/// +public class GetMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetMetadataProvidersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_METADATA_PROVIDERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the metadata providers of a media library. + /// + /// The request containing the Id of the media library whose metadata providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetMetadataProvidersRequest request, CancellationToken cancellationToken) + { + LibraryMetadataProviderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_METADATA_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..78d45f76 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetMetadataProviders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetMetadataProvidersEndpointSummary() + { + Summary = "Retrieves the metadata providers of a media library."; + Description = "Retrieves the metadata providers of the media library identified by the request."; + + RequestParam(r => r.LibraryId, "The unique identifier of the media library whose metadata providers are retrieved."); + + Response(200, "The metadata providers of the media library are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs new file mode 100644 index 00000000..676a5cea --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetRunningLibraryScans; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-running-library-scans route. +/// +public class GetRunningLibraryScansEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetRunningLibraryScansEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_RUNNING_LIBRARY_SCANS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the running media library scans. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + LibraryScanProgressDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_RUNNING_LIBRARIES_SCAN, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointSummary.cs new file mode 100644 index 00000000..a2f78a34 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetRunningLibraryScans; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetRunningLibraryScansEndpointSummary() + { + Summary = "Retrieves the running media library scans."; + Description = "Retrieves the collection of ongoing media library scans."; + + Response(200, "The collection of ongoing media library scans is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs new file mode 100644 index 00000000..f553d0eb --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; + +/// +/// API endpoint for the /{culture}/libraries/manage route. +/// +public class LibrariesIndexViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Displays the media libraries management view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Library/Management/Index.cshtml")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointSummary.cs new file mode 100644 index 00000000..1ae1502c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class LibrariesIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public LibrariesIndexViewEndpointSummary() + { + Summary = "Renders the libraries management view."; + Description = "Renders the view for managing the media libraries."; + + Response(200, "The view for managing the media libraries is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..89ea7054 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-reorder-metadata-providers route. +/// +public class ReorderMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ReorderMetadataProvidersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.LibraryManagement.REORDER_METADATA_PROVIDERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Reorders the metadata providers of a media library. + /// + /// The request containing the Id of the media library and the plugin Ids in the new order. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ReorderLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.Libraries.REORDER_LIBRARY_METADATA_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..1e6ff0e6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ReorderMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ReorderMetadataProvidersEndpointSummary() + { + Summary = "Reorders the metadata providers of a media library."; + Description = "Reorders the metadata providers of the media library identified by the request."; + RequestParam(r => r.LibraryId, "The Id of the media library whose metadata providers are reordered. Required."); + RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); + + ExampleRequest = new ReorderLibraryMetadataProvidersRequest + { + LibraryId = Guid.NewGuid(), + PluginIds = [ + Guid.NewGuid(), + Guid.NewGuid(), + ] + }; + + Response(200, "The metadata providers of the media library are reordered.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpoint.cs new file mode 100644 index 00000000..8ccfdefa --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-item route. +/// +public class SaveLibraryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public SaveLibraryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.LibraryManagement.SAVE_LIBRARY); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + Policies(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); + } + + /// + /// Creates or updates a media library. + /// + /// The request containing the details of the media library to create or update. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(LibraryDto request, CancellationToken cancellationToken) + { + LibraryDto response = request.Id.HasValue + ? await _apiHttpClient.PutAsync(ApiRoutes.Libraries.UPDATE_LIBRARY.Replace("{id}", request.Id.Value.ToString()), request, cancellationToken).ConfigureAwait(false) + : await _apiHttpClient.PostAsync(ApiRoutes.Libraries.ADD_LIBRARY, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs new file mode 100644 index 00000000..8f00c2dd --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SaveLibraryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SaveLibraryEndpointSummary() + { + Summary = "Creates or updates a media library."; + Description = "Creates or updates the media library provided in the request."; + RequestParam(r => r.Id, "The unique identifier of the media library. Optional, when creating a new media library."); + RequestParam(r => r.UserId, "The unique identifier of the user owning the media library. Optional."); + RequestParam(r => r.Title, "The title of the media library. Required."); + RequestParam(r => r.LibraryType, "The type of the media library. Required."); + RequestParam(r => r.CoverImage, "The path of the image file used as the cover of the media library. Optional."); + RequestParam(r => r.ContentLocations, "The collection of directories that contain the media library files. Required."); + RequestParam(r => r.IsEnabled, "Whether the media library is enabled or not. Optional."); + RequestParam(r => r.IsLocked, "Whether the media library is locked or not. Optional."); + RequestParam(r => r.DownloadMetadataFromWeb, "Whether the metadata of the media library items should be downloaded from the web, or not. Optional."); + RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether the downloaded metadata should be copied into the media library content locations, or not. Optional."); + RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether the directories whose contents have not changed since the last scan should be skipped during the scan, or not. Optional."); + + ExampleRequest = new LibraryDto(); + + Response(200, "The media library is created or updated.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs new file mode 100644 index 00000000..7c77f6f0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-scan-libraries route. +/// +public class ScanLibrariesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ScanLibrariesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.LibraryManagement.SCAN_LIBRARIES); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Initiates the scan of all the media libraries. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + ScanLibraryDto[] response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARIES, new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs new file mode 100644 index 00000000..01cc4ddc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ScanLibrariesEndpointSummary() + { + Summary = "Starts the scan of all the media libraries."; + Description = "Initiates the scan of all the media libraries."; + + Response(200, "The scan of all media libraries is started.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs new file mode 100644 index 00000000..19484e1c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-scan-library/{id} route. +/// +public class ScanLibraryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ScanLibraryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.LibraryManagement.SCAN_LIBRARY); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Initiates the scan of a media library. + /// + /// The request containing the Id of the media library to scan. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken) + { + ScanLibraryDto response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs new file mode 100644 index 00000000..20c24430 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ScanLibraryEndpointSummary() + { + Summary = "Starts the scan of a media library."; + Description = "Initiates the scan of the media library identified by the request."; + + RequestParam(r => r.Id, "The unique identifier of the media library to scan."); + + Response(200, "The scan of the media library is started.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs new file mode 100644 index 00000000..c27924c3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-set-metadata-provider-enabled route. +/// +public class SetMetadataProviderEnabledEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public SetMetadataProviderEnabledEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.LibraryManagement.SET_METADATA_PROVIDER_ENABLED); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Enables or disables a metadata provider of a media library. + /// + /// The request containing the Ids of the media library and of the plugin, and whether the provider is enabled. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetLibraryMetadataProviderEnabledRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_METADATA_PROVIDER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs new file mode 100644 index 00000000..472df6f1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetMetadataProviderEnabledEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetMetadataProviderEnabledEndpointSummary() + { + Summary = "Enables or disables a metadata provider of a media library."; + Description = "Enables or disables the metadata provider of the media library identified by the request."; + RequestParam(r => r.LibraryId, "The Id of the media library whose metadata provider is enabled or disabled. Required."); + RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the metadata. Required."); + RequestParam(r => r.IsEnabled, "Whether the metadata provider should be enabled for the media library, or not. Required."); + + ExampleRequest = new SetLibraryMetadataProviderEnabledRequest + { + LibraryId = Guid.NewGuid(), + PluginId = Guid.NewGuid(), + IsEnabled = true + }; + + Response(200, "The metadata provider of the media library is enabled or disabled.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs new file mode 100644 index 00000000..a6fd1b71 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id} route. +/// +public class EditBookViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.EDIT_BOOK); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Displays the book editing view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs new file mode 100644 index 00000000..f9024029 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class EditBookViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public EditBookViewEndpointSummary() + { + Summary = "Renders the edit book view."; + Description = "Renders the view for editing the book identified by the request."; + + RequestParam(r => r.Id, "The unique identifier of the book to edit."); + + Response(200, "The view for editing the book is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs new file mode 100644 index 00000000..c8c344d4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/api-get-library-items route. +/// +public class GetLibraryItemsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryItemsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.GET_LIBRARY_ITEMS); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Retrieves the lightweight details of the books of a media library. + /// + /// The request containing the parameters used to retrieve the books. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBooksLiteRequest request, CancellationToken cancellationToken) + { + PaginatedBookLiteDto response = await _apiHttpClient.GetAsync(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the lightweight details of the books of a media library, from the provided . + /// + /// The request containing the parameters used to retrieve the books. + /// The API endpoint to which the retrieval request is sent. + private static string BuildItemsEndpoint(GetBooksLiteRequest query) + { + StringBuilder endpoint = new(ApiRoutes.Books.GET_BOOKS_LITE); + endpoint.Append($"?libraryId={query.LibraryId}"); + if (query.CurrentPage is not null) + endpoint.Append($"¤tPage={query.CurrentPage}"); + if (query.PerPage is not null) + endpoint.Append($"&perPage={query.PerPage}"); + if (!string.IsNullOrWhiteSpace(query.SearchTerm)) + endpoint.Append($"&searchTerm={Uri.EscapeDataString(query.SearchTerm)}"); + if (!string.IsNullOrWhiteSpace(query.FilterAlphaKey)) + endpoint.Append($"&filterAlphaKey={Uri.EscapeDataString(query.FilterAlphaKey)}"); + endpoint.Append($"&ignoreThePrefixForAlphaPicker={query.IgnoreThePrefixForAlphaPicker}"); + if (!string.IsNullOrWhiteSpace(query.SortBy)) + endpoint.Append($"&sortBy={Uri.EscapeDataString(query.SortBy)}"); + if (query.SortOrder is not null) + endpoint.Append($"&sortOrder={query.SortOrder}"); + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs new file mode 100644 index 00000000..b8f32be7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Libraries; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryItemsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryItemsEndpointSummary() + { + Summary = "Retrieves the lightweight details of the books of a media library."; + Description = "Retrieves the lightweight details of the books of the media library identified by the request."; + + RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved."); + RequestParam(r => r.CurrentPage, "Optional. The page of results to retrieve."); + RequestParam(r => r.PerPage, "Optional. The maximum number of books to retrieve per page."); + RequestParam(r => r.SearchTerm, "Optional. The search term used to filter results."); + RequestParam(r => r.FilterAlphaKey, "Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker."); + RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not."); + RequestParam(r => r.SortBy, "Optional. The name of the field by which to sort the results."); + RequestParam(r => r.SortOrder, "Optional. The direction in which to sort the results."); + + Response(200, "The lightweight details of the books of the media library are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs new file mode 100644 index 00000000..51c5a6b1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books route. +/// +public class BooksIndexViewEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + private readonly IUrlService _urlService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for generating URLs from action and controller names, with localization. + public BooksIndexViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService) + { + _apiHttpClient = apiHttpClient; + _urlService = urlService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Displays the books browsing view. + /// + /// The request containing the Id of the media library whose books are browsed. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBooksViewRequest request, CancellationToken cancellationToken) + { + if (request.LibraryId is null) + return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); + LibraryDto library = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml", library); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs new file mode 100644 index 00000000..cd6b461f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class BooksIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public BooksIndexViewEndpointSummary() + { + Summary = "Renders the books browsing view."; + Description = "Renders the view for browsing the books of the media library identified by the request."; + + RequestParam(r => r.LibraryId, "Optional. The unique identifier of the media library whose books are browsed."); + + Response(200, "The view for browsing the books of the media library is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs new file mode 100644 index 00000000..9d0be7f7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPluginSettings; + +/// +/// API endpoint for the /{culture}/plugins/api-get-plugin-settings/{pluginId} route. +/// +public class GetPluginSettingsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPluginSettingsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Plugins.GET_PLUGIN_SETTINGS); + DontAutoTag(); + Options(options => options.WithTags("Plugins")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the settings of the plugin identified by the request. + /// + /// The request containing the unique identifier of the plugin whose settings are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPluginSettingsRequest request, CancellationToken cancellationToken) + { + PluginSettingsDto response = await _apiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs new file mode 100644 index 00000000..70dfcd95 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPluginSettings; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPluginSettingsEndpointSummary() + { + Summary = "Retrieves the settings of a plugin and their schema."; + Description = "Retrieves the settings and their schema of the plugin identified by the request."; + + RequestParam(r => r.PluginId, "The unique identifier of the plugin whose settings are retrieved."); + + Response(200, "The settings and their schema of the plugin are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs new file mode 100644 index 00000000..56e66099 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins; + +/// +/// API endpoint for the /{culture}/plugins/api-get-plugins route. +/// +public class GetPluginsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPluginsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Plugins.GET_PLUGINS); + DontAutoTag(); + Options(options => options.WithTags("Plugins")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the plugins. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + PluginDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGINS, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs new file mode 100644 index 00000000..b4841d86 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPluginsEndpointSummary() + { + Summary = "Retrieves the plugins."; + Description = "Retrieves the collection of detected plugins."; + + Response(200, "The collection of detected plugins is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpoint.cs new file mode 100644 index 00000000..b75707f4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.Index; + +/// +/// API endpoint for the /{culture}/plugins route. +/// +public class PluginsIndexViewEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public PluginsIndexViewEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Plugins.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Plugins")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Displays the plugins index view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + PluginDto[] plugins = await _apiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGINS, cancellationToken).ConfigureAwait(false); + Dictionary settingsByPluginId = []; + foreach (PluginDto plugin in plugins) + if (plugin.LoadStatus == Lumina.Presentation.Web.Common.Enums.Plugins.PluginLoadStatus.Loaded) + settingsByPluginId[plugin.Id] = await _apiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGIN_SETTINGS.Replace("{pluginId}", plugin.Id.ToString()), cancellationToken).ConfigureAwait(false); + Dictionary viewData = new() { ["pluginSettings"] = settingsByPluginId }; + return View("/Core/Views/Plugins/Index.cshtml", plugins, viewData); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointSummary.cs new file mode 100644 index 00000000..9bf4802a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.Index; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class PluginsIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public PluginsIndexViewEndpointSummary() + { + Summary = "Renders the plugins management view."; + Description = "Renders the view for managing the plugins and their settings."; + + Response(200, "The view for managing the plugins and their settings is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs new file mode 100644 index 00000000..0cd1aba1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings; + +/// +/// API endpoint for the /{culture}/plugins/api-update-plugin-settings route. +/// +public class UpdatePluginSettingsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdatePluginSettingsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Plugins.UPDATE_PLUGIN_SETTINGS); + DontAutoTag(); + Options(options => options.WithTags("Plugins")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Updates the settings of the plugin identified by the request. + /// + /// The request containing the updated settings of the plugin. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointSummary.cs new file mode 100644 index 00000000..80029d6d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointSummary.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePluginSettingsEndpointSummary() + { + Summary = "Updates the settings of a plugin."; + Description = "Updates the settings of the plugin identified by the request."; + RequestParam(r => r.PluginId, "The unique identifier of the plugin. Required."); + RequestParam(r => r.Settings, "The settings of the plugin. Optional."); + + ExampleRequest = new UpdatePluginSettingsRequest + { + PluginId = Guid.NewGuid(), + Settings = new Dictionary + { + { "preferredLanguage", "fr" }, + { "selectionStrategy", "first" } + } + }; + + Response(200, "The settings of the plugin are updated.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpoint.cs new file mode 100644 index 00000000..744af3c0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpoint.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Tools; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Localization; +using Microsoft.AspNetCore.Routing; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; + +/// +/// API endpoint for the /{culture}/tools/language/set-language route. +/// +public class SetLanguageEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Language.SET_LANGUAGE); + DontAutoTag(); + Options(options => options.WithTags("Language")); + } + + /// + /// Sets the culture used by the application. + /// + /// The request containing the new culture to set and the URL to return to. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetLanguageRequest request, CancellationToken cancellationToken) + { + // store the culture preference in a cookie + HttpContext.Response.Cookies.Append( + CookieRequestCultureProvider.DefaultCookieName, + CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(request.NewCulture!)), + new CookieOptions + { + Expires = DateTimeOffset.UtcNow.AddYears(1), + IsEssential = true, + SameSite = SameSiteMode.Lax, + Path = "/" // ensure the cookie works across all paths + } + ); + // determine the URL to return to, defaulting to the localized home page when no return URL is supplied + string newCulture = request.NewCulture!; + string returnUrl = string.IsNullOrEmpty(request.ReturnUrl) ? $"/{newCulture.ToLower()}" : request.ReturnUrl; + string currentCulture = Culture; + + // handle the base path, so that the culture replacement matches the URL + if (!string.IsNullOrEmpty(HttpContext.Request.PathBase)) + returnUrl = returnUrl.Replace(HttpContext.Request.PathBase.Value!, string.Empty, StringComparison.OrdinalIgnoreCase); + // replace the current culture segment of the URL with the new one, whether or not a trailing slash is present + string currentCultureSegment = $"/{currentCulture.ToLower()}"; + string newCultureSegment = $"/{newCulture.ToLower()}"; + if (returnUrl.StartsWith(currentCultureSegment, StringComparison.OrdinalIgnoreCase)) + returnUrl = newCultureSegment + returnUrl[currentCultureSegment.Length..]; + + // re-apply the base path if present + if (!string.IsNullOrEmpty(HttpContext.Request.PathBase)) + returnUrl = HttpContext.Request.PathBase.Value + returnUrl; + + // redirect to the target page + return Results.LocalRedirect(returnUrl); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointSummary.cs new file mode 100644 index 00000000..33243485 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Tools; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetLanguageEndpointSummary() + { + Summary = "Sets the culture of the application."; + Description = "Sets the culture used by the application, storing the preference in a cookie, and redirects the browser back."; + + RequestParam(r => r.NewCulture, "The new culture to set."); + RequestParam(r => r.ReturnUrl, "The URL to return to, after setting the new culture."); + + Response(200, "The culture preference is stored in a cookie, and the browser is redirected back."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpoint.cs new file mode 100644 index 00000000..9dd135dc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// API endpoint for the /{culture}/tools/settings/api-get-user-settings route. +/// +public class GetUserSettingsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetUserSettingsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Settings.GET_USER_SETTINGS); + DontAutoTag(); + Options(options => options.WithTags("Settings")); + } + + /// + /// Retrieves the settings of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + UserSettingsDto response = await _apiHttpClient.GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs new file mode 100644 index 00000000..aaa64482 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserSettingsEndpointSummary() + { + Summary = "Retrieves the settings of the current user."; + Description = "Retrieves the settings of the current user."; + + Response(200, "The settings of the current user are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/SettingsViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/SettingsViewEndpoint.cs new file mode 100644 index 00000000..ece92a34 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/SettingsViewEndpoint.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings; + +/// +/// API endpoint for the /{culture}/tools/settings route. +/// +public class SettingsViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Settings.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Settings")); + } + + /// + /// Displays the user settings view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + UserSettingsDto settings = new(); + return Task.FromResult(View("/Core/Views/Tools/Settings.cshtml", settings)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/SettingsViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/SettingsViewEndpointSummary.cs new file mode 100644 index 00000000..87cb9911 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/SettingsViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SettingsViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SettingsViewEndpointSummary() + { + Summary = "Renders the user settings view."; + Description = "Renders the view for editing the settings of the current user."; + + Response(200, "The view for editing the settings of the current user is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs new file mode 100644 index 00000000..044f7440 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// API endpoint for the /{culture}/tools/settings/api-update-user-settings route. +/// +public class UpdateUserSettingsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdateUserSettingsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Settings.UPDATE_USER_SETTINGS); + DontAutoTag(); + Options(options => options.WithTags("Settings")); + EnableAntiforgery(); + } + + /// + /// Updates the settings of the current user. + /// + /// The request containing the updated settings of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UserSettingsDto request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isUpdated = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs new file mode 100644 index 00000000..ead45202 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateUserSettingsEndpointSummary() + { + Summary = "Updates the settings of the current user."; + Description = "Updates the settings of the current user."; + RequestParam(r => r.UserId, "The unique identifier of the user that owns the settings. Optional."); + RequestParam(r => r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Optional."); + RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Optional."); + RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading 'The' prefix of library item titles is ignored by the alpha picker, or not. Optional."); + + ExampleRequest = new UserSettingsDto(); + + Response(200, "The settings of the current user are updated.", example: new { success = true, data = new { isUpdated = true } }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpoint.cs new file mode 100644 index 00000000..2139b2db --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpoint.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.AccessDenied; + +/// +/// API endpoint for the /{culture}/auth/access-denied route. +/// +public class AccessDeniedViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.ACCESS_DENIED_VIEW); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + AllowAnonymous(); + } + + /// + /// Displays the access denied view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Auth/AccessDenied.cshtml")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointSummary.cs new file mode 100644 index 00000000..9d06908b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.AccessDenied; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AccessDeniedViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AccessDeniedViewEndpointSummary() + { + Summary = "Renders the access denied view."; + Description = "Renders the view that is shown when the user is not authorized to access a resource."; + + Response(200, "The access denied view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs new file mode 100644 index 00000000..2e26cf91 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// API endpoint for the /{culture}/auth/api-change-password route. +/// +public class ChangePasswordEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ChangePasswordEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Authentication.CHANGE_PASSWORD); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + EnableAntiforgery(); + } + + /// + /// Changes the password of the currently logged in account. + /// + /// The request containing the account credentials. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ChangePasswordRequest request, CancellationToken cancellationToken) + { + // assign the currently logged in user as the user for which to change the password + ChangePasswordRequest changePasswordRequest = request with { Username = User?.Identity?.Name }; + ChangePasswordResponse response = await _apiHttpClient.PostAsync(ApiRoutes.Authentication.CHANGE_PASSWORD, changePasswordRequest, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs new file mode 100644 index 00000000..8d146614 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordEndpointSummary() + { + Summary = "Changes the account password."; + Description = "Changes the password of the currently logged in account."; + RequestParam(r => r.Username, "The username of the account. Required."); + RequestParam(r => r.CurrentPassword, "The current password of the account. Required."); + RequestParam(r => r.NewPassword, "The new password of the account. Required."); + RequestParam(r => r.NewPasswordConfirm, "The confirmation of the new password of the account. Required."); + + ExampleRequest = new ChangePasswordRequest( + Username: "JohnDoe", + CurrentPassword: "Abcd123$", + NewPassword: "Abcd1234$", + NewPasswordConfirm: "Abcd1234$" + ); + + Response(200, "The account password is changed.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpoint.cs new file mode 100644 index 00000000..166cfc86 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpoint.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// API endpoint for the /{culture}/auth/change-password route. +/// +public class ChangePasswordViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + } + + /// + /// Displays the account password change view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + ChangePasswordRequest changePasswordRequest = new(Username: null, CurrentPassword: null, NewPassword: null, NewPasswordConfirm: null); + return Task.FromResult(View("/Core/Views/Auth/ChangePassword.cshtml", changePasswordRequest)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointSummary.cs new file mode 100644 index 00000000..2cbfeda4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordViewEndpointSummary() + { + Summary = "Renders the change password view."; + Description = "Renders the view for changing the password of the account."; + + Response(200, "The view for changing the account password is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs new file mode 100644 index 00000000..936620e7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpoint.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Security; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// API endpoint for the /{culture}/auth/api-login route. +/// +public class LoginEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + private readonly ICryptographyService _cryptographyService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for cryptographic functionality. + public LoginEndpoint(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService) + { + _apiHttpClient = apiHttpClient; + _cryptographyService = cryptographyService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Authentication.LOGIN); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + AllowAnonymous(); + EnableAntiforgery(); + } + + /// + /// Authenticates an account and signs the user in. + /// + /// The request containing the account credentials. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(LoginRequest request, CancellationToken cancellationToken) + { + try + { + // attempt API login + LoginResponse response = await _apiHttpClient.PostAsync(ApiRoutes.Authentication.LOGIN_ACCOUNT, request, cancellationToken).ConfigureAwait(false); + // store the received token in a secure cookie + HttpContext.Response.Cookies.Delete("Token"); + HttpContext.Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions + { + Expires = DateTimeOffset.UtcNow.AddMonths(1), + Path = "/", + HttpOnly = true, + Secure = true, + IsEssential = true, + SameSite = SameSiteMode.Strict + }); + // tell asp.net we are logged in + List claims = + [ + new Claim(ClaimTypes.Name, response.Username!), + new Claim(ClaimTypes.NameIdentifier, response.Id.ToString()!), + new Claim("Token", response.Token!), + ]; + ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)).ConfigureAwait(false); + // get current culture from route data or use default if not set + string currentCulture = Culture; + // handle ReturnUrl and ensure it includes the correct culture + string redirectUrl; + if (!string.IsNullOrEmpty(request.ReturnUrl) && IsLocalUrl(request.ReturnUrl)) // ensure that return URL contains the correct culture + redirectUrl = request.ReturnUrl.StartsWith($"/{currentCulture}/") ? request.ReturnUrl : $"/{currentCulture}{request.ReturnUrl}"; + else + { + // if no ReturnUrl is provided or it's invalid, use a default URL with respect to base paths + redirectUrl = "/"; + + // handle reverse proxy scenarios by respecting any base path or forwarded headers + if (HttpContext.Request.Headers.TryGetValue("X-Forwarded-Prefix", out Microsoft.Extensions.Primitives.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 JsonSuccess(redirectUrl); + } + catch (ApiException apiException) + { + // in this particular case, we DO NOT want to let the exception handling middleware take care of this exception, because when the user has 2FA enabled, the first auth step involves sending + // only the username and password, in which case the server API will respond with a validation error, that TOTP code is not valid (empty); it is then that we catch this error here + // and display the form that asks the user for the TOTP code + if (apiException.ProblemDetails is not null && apiException.ProblemDetails.Extensions?.Count > 0 && apiException.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj)) + if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object) + foreach (JsonProperty error in jsonElement.EnumerateObject()) + if (error.Value.ValueKind == JsonValueKind.Array) + foreach (JsonElement errorValue in error.Value.EnumerateArray()) + if (errorValue.ValueKind == JsonValueKind.String && errorValue.GetString() == "InvalidTotpCode" && string.IsNullOrEmpty(request.TotpCode)) + return JsonSuccess(new { isTotpRequired = true }); // only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error + throw; + } + } + + /// + /// Determines whether the specified URL is a local URL. + /// + /// The URL to inspect. + /// if the URL is local, otherwise. + private bool IsLocalUrl(string? url) + { + IUrlHelperFactory urlHelperFactory = HttpContext.RequestServices.GetRequiredService(); + RouteData routeData = HttpContext.GetRouteData() ?? new RouteData(); + IUrlHelper urlHelper = urlHelperFactory.GetUrlHelper(new ActionContext(HttpContext, routeData, new ActionDescriptor())); + return urlHelper.IsLocalUrl(url); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs new file mode 100644 index 00000000..88eb86ba --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public LoginEndpointSummary() + { + Summary = "Authenticates a user."; + Description = "Authenticates an account and signs the user in, returning the URL to redirect to."; + RequestParam(r => r.Username, "The username of the account. Required."); + RequestParam(r => r.Password, "The password of the account. Required."); + RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) code used for two-factor authentication. Optional."); + RequestParam(r => r.ReturnUrl, "The URL to return to, after login. Optional."); + + ExampleRequest = new LoginRequest( + Username: "JohnDoe", + Password: "Abcd123$", + TotpCode: "123456", + ReturnUrl: "/" + ); + + Response(200, "The user is authenticated, and the URL to redirect to is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpoint.cs new file mode 100644 index 00000000..4a758ef8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpoint.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// API endpoint for the /{culture}/auth/login/{returnUrl?} route. +/// +public class LoginViewEndpoint : BaseEndpoint +{ + private readonly IUrlService _urlService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + public LoginViewEndpoint(IUrlService urlService) + { + _urlService = urlService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.LOGIN_VIEW); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + AllowAnonymous(); + PreProcessor>(); + } + + /// + /// Displays the account login view. + /// + /// The request containing the URL to return to, after login. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(LoginViewRequest request, CancellationToken cancellationToken) + { + Dictionary viewData = new() { ["ReturnUrl"] = request.ReturnUrl }; + // if the user is already logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == true) + return Task.FromResult(Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!)); + // 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") + return Task.FromResult(Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW)!)); + return Task.FromResult(View("/Core/Views/Auth/Login.cshtml", new LoginRequest(), viewData)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointSummary.cs new file mode 100644 index 00000000..612c6bda --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class LoginViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public LoginViewEndpointSummary() + { + Summary = "Renders the account login view."; + Description = "Renders the account login view, using the specified URL to return to after login."; + + RequestParam(r => r.ReturnUrl, "The URL to return to, after login."); + + Response(200, "The account login view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpoint.cs new file mode 100644 index 00000000..b6dae3b9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Logout; + +/// +/// API endpoint for the /{culture}/auth/logout route. +/// +public class LogoutEndpoint : BaseEndpoint +{ + private readonly IUrlService _urlService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + public LogoutEndpoint(IUrlService urlService) + { + _urlService = urlService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.LOGOUT); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + } + + /// + /// Logs out the account and redirects to the login page. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // if the user is not logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == false) + return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); + HttpContext.Response.Cookies.Delete("Token"); + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false); + return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)!); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointSummary.cs new file mode 100644 index 00000000..480cd8cb --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Logout; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class LogoutEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public LogoutEndpointSummary() + { + Summary = "Logs out the user."; + Description = "Logs out the currently logged in account and redirects the browser to the login page."; + + Response(200, "The user is logged out, and the browser is redirected to the login page."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Profile/ProfileViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Profile/ProfileViewEndpoint.cs new file mode 100644 index 00000000..f816c470 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Profile/ProfileViewEndpoint.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Profile; + +/// +/// API endpoint for the /{culture}/auth/profile route. +/// +public class ProfileViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.PROFILE_VIEW); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + } + + /// + /// Displays the user profile view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Auth/Profile.cshtml")); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Profile/ProfileViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Profile/ProfileViewEndpointSummary.cs new file mode 100644 index 00000000..138092d4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Profile/ProfileViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Profile; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ProfileViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ProfileViewEndpointSummary() + { + Summary = "Renders the user profile view."; + Description = "Renders the user profile view of the currently logged in account."; + + Response(200, "The user profile view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs new file mode 100644 index 00000000..5af7f1d0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// API endpoint for the /{culture}/auth/api-recover-password route. +/// +public class RecoverPasswordEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RecoverPasswordEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Authentication.RECOVER_PASSWORD); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + AllowAnonymous(); + EnableAntiforgery(); + } + + /// + /// Recovers the password of an account. + /// + /// The request containing the account credentials. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RecoverPasswordRequest request, CancellationToken cancellationToken) + { + RecoverPasswordResponse response = await _apiHttpClient.PostAsync(ApiRoutes.Authentication.RECOVER_PASSWORD, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs new file mode 100644 index 00000000..99946250 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordEndpointSummary() + { + Summary = "Recovers the account password."; + Description = "Recovers the password of an account by verifying the provided TOTP code."; + RequestParam(r => r.Username, "The username of the account. Required."); + RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) code used for two-factor authentication. Optional."); + + ExampleRequest = new RecoverPasswordRequest( + Username: "JohnDoe", + TotpCode: "123456" + ); + + Response(200, "The account password is recovered.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpoint.cs new file mode 100644 index 00000000..cf3a319a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// API endpoint for the /{culture}/auth/recover-password route. +/// +public class RecoverPasswordViewEndpoint : BaseEndpoint +{ + private readonly IUrlService _urlService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + public RecoverPasswordViewEndpoint(IUrlService urlService) + { + _urlService = urlService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + AllowAnonymous(); + PreProcessor>(); + } + + /// + /// Displays the account password recovery view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // if the user is already logged in, redirect them to the home page + if (User?.Identity?.IsAuthenticated == true) + return Task.FromResult(Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!)); + RecoverPasswordRequest recoverPasswordRequest = new(Username: null, TotpCode: null); + return Task.FromResult(View("/Core/Views/Auth/RecoverPassword.cshtml", recoverPasswordRequest)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointSummary.cs new file mode 100644 index 00000000..378fadd9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordViewEndpointSummary() + { + Summary = "Renders the account password recovery view."; + Description = "Renders the view for recovering the password of the account."; + + Response(200, "The account password recovery view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs new file mode 100644 index 00000000..7c7244ca --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// API endpoint for the /{culture}/auth/api-register route. +/// +public class RegisterEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RegisterEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Authentication.REGISTER); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + AllowAnonymous(); + EnableAntiforgery(); + } + + /// + /// Registers an account, or sets up the initial application admin account. + /// + /// The request containing the account credentials. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RegisterRequest request, CancellationToken cancellationToken) + { + // call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup + string endpoint = request.RegistrationType == "Admin" ? ApiRoutes.Initialization.SETUP_APPLICATION : ApiRoutes.Authentication.REGISTER_ACCOUNT; + // attempt API registration + RegisterResponse response = await _apiHttpClient.PostAsync(endpoint, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs new file mode 100644 index 00000000..94cde333 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RegisterEndpointSummary() + { + Summary = "Registers an account."; + Description = "Registers an account, or sets up the initial application admin account."; + RequestParam(r => r.Username, "The username of the account. Required."); + RequestParam(r => r.Password, "The password of the account. Required."); + RequestParam(r => r.PasswordConfirm, "The confirmation of the password of the account. Required."); + RequestParam(r => r.RegistrationType, "The type of the registration, either 'Admin' or 'User'. Required."); + RequestParam(r => r.Use2fa, "Whether two-factor authentication should be enabled for the account. Optional."); + + ExampleRequest = new RegisterRequest( + Username: "JohnDoe", + Password: "Abcd123$", + PasswordConfirm: "Abcd123$", + RegistrationType: "User" + ); + + Response(200, "The account is registered.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpoint.cs new file mode 100644 index 00000000..3dd37c77 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpoint.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// API endpoint for the /{culture}/auth/register route. +/// +public class RegisterViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.REGISTER_VIEW); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + AllowAnonymous(); + PreProcessor>(); + } + + /// + /// Displays the account registration view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // check if this is the initial super admin setup + string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP); + string registrationType = isPendingSuperAdminSetup == "true" ? "Admin" : "User"; + Dictionary viewData = new() { ["RegistrationType"] = registrationType }; + RegisterRequest registerRequest = new(Username: null, Password: null, PasswordConfirm: null, RegistrationType: registrationType); + return Task.FromResult(View("/Core/Views/Auth/Register.cshtml", registerRequest, viewData)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointSummary.cs new file mode 100644 index 00000000..8df98355 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RegisterViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RegisterViewEndpointSummary() + { + Summary = "Renders the account registration view."; + Description = "Renders the view for registering a new account."; + + Response(200, "The account registration view is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs b/src/Lumina.Presentation.Web/Core/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs new file mode 100644 index 00000000..302bf575 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs @@ -0,0 +1,8 @@ +namespace Lumina.Presentation.Web.Core.Renderers.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Renders the book template elements. +/// +public class BooksTemplateRenderer +{ +} diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManagePermissions.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/ManageRoles.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/AccessDenied.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/AccessDenied.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.Designer.cs b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.Designer.cs similarity index 97% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.Designer.cs rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.Designer.cs index e8cb32ae..929e4c25 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.Designer.cs +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.Designer.cs @@ -8,7 +8,7 @@ // //------------------------------------------------------------------------------ -namespace Lumina.Presentation.Web.Resources.Views.Auth { +namespace Lumina.Presentation.Web.Core.Resources.Views.Auth { using System; @@ -39,7 +39,7 @@ namespace Lumina.Presentation.Web.Resources.Views.Auth { public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Resources.Views.Auth.ChangePassword", typeof(ChangePassword).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Core.Resources.Views.Auth.ChangePassword", typeof(ChangePassword).Assembly); resourceMan = temp; } return resourceMan; diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/ChangePassword.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/ChangePassword.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.Designer.cs b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.Designer.cs similarity index 97% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.Designer.cs rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.Designer.cs index e014b269..52d807db 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.Designer.cs +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.Designer.cs @@ -8,7 +8,7 @@ // //------------------------------------------------------------------------------ -namespace Lumina.Presentation.Web.Resources.Views.Auth { +namespace Lumina.Presentation.Web.Core.Resources.Views.Auth { using System; @@ -39,7 +39,7 @@ namespace Lumina.Presentation.Web.Resources.Views.Auth { public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Resources.Views.Auth.Login", typeof(Login).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Core.Resources.Views.Auth.Login", typeof(Login).Assembly); resourceMan = temp; } return resourceMan; diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Login.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Login.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Login.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.Designer.cs b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.Designer.cs similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.Designer.cs rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.Designer.cs index b349f29d..ced70740 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.Designer.cs +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.Designer.cs @@ -8,7 +8,7 @@ // //------------------------------------------------------------------------------ -namespace Lumina.Presentation.Web.Resources.Views.Auth { +namespace Lumina.Presentation.Web.Core.Resources.Views.Auth { using System; @@ -39,7 +39,7 @@ namespace Lumina.Presentation.Web.Resources.Views.Auth { public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Resources.Views.Auth.RecoverPassword", typeof(RecoverPassword).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Core.Resources.Views.Auth.RecoverPassword", typeof(RecoverPassword).Assembly); resourceMan = temp; } return resourceMan; diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/RecoverPassword.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/RecoverPassword.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.Designer.cs b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.Designer.cs similarity index 98% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.Designer.cs rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.Designer.cs index 43187706..0c6c5c0f 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.Designer.cs +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.Designer.cs @@ -8,7 +8,7 @@ // //------------------------------------------------------------------------------ -namespace Lumina.Presentation.Web.Resources.Views.Auth { +namespace Lumina.Presentation.Web.Core.Resources.Views.Auth { using System; @@ -39,7 +39,7 @@ namespace Lumina.Presentation.Web.Resources.Views.Auth { public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Resources.Views.Auth.Register", typeof(Register).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Core.Resources.Views.Auth.Register", typeof(Register).Assembly); resourceMan = temp; } return resourceMan; diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Auth/Register.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Auth/Register.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Auth/Register.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Home/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Home/Index.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.Designer.cs b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.Designer.cs similarity index 86% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.Designer.cs rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.Designer.cs index 63eaff32..33123b17 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.Designer.cs +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.Designer.cs @@ -1,4 +1,4 @@ -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.42000 @@ -8,7 +8,7 @@ // //------------------------------------------------------------------------------ -namespace Lumina.Presentation.Web.Resources.Views.Library.Management { +namespace Lumina.Presentation.Web.Core.Resources.Views.Library.Management { using System; @@ -39,7 +39,7 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Resources.Views.Library.Management.Item", typeof(Item).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Core.Resources.Views.Library.Management.Item", typeof(Item).Assembly); resourceMan = temp; } return resourceMan; @@ -258,6 +258,15 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { } } + /// + /// Looks up a localized string similar to The metadata providers used to enrich the items of this library, in the order they are tried.. + /// + public static string DescriptionMetadataProviders { + get { + return ResourceManager.GetString("DescriptionMetadataProviders", resourceCulture); + } + } + /// /// Looks up a localized string similar to Whether to save a copy of the downloaded metadata in the media library content locations directories, or not. This only has an effect if downloading metadata from the web is active.. /// @@ -267,6 +276,15 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { } } + /// + /// Looks up a localized string similar to When enabled, this option uses directory metadata to skip directories that have not changed since the last scan. This can _significantly_ speed up scans, but be aware that directories metadata _does not_ change/update when editing existing files, it does so only when adding new files or deleting existing ones. Only enable this if you don't modify existing files.. + /// + public static string DescriptionShouldSkipUnchangedDirectoriesDuringScan { + get { + return ResourceManager.GetString("DescriptionShouldSkipUnchangedDirectoriesDuringScan", resourceCulture); + } + } + /// /// Looks up a localized string similar to A name to identify this library. /// @@ -429,6 +447,15 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { } } + /// + /// Looks up a localized string similar to Metadata providers. + /// + public static string MetadataProviders { + get { + return ResourceManager.GetString("MetadataProviders", resourceCulture); + } + } + /// /// Looks up a localized string similar to Miscellaneous Content. /// @@ -438,6 +465,24 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { } } + /// + /// Looks up a localized string similar to Move down. + /// + public static string MoveDown { + get { + return ResourceManager.GetString("MoveDown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Move up. + /// + public static string MoveUp { + get { + return ResourceManager.GetString("MoveUp", resourceCulture); + } + } + /// /// Looks up a localized string similar to Movie. /// @@ -456,6 +501,33 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { } } + /// + /// Looks up a localized string similar to Name. + /// + public static string Name { + get { + return ResourceManager.GetString("Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Order. + /// + public static string Order { + get { + return ResourceManager.GetString("Order", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Order saved. + /// + public static string OrderSaved { + get { + return ResourceManager.GetString("OrderSaved", resourceCulture); + } + } + /// /// Looks up a localized string similar to Other. /// @@ -528,15 +600,6 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { } } - /// - /// Looks up a localized string similar to Save Metadata In Media Directories. - /// - public static string ShouldSaveMetadataInMediaDirectories { - get { - return ResourceManager.GetString("ShouldSaveMetadataInMediaDirectories", resourceCulture); - } - } - /// /// Looks up a localized string similar to Screenplay. /// @@ -555,6 +618,24 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { } } + /// + /// Looks up a localized string similar to Save Metadata In Media Directories. + /// + public static string ShouldSaveMetadataInMediaDirectories { + get { + return ResourceManager.GetString("ShouldSaveMetadataInMediaDirectories", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Skip Unchanged Directories During Scan. + /// + public static string ShouldSkipUnchangedDirectoriesDuringScan { + get { + return ResourceManager.GetString("ShouldSkipUnchangedDirectoriesDuringScan", resourceCulture); + } + } + /// /// Looks up a localized string similar to Sound Effect. /// diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.Designer.cs b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.Designer.cs new file mode 100644 index 00000000..03dfce55 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.Designer.cs @@ -0,0 +1,180 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Lumina.Presentation.Web.Core.Resources.Views.Plugins { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Index { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Index() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Core.Resources.Views.Plugins.Index", typeof(Index).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Author. + /// + public static string Author { + get { + return ResourceManager.GetString("Author", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Description. + /// + public static string Description { + get { + return ResourceManager.GetString("Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Failed to load. + /// + public static string FailedToLoad { + get { + return ResourceManager.GetString("FailedToLoad", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Loaded. + /// + public static string Loaded { + get { + return ResourceManager.GetString("Loaded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Load error. + /// + public static string LoadError { + get { + return ResourceManager.GetString("LoadError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Load status. + /// + public static string LoadStatus { + get { + return ResourceManager.GetString("LoadStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name. + /// + public static string Name { + get { + return ResourceManager.GetString("Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No plugins have been detected.. + /// + public static string NoPlugins { + get { + return ResourceManager.GetString("NoPlugins", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Plugins. + /// + public static string Plugins { + get { + return ResourceManager.GetString("Plugins", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Save. + /// + public static string Save { + get { + return ResourceManager.GetString("Save", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Settings. + /// + public static string Settings { + get { + return ResourceManager.GetString("Settings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Settings saved. + /// + public static string SettingsSaved { + get { + return ResourceManager.GetString("SettingsSaved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Version. + /// + public static string Version { + get { + return ResourceManager.GetString("Version", resourceCulture); + } + } + } +} diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Plugins/Index.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/Components/FileSystemBrowser/Default.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/NotFound.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/NotFound.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Resources/Views/Tools/Settings.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs b/src/Lumina.Presentation.Web/Core/ViewComponents/FileSystemBrowserViewComponent.cs similarity index 70% rename from src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs rename to src/Lumina.Presentation.Web/Core/ViewComponents/FileSystemBrowserViewComponent.cs index f74eec74..dfc458f3 100644 --- a/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs +++ b/src/Lumina.Presentation.Web/Core/ViewComponents/FileSystemBrowserViewComponent.cs @@ -1,28 +1,28 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; using Lumina.Presentation.Web.Common.Enums.FileSystem; -using Lumina.Presentation.Web.Common.Models.Configuration; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System.Runtime.InteropServices; #endregion -namespace Lumina.Presentation.Web.ViewComponents; +namespace Lumina.Presentation.Web.Core.ViewComponents; /// /// View component for the file system browser. /// public class FileSystemBrowserViewComponent : ViewComponent { - private readonly ServerConfigurationModel _serverConfigurationModel; + private readonly ServerConfigurationDto _serverConfiguration; /// /// Initializes a new instance of the class. /// - /// Injected service for retrieving . - public FileSystemBrowserViewComponent(IOptions serverConfigurationModelOptions) + /// Injected service for retrieving . + public FileSystemBrowserViewComponent(IOptions serverConfigurationOptions) { - _serverConfigurationModel = serverConfigurationModelOptions.Value; + _serverConfiguration = serverConfigurationOptions.Value; } /// @@ -36,7 +36,7 @@ public class FileSystemBrowserViewComponent : ViewComponent return View(new { Path = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"/" : @"C:\Users\", - ServerBasePath = $"{_serverConfigurationModel.BaseAddress}:{_serverConfigurationModel.Port}/api/v{_serverConfigurationModel.ApiVersion}/", + ServerBasePath = $"{_serverConfiguration.BaseAddress}:{_serverConfiguration.Port}/api/v{_serverConfiguration.ApiVersion}/", ClientBasePath = "http://localhost:5012/", // TODO: take from appsettings or environment ViewMode = FileSystemViewMode.List, IconSize = FileSystemIconSize.Large diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml similarity index 95% rename from src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml index eed906a3..2dbe731d 100644 --- a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml @@ -2,15 +2,15 @@ /admin/manage-permissions/ *@ -@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.DTO.Authorization +@using Lumina.Presentation.Web.Common.DTO.UsersManagement @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization -@using Lumina.Presentation.Web.Common.Models.Authorization @{ - var roles = ViewData["roles"] as RoleModel[]; - var users = ViewData["users"] as UserModel[]; - var permissions = ViewData["permissions"] as PermissionModel[]; + var roles = ViewData["roles"] as RoleDto[]; + var users = ViewData["users"] as UserDto[]; + var permissions = ViewData["permissions"] as PermissionDto[]; // 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(); } @@ -121,13 +121,13 @@ .map(checkbox => checkbox.value) }; - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl("UpdateUserAuthorization", "Admin")', formData); + const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.UPDATE_USER_AUTHORIZATION)', formData); if (result.success) notificationService.show('@_localizer["UserAuthorizationUpdated"]', NotificationType.SUCCESS); } async function fetchUserRoleAsync(userId) { - const url = '@_urlService.GetAbsoluteUrl("GetRoleByUserId", "Admin", new { userId = default(Guid) })'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Admin.GET_ROLE_BY_USER_ID, new { userId = default(Guid) })'; const data = await callApiGetAsync(url.replace('/@(default(Guid))', `/${userId}`)); // userId needs to be replaced here, because GetAbsoluteUrl is server side, userId is client side if (data) { var roleElement = document.querySelector('#authorization-roles-combobox .enlightenment-option[data-value="' + data.id + '"]'); @@ -139,7 +139,7 @@ } async function fetchUserPermissionsAsync(userId) { - const url = '@_urlService.GetAbsoluteUrl("GetPermissionsByUserId", "Admin", new { userId = default(Guid) })'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Admin.GET_PERMISSIONS_BY_USER_ID, new { userId = default(Guid) })'; const data = await callApiGetAsync(url.replace('/@(default(Guid))', `/${userId}`)); // userId needs to be replaced here, because GetAbsoluteUrl is server side, userId is client side if (data) { // clear all checkboxes diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css b/src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml.css similarity index 100% rename from src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css rename to src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml.css diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml similarity index 95% rename from src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml index c82b385c..1845ccaa 100644 --- a/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml @@ -2,13 +2,13 @@ /admin/manage-roles/ *@ +@using Lumina.Presentation.Web.Common.DTO.Authorization @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization -@using Lumina.Presentation.Web.Common.Models.Authorization @{ - var roles = ViewData["roles"] as RoleModel[]; - var permissions = ViewData["permissions"] as PermissionModel[]; + var roles = ViewData["roles"] as RoleDto[]; + var permissions = ViewData["permissions"] as PermissionDto[]; // 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(); } @@ -104,8 +104,8 @@ const isRoleSelected = formData.roleId !== ''; const result = isRoleSelected ? - await callApiPutAsync('@_urlService.GetAbsoluteUrl("UpdateRole", "Admin")', formData) : - { success: (await callApiPostAsync('@_urlService.GetAbsoluteUrl("CreateRole", "Admin")', formData)) !== undefined }; + await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.UPDATE_ROLE)', formData) : + { success: (await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.CREATE_ROLE)', formData)) !== undefined }; if (result.success) { await fetchRolesAsync(); notificationService.show(isRoleSelected ? '@_localizer["RoleUpdated"]' : '@_localizer["RoleCreated"]', NotificationType.SUCCESS); @@ -113,7 +113,7 @@ } async function fetchRolesAsync() { - const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetRoles", "Admin")'); + const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.GET_ROLES)'); if (data) { // clear the roles drop down list const rolesDropdown = document.querySelector("#authorization-roles-combobox .enlightenment-dropdown"); @@ -152,7 +152,7 @@ async function fetchRolePermissionsAsync(roleId) { if (roleId) { - const url = '@_urlService.GetAbsoluteUrl("GetPermissionsByRoleId", "Admin", new { roleId = default(Guid) })'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Admin.GET_PERMISSIONS_BY_ROLE_ID, new { roleId = default(Guid) })'; const data = await callApiGetAsync(url.replace('/@(default(Guid))', `/${roleId}`)); // roleId needs to be replaced here, because GetAbsoluteUrl is server side, roleId is client side if (data) { // clear all checkboxes @@ -192,7 +192,7 @@ const handleBtnDeleteRoleClick = async function(e) { // ask the user for confirmation before deleting the role if (await dialogService.show('@_localizer["DeleteRoleConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { - const url = '@_urlService.GetAbsoluteUrl("DeleteRole", "Admin", new { roleId = default(Guid) })'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Admin.DELETE_ROLE, new { roleId = default(Guid) })'; const success = await callApiDeleteAsync(url.replace('/@(default(Guid))', `/${roleIdInput.value}`)); // roleId needs to be replaced here, because GetAbsoluteUrl is server side, roleId is client side if (success) { await fetchRolesAsync(); diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml.css b/src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml.css similarity index 100% rename from src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml.css rename to src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml.css diff --git a/src/Lumina.Presentation.Web/Views/Auth/AccessDenied.cshtml b/src/Lumina.Presentation.Web/Core/Views/Auth/AccessDenied.cshtml similarity index 100% rename from src/Lumina.Presentation.Web/Views/Auth/AccessDenied.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Auth/AccessDenied.cshtml diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Core/Views/Auth/ChangePassword.cshtml similarity index 97% rename from src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Auth/ChangePassword.cshtml index fb971570..c260c0e9 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Auth/ChangePassword.cshtml @@ -2,7 +2,7 @@ /auth/change-password/ *@ -@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Requests.UsersManagement @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -14,7 +14,7 @@ @inject IUrlService _urlService @inject IViewLocalizer _localizer -@model ChangePasswordRequestModel +@model ChangePasswordRequest
@@ -91,7 +91,7 @@ NewPassword: txtNewPassword.value, NewPasswordConfirm: txtNewPasswordConfirm.value }; - const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("ChangePasswordPost", "Auth")', formData); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD)', formData); if (data && data.isPasswordChanged === true) { changePasswordSuccess.classList.replace('hidden', 'block'); divCurrentPassword.classList.add('hidden'); diff --git a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml b/src/Lumina.Presentation.Web/Core/Views/Auth/Login.cshtml similarity index 96% rename from src/Lumina.Presentation.Web/Views/Auth/Login.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Auth/Login.cshtml index 29615bec..9e30798e 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Auth/Login.cshtml @@ -2,7 +2,7 @@ /auth/login/ *@ -@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Requests.UsersManagement @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -14,7 +14,7 @@ @inject IUrlService _urlService @inject IViewLocalizer _localizer -@model LoginRequestModel +@model LoginRequest
@@ -85,7 +85,7 @@ TotpCode: txtTotpCode.value, ReturnUrl: returnUrlInput.value }; - const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("LoginPost", "Auth")', formData); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN)', formData); if (data && data.isTotpRequired === true) { txtUsername.disabled = true; txtPassword.disabled = true; @@ -115,7 +115,7 @@ // on recover password button click const handleBtnRecoverPasswordClick = function() { - window.location.href = '@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")'; + window.location.href = '@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW)'; }; // add listeners diff --git a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml b/src/Lumina.Presentation.Web/Core/Views/Auth/RecoverPassword.cshtml similarity index 96% rename from src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Auth/RecoverPassword.cshtml index 4174e487..588befd3 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Auth/RecoverPassword.cshtml @@ -2,7 +2,7 @@ /auth/recover-password/ *@ -@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Requests.UsersManagement @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -14,7 +14,7 @@ @inject IUrlService _urlService @inject IViewLocalizer _localizer -@model RecoverPasswordRequestModel +@model RecoverPasswordRequest
@@ -77,7 +77,7 @@ Username: txtUsername.value, TotpCode: txtTotpCode.value }; - const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("RecoverPasswordPost", "Auth")', formData); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD)', formData); if (data && data.isPasswordReset === true) { divUsername.classList.add('hidden'); btnValidateTotp.classList.add('hidden'); @@ -104,12 +104,12 @@ // on login button click const handleBtnLoginClick = function() { - window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")'; + window.location.href = '@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)'; }; // on login redirect button click const handleBtnRedirectLoginClick = function() { - window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")'; + window.location.href = '@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)'; }; // add listeners diff --git a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml b/src/Lumina.Presentation.Web/Core/Views/Auth/Register.cshtml similarity index 98% rename from src/Lumina.Presentation.Web/Views/Auth/Register.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Auth/Register.cshtml index d1634a86..914cde39 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Auth/Register.cshtml @@ -2,7 +2,7 @@ /auth/register/ *@ -@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.Requests.UsersManagement @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -15,7 +15,7 @@ @inject IUrlService _urlService @inject IViewLocalizer _localizer -@model RegisterRequestModel +@model RegisterRequest
@@ -123,7 +123,7 @@ Use2fa: chkUse2FA.checked, RegistrationType: form.querySelector('[name="RegistrationType"]').value }; - const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("RegisterPost", "Auth")', formData); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER)', formData); if (data) { txtUsername.value = ''; txtPassword.value = ''; @@ -169,7 +169,7 @@ // on login button click const handleBtnLoginClick = function() { - window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")'; + window.location.href = '@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)'; }; // add listeners diff --git a/src/Lumina.Presentation.Web/Views/Home/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml similarity index 94% rename from src/Lumina.Presentation.Web/Views/Home/Index.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml index 09a2baa7..b8c56118 100644 --- a/src/Lumina.Presentation.Web/Views/Home/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml @@ -2,7 +2,7 @@ / *@ -@using Lumina.Presentation.Web.Common.Models.Libraries +@using Lumina.Presentation.Web.Common.DTO.Libraries @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -38,7 +38,7 @@ isInitialized = true; // get the media libraries // TODO: add setting check whether the user desires this feature or not - const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetEnabledLibraries", "LibraryManagement")'); + const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES)'); if (data && data.length > 0) { noLibrariesMessage.classList.replace('block', 'hidden'); librariesContainer.classList.replace('justify-center', 'justify-start'); @@ -47,7 +47,7 @@ // book libraries are browsable, so their panel is rendered as a link to their browse page const isBrowsable = library.libraryType === 'Book'; const browseUrl = isBrowsable - ? '@_urlService.GetAbsoluteUrl("Index", "Books")' + '?libraryId=' + library.id + ? '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)' + '?libraryId=' + library.id : null; const libraryElement = isBrowsable ? document.createElement('a') : document.createElement('div'); diff --git a/src/Lumina.Presentation.Web/Views/Home/Privacy.cshtml b/src/Lumina.Presentation.Web/Core/Views/Home/Privacy.cshtml similarity index 100% rename from src/Lumina.Presentation.Web/Views/Home/Privacy.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Home/Privacy.cshtml diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml similarity index 97% rename from src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index 7b4d6646..8cca8518 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -2,7 +2,7 @@ /library/manage *@ -@using Lumina.Presentation.Web.Common.Models.Libraries +@using Lumina.Presentation.Web.Common.DTO.Libraries @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @using System.Security.Claims @@ -224,7 +224,7 @@ // get media libraries const loadLibrariesAsync = async function() { - const response = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetLibraries", "LibraryManagement")'); + const response = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARIES)'); const table = document.getElementById('media-libraries-table'); const tbody = table.querySelector('tbody') || table.appendChild(document.createElement('tbody')); const noMediaLibrary = document.getElementById('no-media-libaries'); @@ -234,7 +234,7 @@ noMediaLibrary.style.display = 'none'; btnScanAllLibraries.style.display = 'block'; tbody.innerHTML = response.map(library => { - const editUrl = '@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement", new { id = default(Guid) })' + const editUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.EDIT_LIBRARY, new { id = default(Guid) })' .replace('/@(default(Guid))', `/${library.id}`); return ` @@ -278,7 +278,7 @@ // get which libraries have active scans const getRunningLibraryScansAsync = async function() { - const response = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetRunningLibraryScans", "LibraryManagement")'); + const response = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_RUNNING_LIBRARY_SCANS)'); if (response && response.length > 0) { await Promise.all(response.map(async scan => { const row = document.querySelector(`tr[data-library-id="${scan.libraryId}"]`); @@ -317,7 +317,7 @@ if (await dialogService.show('@_localizer["DeleteLibraryConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { const libraryId = row.getAttribute('data-library-id'); - const url = '@_urlService.GetAbsoluteUrl("DeleteLibrary", "LibraryManagement", new { id = default(Guid) })'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id = default(Guid) })'; const success = await callApiDeleteAsync(url.replace('/@(default(Guid))', `/${libraryId}`)); if (success) { @@ -330,7 +330,7 @@ // on scan all libraries button click const handleScanAllLibrariesClick = async function(e) { - const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("ScanAllLibraries", "LibraryManagement")', {}); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SCAN_LIBRARIES)', {}); if (data) { btnScanAllLibraries.style.display = 'none'; btnCancelLibrariesScan.style.display = 'block'; @@ -369,7 +369,7 @@ const row = e.target.closest('tr'); const libraryId = row.getAttribute('data-library-id'); - const url = '@_urlService.GetAbsoluteUrl("ScanLibrary", "LibraryManagement", new { id = default(Guid) })'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SCAN_LIBRARY, new { id = default(Guid) })'; const success = await callApiPostAsync(url.replace('/@(default(Guid))', `/${libraryId}`)); if (success) { @@ -397,7 +397,7 @@ // on cancel all libraries scan button click const handleCancelLibrariesScanClick = async function(e) { - await callApiPostAsync('@_urlService.GetAbsoluteUrl("CancelLibrariesScan", "LibraryManagement")', {}); + await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARIES_SCAN)', {}); btnCancelLibrariesScan.style.display = 'none'; btnScanAllLibraries.style.display = 'block'; @@ -430,7 +430,7 @@ if (e.target.matches('img[src*="stop.svg"]')) { const row = e.target.closest('tr'); - const url = '@_urlService.GetAbsoluteUrl("CancelLibraryScan", "LibraryManagement", new { libraryId = default(Guid), scanId = default(Guid) })'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.CANCEL_LIBRARY_SCAN, new { libraryId = default(Guid), scanId = default(Guid) })'; // make a list of values from DOM that are needed as URL query params (they need to be in the order they appear in the URL!) const params = [ diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml.css b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml.css similarity index 100% rename from src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml.css rename to src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml.css diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml similarity index 97% rename from src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml index c7ea7bdc..091c47cf 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml @@ -2,7 +2,7 @@ /library/manage/item/{id:guid} *@ -@using Lumina.Presentation.Web.Common.Models.Libraries +@using Lumina.Presentation.Web.Common.DTO.Libraries @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -15,7 +15,7 @@ @inject IUrlService _urlService @inject IViewLocalizer _localizer -@model LibraryModel +@model LibraryDto @await Component.InvokeAsync("FileSystemBrowser") @@ -275,7 +275,7 @@ ShouldSaveMetadataInMediaDirectories: chkShouldSaveMetadataInMediaDirectories.checked, ShouldSkipUnchangedDirectoriesDuringScan: chkShouldSkipUnchangedDirectoriesDuringScan.checked }; - const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("SaveLibrary", "LibraryManagement")', formData); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SAVE_LIBRARY)', formData); if (data) { form.classList.replace('inline', 'hidden'); saveSuccess.classList.replace('hidden', 'inline'); @@ -338,12 +338,12 @@ // on back to libraries button click const handleBtnBackToLibrariesClick = function() { - window.location.href = '@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")'; + window.location.href = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX)'; }; // on add new library button click const handleBtnAddNewLibraryClick = function() { - window.location.href = '@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")'; + window.location.href = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.EDIT_LIBRARY)'; }; // on add media directory image click @@ -369,7 +369,7 @@ // loads the metadata providers configured for the library, when editing an existing library async function loadMetadataProvidersAsync() { if (!id || !metadataProvidersTbody) return; - const url = '@_urlService.GetAbsoluteUrl("GetMetadataProviders", "LibraryManagement", new { libraryId = default(Guid) })' + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_METADATA_PROVIDERS, new { libraryId = default(Guid) })' .replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side const response = await callApiGetAsync(url); if (response && response.length > 0) { @@ -412,7 +412,7 @@ if (!id || !metadataProvidersTbody) return; const pluginIds = Array.from(metadataProvidersTbody.querySelectorAll('tr[data-provider-plugin-id]')) .map(row => row.getAttribute('data-provider-plugin-id')); - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl("ReorderMetadataProviders", "LibraryManagement")', { libraryId: id, pluginIds: pluginIds }); + const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.REORDER_METADATA_PROVIDERS)', { libraryId: id, pluginIds: pluginIds }); if (result.success) { notificationService.show('@_localizer["OrderSaved"]', NotificationType.SUCCESS); } @@ -424,7 +424,7 @@ const row = e.target.closest('tr'); const pluginId = row.getAttribute('data-provider-plugin-id'); const isEnabled = e.target.checked; - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl("SetMetadataProviderEnabled", "LibraryManagement")', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled }); + const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_METADATA_PROVIDER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled }); if (!result.success) { e.target.checked = !isEnabled; } diff --git a/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml similarity index 98% rename from src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml index e5262832..6832ccf2 100644 --- a/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml @@ -2,7 +2,7 @@ /library/written-content-library/books-library/books?libraryId=... *@ -@using Lumina.Presentation.Web.Common.Models.Libraries +@using Lumina.Presentation.Web.Common.DTO.Libraries @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -14,7 +14,7 @@ @inject IViewLocalizer _localizer @inject IUrlService _urlService -@model LibraryModel +@model LibraryDto
@@ -89,7 +89,7 @@ // builds the URL of the retrieval endpoint, from the current state function buildItemsUrl() { - const url = '@_urlService.GetAbsoluteUrl("GetLibraryItems", "Books")'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS)'; const params = new URLSearchParams(); params.set('libraryId', libraryId); if (state.perPage !== null) { @@ -257,7 +257,7 @@ // loads the settings of the current user, which drive pagination and the alpha picker prefix handling async function loadSettingsAsync() { - const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetUserSettings", "Settings")'); + const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)'); if (data) { state.ignoreThePrefix = data.ignoreThePrefixForAlphaPicker === true; state.perPage = data.isPaginationEnabled === true ? data.itemsPerPage : null; diff --git a/src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml similarity index 100% rename from src/Lumina.Presentation.Web/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml diff --git a/src/Lumina.Presentation.Web/Views/Plugins/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Plugins/Index.cshtml similarity index 95% rename from src/Lumina.Presentation.Web/Views/Plugins/Index.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Plugins/Index.cshtml index cf0140c2..734f9ff4 100644 --- a/src/Lumina.Presentation.Web/Views/Plugins/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Plugins/Index.cshtml @@ -2,15 +2,15 @@ /plugins *@ +@using Lumina.Presentation.Web.Common.DTO.Plugins @using Lumina.Presentation.Web.Common.Enums.Plugins -@using Lumina.Presentation.Web.Common.Models.Plugins @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization -@model PluginModel[] +@model PluginDto[] @{ - var settingsByPluginId = ViewData["pluginSettings"] as Dictionary ?? new Dictionary(); + var settingsByPluginId = ViewData["pluginSettings"] as Dictionary ?? new Dictionary(); // 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(); } @@ -41,7 +41,7 @@ - @foreach (PluginModel plugin in Model) + @foreach (PluginDto plugin in Model) { @plugin.Name @@ -75,11 +75,11 @@ } @if (plugin.LoadStatus == PluginLoadStatus.Loaded && settingsByPluginId.ContainsKey(plugin.Id)) { - PluginSettingsModel pluginSettings = settingsByPluginId[plugin.Id]; + PluginSettingsDto pluginSettings = settingsByPluginId[plugin.Id];
- @foreach (PluginSettingDescriptorModel descriptor in pluginSettings.Schema) + @foreach (PluginSettingDescriptorDto descriptor in pluginSettings.Schema) { string currentValue = pluginSettings.Settings is not null && pluginSettings.Settings.ContainsKey(descriptor.Key) ? pluginSettings.Settings[descriptor.Key] @@ -171,7 +171,7 @@ } }); - const url = '@_urlService.GetAbsoluteUrl("UpdatePluginSettings", "Plugins")'; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Plugins.UPDATE_PLUGIN_SETTINGS)'; const result = await callApiPutAsync(url, { pluginId: pluginId, settings: settings }); if (result.success) { notificationService.show('@_localizer["SettingsSaved"]', NotificationType.SUCCESS); diff --git a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/Components/FileSystemBrowser/Default.cshtml similarity index 99% rename from src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Shared/Components/FileSystemBrowser/Default.cshtml index 4043efe0..ac082b75 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -1,9 +1,9 @@ -@using Lumina.Presentation.Web.Common.Models.Common +@using Lumina.Presentation.Web.Common.DTO.Common @using Lumina.Presentation.Web.Common.Api @using Lumina.Presentation.Web.Common.Enums.FileSystem @using Lumina.Presentation.Web.Common.Enums.Notifications @using Lumina.Presentation.Web.Common.Exceptions -@using Lumina.Presentation.Web.Common.Models.FileSystemManagement +@using Lumina.Presentation.Web.Common.DTO.FileSystemManagement @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.AspNetCore.Components diff --git a/src/Lumina.Presentation.Web/Views/Shared/Error.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/Error.cshtml similarity index 92% rename from src/Lumina.Presentation.Web/Views/Shared/Error.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Shared/Error.cshtml index a1e04783..9796d49c 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/Error.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/Error.cshtml @@ -1,4 +1,5 @@ -@model ErrorViewModel +@using Lumina.Presentation.Web.Common.DTO.Common +@model ErrorViewDto @{ ViewData["Title"] = "Error"; } diff --git a/src/Lumina.Presentation.Web/Views/Shared/NotFound.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/NotFound.cshtml similarity index 100% rename from src/Lumina.Presentation.Web/Views/Shared/NotFound.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Shared/NotFound.cshtml diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml similarity index 96% rename from src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index 3c6c2ad1..2b8187f2 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -1,9 +1,9 @@ -@using Lumina.Presentation.Web.Common.Models.Configuration +@using Lumina.Presentation.Web.Common.DTO.Configuration @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.Extensions.Options @inject IViewLocalizer _localizer -@inject IOptions _serverConfigurationModel +@inject IOptions _serverConfigurationModel diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml.css similarity index 100% rename from src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml.css rename to src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml.css diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml similarity index 54% rename from src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml index e7f6b6e1..a1f51376 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml @@ -19,7 +19,7 @@ Lumina
@_localizer["Account"] @@ -27,18 +27,18 @@ @if (User?.Identity?.IsAuthenticated == true) @@ -49,19 +49,19 @@ @_localizer["Administrator"]
}
@_localizer["Library"]
@@ -90,15 +90,15 @@ @_localizer["Language"]
@if (User?.Identity?.IsAuthenticated == true) { @@ -106,7 +106,7 @@ @_localizer["Tools"]
}
@@ -124,7 +124,7 @@
  • @@ -132,18 +132,18 @@
  • @@ -154,19 +154,19 @@
  • }
  • diff --git a/src/Lumina.Presentation.Web/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml similarity index 97% rename from src/Lumina.Presentation.Web/Views/Tools/Settings.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index 09304622..7ea8be9a 100644 --- a/src/Lumina.Presentation.Web/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -2,7 +2,7 @@ /tools/settings *@ -@using Lumina.Presentation.Web.Common.Models.UsersManagement +@using Lumina.Presentation.Web.Common.DTO.UsersManagement @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @@ -14,7 +14,7 @@ @inject IUrlService _urlService @inject IViewLocalizer _localizer -@model UserSettingsModel +@model UserSettingsDto
    @@ -90,7 +90,7 @@ // load the settings of the current user async function loadUserSettingsAsync() { - const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetUserSettings", "Settings")'); + const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)'); if (data) { checkboxIsPaginationEnabled.checked = data.isPaginationEnabled === true; inputItemsPerPage.value = data.itemsPerPage; @@ -106,7 +106,7 @@ ItemsPerPage: Number(inputItemsPerPage.value), IgnoreThePrefixForAlphaPicker: checkboxIgnoreThePrefixForAlphaPicker.checked }; - const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("UpdateUserSettings", "Settings")', formData); + const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData); if (data && data.isUpdated === true) notificationService.show('@_localizer["SettingsSaved"]', NotificationType.SUCCESS); } diff --git a/src/Lumina.Presentation.Web/Core/Views/_ViewImports.cshtml b/src/Lumina.Presentation.Web/Core/Views/_ViewImports.cshtml new file mode 100644 index 00000000..263725d5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/_ViewImports.cshtml @@ -0,0 +1,4 @@ +@using Lumina.Presentation.Web +@using Lumina.Presentation.Web.Common.Routes + +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Views/_ViewStart.cshtml b/src/Lumina.Presentation.Web/Core/Views/_ViewStart.cshtml similarity index 100% rename from src/Lumina.Presentation.Web/Views/_ViewStart.cshtml rename to src/Lumina.Presentation.Web/Core/Views/_ViewStart.cshtml diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index a29edcbc..c4010b22 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -19,12 +19,16 @@ + + + + @@ -33,326 +37,331 @@ - + True True ChangePassword.resx - + True True Login.resx - + True True RecoverPassword.resx - + True True Register.resx - + True True Item.resx + + True + True + Index.resx + - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator ChangePassword.Designer.cs - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator Login.Designer.cs - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator RecoverPassword.Designer.cs - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator Register.Designer.cs - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator Item.Designer.cs - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator Index.Designer.cs - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator diff --git a/src/Lumina.Presentation.Web/Models/ErrorViewModel.cs b/src/Lumina.Presentation.Web/Models/ErrorViewModel.cs deleted file mode 100644 index 5775d1f6..00000000 --- a/src/Lumina.Presentation.Web/Models/ErrorViewModel.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Lumina.Presentation.Web.Models; - -public class ErrorViewModel -{ - public string? RequestId { get; set; } - - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); -} diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index fdbfdb5e..c314290d 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -1,13 +1,14 @@ #region ========================================================================= USING ===================================================================================== +using FastEndpoints; 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; +using Scalar.AspNetCore; using Serilog; using System; using System.Diagnostics.CodeAnalysis; @@ -92,6 +93,8 @@ public class Program app.UseCultureRedirect(); // if the user attempts to go to a localized route without providing a culture, redirect to default culture app.UseApiExceptionHandling(); // handle any problem details returned by the API app.UseRouting(); + app.UseAntiforgeryFE(additionalContentTypes: ["application/json"]); // validate the antiforgery token of the JSON requests, sent via the RequestVerificationToken header + app.UseRequestLocalization(); // set the culture from the localized routes app.UseSession(); app.UseAuthentication(); app.UseAuthorization(); @@ -105,17 +108,18 @@ public class Program return next(); }); - // 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}" - ); + app.UseFastEndpoints(); + + // add API documentation (OpenApi/Scalar), so that the endpoints exposed by the web application are discoverable and their contracts are visible + app.MapOpenApi(); + app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); + app.MapScalarApiReference(scalarOptions => + { + scalarOptions.WithTitle("Lumina Web") + .WithTheme(ScalarTheme.BluePlanet) + .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient) + .WithDotNetFlag(true); + }); await app.RunAsync(); } diff --git a/src/Lumina.Presentation.Web/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs b/src/Lumina.Presentation.Web/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs deleted file mode 100644 index 02466425..00000000 --- a/src/Lumina.Presentation.Web/Renderers/Library/WrittenContentLibrary/BookLibrary/Books/BooksTemplateRenderer.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace Lumina.Presentation.Web.Renderers.Library.WrittenContentLibrary.BookLibrary.Books; - -public class BooksTemplateRenderer -{ -} diff --git a/src/Lumina.Presentation.Web/Views/_ViewImports.cshtml b/src/Lumina.Presentation.Web/Views/_ViewImports.cshtml deleted file mode 100644 index 739426be..00000000 --- a/src/Lumina.Presentation.Web/Views/_ViewImports.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@using Lumina.Presentation.Web -@using Lumina.Presentation.Web.Models -@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/src/Lumina.sln b/src/Lumina.sln index 2859a645..712b3786 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -1,3 +1,4 @@ + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -223,6 +224,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.Fix EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Domain.SharedKernel.Fixtures", "..\tests\Common\Lumina.Domain.SharedKernel.Fixtures\Lumina.Domain.SharedKernel.Fixtures.csproj", "{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.Fixtures", "..\tests\Common\Lumina.Presentation.Web.Fixtures\Lumina.Presentation.Web.Fixtures.csproj", "{52245330-641B-4E14-823A-10B3D9105D58}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.UnitTests", "..\tests\UnitTests\Lumina.Presentation.Web.UnitTests\Lumina.Presentation.Web.UnitTests.csproj", "{697F6057-DBDC-40B9-A7E5-02F295BC18B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Web.IntegrationTests\Lumina.Presentation.Web.IntegrationTests.csproj", "{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.SecurityTests", "..\tests\SecurityTests\Lumina.Presentation.Web.SecurityTests\Lumina.Presentation.Web.SecurityTests.csproj", "{3FE25467-CBC6-438F-BB96-6601AF56E937}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -517,6 +526,54 @@ Global {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x64.Build.0 = Release|Any CPU {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.ActiveCfg = Release|Any CPU {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.Build.0 = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|Any CPU.Build.0 = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x64.ActiveCfg = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x64.Build.0 = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x86.ActiveCfg = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Debug|x86.Build.0 = Debug|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|Any CPU.ActiveCfg = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|Any CPU.Build.0 = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x64.ActiveCfg = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x64.Build.0 = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x86.ActiveCfg = Release|Any CPU + {52245330-641B-4E14-823A-10B3D9105D58}.Release|x86.Build.0 = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x64.ActiveCfg = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x64.Build.0 = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x86.ActiveCfg = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x86.Build.0 = Debug|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|Any CPU.Build.0 = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x64.ActiveCfg = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x64.Build.0 = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x86.ActiveCfg = Release|Any CPU + {697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x86.Build.0 = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x64.ActiveCfg = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x64.Build.0 = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x86.ActiveCfg = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x86.Build.0 = Debug|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|Any CPU.Build.0 = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x64.ActiveCfg = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x64.Build.0 = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x86.ActiveCfg = Release|Any CPU + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x86.Build.0 = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x64.ActiveCfg = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x64.Build.0 = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x86.ActiveCfg = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x86.Build.0 = Debug|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|Any CPU.Build.0 = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x64.ActiveCfg = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x64.Build.0 = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.ActiveCfg = Release|Any CPU + {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -570,6 +627,10 @@ Global {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {52245330-641B-4E14-823A-10B3D9105D58} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {697F6057-DBDC-40B9-A7E5-02F295BC18B3} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A} = {3F057926-562F-4EF4-BFC0-EE62372D4551} + {3FE25467-CBC6-438F-BB96-6601AF56E937} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs new file mode 100644 index 00000000..93a80e81 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -0,0 +1,255 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Api; + +/// +/// Test double for the interface, allowing integration and security tests to stub the +/// remote API responses without hosting a real backend. +/// +[ExcludeFromCodeCoverage] +public class StubApiHttpClient : IApiHttpClient +{ + private readonly Dictionary> _getResponseFactories = []; + private readonly Dictionary> _postResponseFactories = []; + private readonly Dictionary> _putResponseFactories = []; + private readonly HashSet _deleteSuccessEndpoints = []; + + /// + /// Gets the authorization response returned for the auth/get-authorization endpoint. + /// + public GetAuthorizationResponse AuthorizationResponse { get; set; } = new(Guid.NewGuid(), "Admin", Enum.GetValues()); + + /// + /// Gets or sets the initialization response returned for the initialization endpoint. + /// + public InitializationResponse InitializationResponse { get; set; } = new() { IsInitialized = true }; + + /// + /// Gets or sets the login response returned for the auth/login endpoint. + /// + public LoginResponse LoginResponse { get; set; } = new(Guid.NewGuid(), "testuser", "test_jwt_token", false); + + /// + /// Gets the list of GET endpoints that were requested. + /// + public List GetEndpointsCalled { get; } = []; + + /// + /// Gets the list of POST requests that were sent, with their payloads. + /// + public List<(string Endpoint, object? Data)> PostRequests { get; } = []; + + /// + /// Gets the list of PUT requests that were sent, with their payloads. + /// + public List<(string Endpoint, object? Data)> PutRequests { get; } = []; + + /// + /// Gets the list of DELETE endpoints that were requested. + /// + public List DeleteEndpointsCalled { get; } = []; + + /// + /// Registers the response returned when the specified GET endpoint is called. + /// + /// The type of the response. + /// The API endpoint for which to register the response. + /// The response to return. + public void RegisterGetResponse(string endpoint, TResponse response) where TResponse : class + { + _getResponseFactories[endpoint] = () => response; + } + + /// + /// Registers the response factory invoked when the specified GET endpoint is called. + /// + /// The API endpoint for which to register the response factory. + /// The factory that produces the response. + public void RegisterGetResponseFactory(string endpoint, Func responseFactory) + { + _getResponseFactories[endpoint] = responseFactory; + } + + /// + /// Registers the response returned when the specified POST endpoint is called. + /// + /// The type of the response. + /// The API endpoint for which to register the response. + /// The response to return. + public void RegisterPostResponse(string endpoint, TResponse response) where TResponse : class + { + _postResponseFactories[endpoint] = _ => response; + } + + /// + /// Registers the response factory invoked when the specified POST endpoint is called. + /// + /// The API endpoint for which to register the response factory. + /// The factory that produces the response from the request payload. + public void RegisterPostResponseFactory(string endpoint, Func responseFactory) + { + _postResponseFactories[endpoint] = responseFactory; + } + + /// + /// Registers the exception thrown when the specified POST endpoint is called. + /// + /// The API endpoint for which to register the exception. + /// The exception to throw. + public void RegisterPostException(string endpoint, ApiException exception) + { + _postResponseFactories[endpoint] = _ => throw exception; + } + + /// + /// Registers the exception thrown when the specified GET endpoint is called. + /// + /// The API endpoint for which to register the exception. + /// The exception to throw. + public void RegisterGetException(string endpoint, ApiException exception) + { + _getResponseFactories[endpoint] = () => throw exception; + } + + /// + /// Registers the response returned when the specified PUT endpoint is called. + /// + /// The type of the response. + /// The API endpoint for which to register the response. + /// The response to return. + public void RegisterPutResponse(string endpoint, TResponse response) where TResponse : class + { + _putResponseFactories[endpoint] = _ => response; + } + + /// + /// Registers the specified DELETE endpoint as succeeding. + /// + /// The API endpoint for which to register success. + public void RegisterDeleteSuccess(string endpoint) + { + _deleteSuccessEndpoints.Add(endpoint); + } + + /// + /// Resets all registered responses and captured requests, keeping only the default responses. + /// + public void Reset() + { + _getResponseFactories.Clear(); + _postResponseFactories.Clear(); + _putResponseFactories.Clear(); + _deleteSuccessEndpoints.Clear(); + GetEndpointsCalled.Clear(); + PostRequests.Clear(); + PutRequests.Clear(); + DeleteEndpointsCalled.Clear(); + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the GET request. + public Task GetAsync(string endpoint, CancellationToken cancellationToken = default) + { + GetEndpointsCalled.Add(endpoint); + if (_getResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory()); + if (endpoint.StartsWith(ApiRoutes.Initialization.CHECK_INITIALIZATION, StringComparison.OrdinalIgnoreCase)) + return Task.FromResult((TResponse)(object)InitializationResponse); + if (endpoint.Contains("auth/get-authorization", StringComparison.OrdinalIgnoreCase)) + return Task.FromResult((TResponse)(object)AuthorizationResponse); + throw new InvalidOperationException($"No GET response is registered for the endpoint '{endpoint}'."); + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result as a streamable response. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// An object, which allows for asynchronous iteration over the deserialized items. + public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await Task.CompletedTask; + yield break; + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// A model containing the deserialized blob. + public Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) + { + throw new NotSupportedException("Blob retrieval is not supported by the test stub."); + } + + /// + /// Sends a DELETE request to the specified as an asynchronous operation. + /// + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + public Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) + { + DeleteEndpointsCalled.Add(endpoint); + if (_deleteSuccessEndpoints.Contains(endpoint)) + return Task.CompletedTask; + throw new ApiException(null, System.Net.HttpStatusCode.InternalServerError, endpoint); + } + + /// + /// Sends a PUT request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and send to the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + public Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + PutRequests.Add((endpoint, data)); + if (_putResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory(data!)); + throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'."); + } + + /// + /// Sends a POST request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and send to the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + public Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + PostRequests.Add((endpoint, data)); + if (_postResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory(data!)); + if (endpoint == ApiRoutes.Authentication.LOGIN_ACCOUNT) + return Task.FromResult((TResponse)(object)LoginResponse); + throw new InvalidOperationException($"No POST response is registered for the endpoint '{endpoint}'."); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs new file mode 100644 index 00000000..af327f97 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Api; + +/// +/// test double that returns a configurable response for every request sent through it. +/// +[ExcludeFromCodeCoverage] +public class TestApiHttpMessageHandler : HttpMessageHandler +{ + private readonly Func _responseFactory; + + /// + /// Gets the list of requests that were sent through this handler. + /// + public List Requests { get; } = []; + + /// + /// Gets the bodies of the requests that were sent through this handler, captured while the request content is still available. + /// + public List RequestBodies { get; } = []; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response for a given request. + public TestApiHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Sends the request to the configured response factory. + /// + /// The HTTP request message to send. + /// Cancellation token that can be used to stop the execution. + /// The configured HTTP response message. + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request); + RequestBodies.Add(request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken)); + return await Task.FromResult(_responseFactory(request)); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs new file mode 100644 index 00000000..858f0dc7 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RoleDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the role. + /// Optional name of the role. + /// A configured instance. + public RoleDto Create(Guid? id = null, string? roleName = null) + { + Faker faker = new(); + return new RoleDto( + Id: id ?? Guid.NewGuid(), + RoleName: roleName ?? faker.Commerce.Department() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs new file mode 100644 index 00000000..b6a98ac1 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional title of the library. + /// Optional type of the library. + /// Whether the media library is enabled or not. + /// Optional collection of directories that contain the library files. + /// A configured instance. + public LibraryDto Create(Guid? id = null, string? title = null, string? libraryType = null, bool? isEnabled = null, List? contentLocations = null) + { + Faker faker = new(); + return new LibraryDto + { + Id = id ?? Guid.NewGuid(), + UserId = Guid.NewGuid(), + Title = title ?? faker.Commerce.Department(), + LibraryType = libraryType ?? faker.PickRandom("Book", "Video", "Photo"), + CoverImage = faker.Image.PicsumUrl(), + ContentLocations = contentLocations ?? [faker.System.DirectoryPath()], + IsEnabled = isEnabled ?? faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs new file mode 100644 index 00000000..74311aa5 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the user that owns the settings. + /// Whether pagination is enabled for the user. + /// Number of library items displayed per page. + /// Whether the "The" prefix is ignored by the alpha picker. + /// A configured instance. + public UserSettingsDto Create(Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, bool? ignoreThePrefixForAlphaPicker = null) + { + Faker faker = new(); + return new UserSettingsDto + { + UserId = userId ?? Guid.NewGuid(), + IsPaginationEnabled = isPaginationEnabled ?? faker.Random.Bool(), + ItemsPerPage = itemsPerPage ?? faker.Random.Int(1, 200), + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs new file mode 100644 index 00000000..0057f6d2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class AddRoleRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional name of the role. + /// Optional collection of permission identifiers. + /// A configured instance. + public AddRoleRequest Create(string? roleName = null, List? permissions = null) + { + Faker faker = new(); + return new AddRoleRequest( + RoleName: roleName ?? faker.Commerce.Department(), + Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs new file mode 100644 index 00000000..73d036cf --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/DeleteRoleRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the role. + /// A configured instance. + public DeleteRoleRequest Create(Guid? roleId = null) + { + return new DeleteRoleRequest( + RoleId: roleId ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs new file mode 100644 index 00000000..3683b3a4 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system path whose directories are retrieved. + /// Whether hidden file system elements are included or not. + /// A configured instance. + public GetDirectoriesRequest Create(string? path = null, bool includeHiddenElements = false) + { + return new GetDirectoriesRequest( + Path: path ?? $"/media/{System.Guid.NewGuid():N}", + IncludeHiddenElements: includeHiddenElements + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs new file mode 100644 index 00000000..4a409d37 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system path to validate. + /// A configured instance. + public ValidatePathRequest Create(string? path = null) + { + return new ValidatePathRequest( + Path: path ?? $"/media/{System.Guid.NewGuid():N}" + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs new file mode 100644 index 00000000..7bf7557f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Enums.Common; +using Lumina.Presentation.Web.Common.Requests.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional page of results to retrieve. + /// Optional number of books to retrieve per page. + /// Optional search term used to filter results. + /// Optional alpha key used to filter the results. + /// Whether the leading "The " prefix is ignored by the alpha picker. + /// Optional name of the field by which to sort the results. + /// Optional direction in which to sort the results. + /// A configured instance. + public GetBooksLiteRequest Create( + Guid? libraryId = null, + int? currentPage = null, + int? perPage = null, + string? searchTerm = null, + string? filterAlphaKey = null, + bool ignoreThePrefixForAlphaPicker = false, + string? sortBy = null, + SortOrder? sortOrder = null) + { + return new GetBooksLiteRequest + { + LibraryId = libraryId ?? Guid.NewGuid(), + CurrentPage = currentPage, + PerPage = perPage, + SearchTerm = searchTerm, + FilterAlphaKey = filterAlphaKey, + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker, + SortBy = sortBy, + SortOrder = sortOrder + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs new file mode 100644 index 00000000..e2997aa2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/DeleteLibraryRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// A configured instance. + public DeleteLibraryRequest Create(Guid? id = null) + { + return new DeleteLibraryRequest( + Id: id ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs new file mode 100644 index 00000000..725afc87 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the plugin. + /// Optional dictionary of settings. + /// A configured instance. + public UpdatePluginSettingsRequest Create(Guid? pluginId = null, Dictionary? settings = null) + { + Faker faker = new(); + return new UpdatePluginSettingsRequest + { + PluginId = pluginId ?? Guid.NewGuid(), + Settings = settings ?? new Dictionary { [faker.Lorem.Word()] = faker.Lorem.Word() } + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs new file mode 100644 index 00000000..2c3cd82d --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Tools/SetLanguageRequestFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Tools; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Tools; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional new culture to set. + /// Optional URL to return to, after setting the new culture. + /// A configured instance. + public SetLanguageRequest Create(string? newCulture = "en-US", string? returnUrl = null) + { + return new SetLanguageRequest( + NewCulture: newCulture, + ReturnUrl: returnUrl + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs new file mode 100644 index 00000000..fe08c93e --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement.Authentication; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LoginViewRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional URL to return to, after login. + /// A configured instance. + public LoginViewRequest Create(string? returnUrl = null) + { + Faker faker = new(); + return new LoginViewRequest( + ReturnUrl: returnUrl ?? $"/{faker.Random.AlphaNumeric(8)}" + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs new file mode 100644 index 00000000..a0e75deb --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional current password. + /// Optional new password. + /// Optional confirmation of the new password. + /// A configured instance. + public ChangePasswordRequest Create(string? username = null, string? currentPassword = null, string? newPassword = null, string? newPasswordConfirm = null) + { + Faker faker = new(); + string generatedNewPassword = newPassword ?? faker.Internet.Password(12); + return new ChangePasswordRequest( + Username: username ?? faker.Internet.UserName(), + CurrentPassword: currentPassword ?? faker.Internet.Password(12), + NewPassword: generatedNewPassword, + NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs new file mode 100644 index 00000000..9d39afdb --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional password. + /// Optional TOTP code. + /// Optional URL to return to, after login. + /// A configured instance. + public LoginRequest Create(string? username = null, string? password = null, string? totpCode = null, string? returnUrl = null) + { + Faker faker = new(); + return new LoginRequest( + Username: username ?? faker.Internet.UserName(), + Password: password ?? faker.Internet.Password(12), + TotpCode: totpCode, + ReturnUrl: returnUrl + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs new file mode 100644 index 00000000..cb8f2ce5 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional TOTP code. + /// A configured instance. + public RecoverPasswordRequest Create(string? username = null, string? totpCode = null) + { + Faker faker = new(); + return new RecoverPasswordRequest( + Username: username ?? faker.Internet.UserName(), + TotpCode: totpCode + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs new file mode 100644 index 00000000..a6596a66 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RegisterRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username. + /// Optional password. + /// Optional password confirmation. + /// Optional registration type, e.g. "Admin" or "User". + /// Whether two-factor authentication is enabled for the account. + /// A configured instance. + public RegisterRequest Create(string? username = null, string? password = null, string? passwordConfirm = null, string? registrationType = "User", bool use2fa = true) + { + Faker faker = new(); + string generatedPassword = password ?? faker.Internet.Password(12); + return new RegisterRequest( + Username: username ?? faker.Internet.UserName(), + Password: generatedPassword, + PasswordConfirm: passwordConfirm ?? generatedPassword, + RegistrationType: registrationType, + Use2fa: use2fa + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/JsonResultTestHelper.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/JsonResultTestHelper.cs new file mode 100644 index 00000000..f737af84 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/JsonResultTestHelper.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers; + +/// +/// Helper for executing instances and reading the JSON response body they produce. +/// +[ExcludeFromCodeCoverage] +public static class JsonResultTestHelper +{ + /// + /// Executes the specified against a fresh HTTP context and reads the response body. + /// + /// The result to execute. + /// Optional HTTP context to execute the result against; a fresh context is created when not provided. + /// The response body produced by the result. + public static async Task GetResponseBodyAsync(IResult result, HttpContext? httpContext = null) + { + DefaultHttpContext context = httpContext as DefaultHttpContext ?? TestHttpContextFactory.Create(); + await result.ExecuteAsync(context); + context.Response.Body.Position = 0; + return await new StreamReader(context.Response.Body).ReadToEndAsync(); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/TestHttpContextFactory.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/TestHttpContextFactory.cs new file mode 100644 index 00000000..5727e891 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/TestHttpContextFactory.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Security.Claims; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers; + +/// +/// Factory for creating and configuring instances for unit testing Web endpoints. +/// +[ExcludeFromCodeCoverage] +public static class TestHttpContextFactory +{ + /// + /// Creates a with a writable response body, optional culture route value, session and user. + /// + /// The value of the culture route value. + /// The user associated with the context, for anonymous requests. + /// The session associated with the context, when no session is available. + /// A configured instance. + public static DefaultHttpContext Create(string? culture = "en-US", ClaimsPrincipal? user = null, ISession? session = null) + { + DefaultHttpContext httpContext = new(); + // provide a writable response body, so that executed IResult instances can be inspected by the tests + httpContext.Features.Set(new StreamResponseBodyFeature(new MemoryStream())); + // provide the minimal services needed by the result execution machinery (logging, options, JSON options) + httpContext.RequestServices = CreateServiceProvider(); + httpContext.Request.RouteValues["culture"] = culture; + if (user is not null) + httpContext.User = user; + if (session is not null) + httpContext.Features.Set(new TestSessionFeature { Session = session }); + return httpContext; + } + + /// + /// Creates a service provider that provides the minimal services needed by the result execution machinery. + /// + /// A configured instance. + public static IServiceProvider CreateServiceProvider() + { + ServiceCollection services = new(); + services.AddLogging(); + services.AddOptions(); + services.Configure(jsonOptions => jsonOptions.SerializerOptions.MaxDepth = 256); + return services.BuildServiceProvider(); + } + + /// + /// Attaches a session to the provided HTTP context. + /// + /// The HTTP context to configure. + /// The session to attach. + public static void ConfigureSession(HttpContext httpContext, ISession session) + { + httpContext.Features.Set(new TestSessionFeature { Session = session }); + } + + /// + /// Attaches a user to the provided HTTP context. + /// + /// The HTTP context to configure. + /// The user to attach. + public static void ConfigureUser(HttpContext httpContext, ClaimsPrincipal user) + { + httpContext.User = user; + } + + /// + /// Sets the value of the culture route value of the provided HTTP context. + /// + /// The HTTP context to configure. + /// The culture to set. + public static void ConfigureCulture(HttpContext httpContext, string? culture) + { + httpContext.Request.RouteValues["culture"] = culture; + } + + /// + /// Creates a mock that supports the GetString and SetString extension methods. + /// + /// A mock instance. + public static ISession CreateSession() + { + ISession session = Substitute.For(); +#pragma warning disable CS8601 // possible null reference assignment in the NSubstitute out-argument stub + session.TryGetValue(Arg.Any(), out Arg.Any()).Returns(callInfo => + { + callInfo[1] = null; + return false; + }); +#pragma warning restore CS8601 + return session; + } + + /// + /// Creates an authenticated with the specified username. + /// + /// The username of the authenticated user. + /// An authenticated instance. + public static ClaimsPrincipal CreateAuthenticatedUser(string username = "testuser") + { + return new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, username)], "TestAuthentication")); + } + + /// + /// Minimal implementation used to attach a session to test HTTP contexts. + /// + [ExcludeFromCodeCoverage] + private sealed class TestSessionFeature : ISessionFeature + { + /// + /// Gets or sets the session associated with the feature. + /// + public ISession Session { get; set; } = null!; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs new file mode 100644 index 00000000..ba8de2a2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Microsoft.AspNetCore.Mvc.Testing; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers; + +/// +/// Represents an HTTP client that has been authenticated through the real login flow of the Web application. +/// +/// The authenticated HTTP client. +/// The antiforgery token captured before the login, valid for subsequent mutating requests. +[ExcludeFromCodeCoverage] +public record AuthenticatedWebClient(HttpClient Client, string AntiforgeryToken); + +/// +/// Helper methods for exercising the authentication and antiforgery flows of the Web application in integration and security tests. +/// +[ExcludeFromCodeCoverage] +public static partial class WebTestHelpers +{ + private const string LOGIN_PAGE_PATH = "/en-us/auth/login"; + private const string LOGIN_ENDPOINT_PATH = "/en-us/auth/api-login"; + + [GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]*)\"")] + private static partial Regex AntiforgeryTokenRegex(); + + /// + /// Creates an anonymous HTTP client that does not follow redirects. + /// + /// The Web application factory. + /// An anonymous HTTP client. + public static HttpClient CreateAnonymousClient(WebApplicationFactory factory) + { + return factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + } + + /// + /// Creates an HTTP client that has been authenticated through the real login flow of the application. + /// + /// The Web application factory. + /// The username to authenticate with. + /// The password to authenticate with. + /// An HTTP client authenticated with the application's authentication cookie, together with an antiforgery token. + public static async Task CreateAuthenticatedClientAsync(WebApplicationFactory factory, string? username = "testuser", string? password = "TestPass123!") + { + // the application marks its cookies as secure, so the test client must communicate over HTTPS for the cookies to be sent back + HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions + { + BaseAddress = new Uri("https://localhost"), + AllowAutoRedirect = false + }); + string antiforgeryToken = await GetAntiforgeryTokenAsync(client); + await LoginAsync(client, username!, password!, antiforgeryToken); + return new AuthenticatedWebClient(client, antiforgeryToken); + } + + /// + /// Performs the login flow of the application against the provided client. + /// + /// The HTTP client to log in through. + /// The username to authenticate with. + /// The password to authenticate with. + /// The antiforgery token to send with the login request. + public static async Task LoginAsync(HttpClient client, string username, string password, string antiforgeryToken) + { + HttpRequestMessage loginRequest = new(HttpMethod.Post, LOGIN_ENDPOINT_PATH) + { + Content = JsonContent.Create(new LoginRequest(Username: username, Password: password)) + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + HttpResponseMessage response = await client.SendAsync(loginRequest); + response.EnsureSuccessStatusCode(); + } + + /// + /// Retrieves the antiforgery token and cookie by requesting the login page. + /// + /// The HTTP client to retrieve the token through. + /// The antiforgery token value. + public static async Task GetAntiforgeryTokenAsync(HttpClient client) + { + HttpResponseMessage loginPageResponse = await client.GetAsync(LOGIN_PAGE_PATH); + loginPageResponse.EnsureSuccessStatusCode(); + string loginPageHtml = await loginPageResponse.Content.ReadAsStringAsync(); + Match match = AntiforgeryTokenRegex().Match(loginPageHtml); + if (!match.Success) + throw new InvalidOperationException("Could not find the antiforgery token on the login page."); + return System.Net.WebUtility.HtmlDecode(match.Groups[1].Value); + } + + /// + /// Deserializes a JSON response body into a . + /// + /// The HTTP response whose body is deserialized. + /// The parsed . + public static async Task ReadJsonAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonDocument.Parse(content); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs new file mode 100644 index 00000000..134d8c23 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Core.Endpoints.Common; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +[DontRegister] +public class BaseEndpointFixture : BaseEndpoint +{ + /// + /// Exposes the Culture property of the class. + /// + public string TestCulture => Culture; + + /// + /// Renders a Razor view through the helper. + /// + /// The name or path of the view to render. + /// The model to pass to the view. + /// Optional additional view data entries made available to the view via ViewData. + /// An that renders the view. + public IResult TestView(string viewName, object? model = null, IReadOnlyDictionary? viewData = null) + { + return View(viewName, model, viewData); + } + + /// + /// Creates a JSON response indicating a successful operation through the helper. + /// + /// The payload of the successful response. + /// An containing the success JSON payload. + public IResult TestJsonSuccess(object? data) + { + return JsonSuccess(data); + } + + /// + /// Creates a JSON response indicating a successful operation without a payload through the helper. + /// + /// An containing the success JSON payload. + public IResult TestJsonSuccess() + { + return JsonSuccess(); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + } + + /// + /// Handles the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + /// An containing the success JSON payload. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(TestJsonSuccess()); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj b/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj new file mode 100644 index 00000000..23889ee3 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Lumina.Presentation.Web.Fixtures.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\web\ + + false + false + false + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..ed54683a --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Presentation.Web.Fixtures")] +[assembly: AssemblyProduct("Lumina.Presentation.Web.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("B7C8D9E0-0001-4C5D-8E1F-222222222222")] + +[assembly: InternalsVisibleTo("Lumina.Presentation.Web.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Web.IntegrationTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Web.SecurityTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs index ef35ee34..8815cb3e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs @@ -2,6 +2,7 @@ using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement; using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using Xunit; #endregion @@ -12,6 +13,7 @@ namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; /// Marks a test to be skipped when the file system does not support the attribute. /// [AttributeUsage(AttributeTargets.Method)] +[ExcludeFromCodeCoverage] public sealed class SkipWhenHiddenAttributeNotSupportedFactAttribute : FactAttribute { /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Documentation/OpenApiEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Documentation/OpenApiEndpointTests.cs new file mode 100644 index 00000000..e2dea7f3 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Documentation/OpenApiEndpointTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Common.Documentation; + +/// +/// Contains integration tests for the OpenAPI and Scalar documentation endpoints of the Web application. +/// +[ExcludeFromCodeCoverage] +public class OpenApiEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public OpenApiEndpointTests(LuminaWebFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task OpenApi_WhenRequested_ShouldServeDocument() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/openapi/v1.json"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("openapi", content); + } + + [Fact] + public async Task Scalar_WhenRequested_ShouldServeReferencePage() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/scalar/v1"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs new file mode 100644 index 00000000..0ade61d2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Common.Setup; + +/// +/// Factory for creating the Web application for integration tests, with the remote API client replaced by a configurable stub. +/// +[ExcludeFromCodeCoverage] +public class LuminaWebFactory : WebApplicationFactory, IDisposable +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + + /// + /// Gets the stub used in place of the remote API client. + /// + public StubApiHttpClient ApiClientStub { get; } = new(); + + /// + /// Initializes a new instance of the class. + /// + public LuminaWebFactory() + { + } + + /// + /// Configures the web host for the integration tests. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureAppConfiguration((context, config) => + { + // provide the application configuration values that the Web app validates on startup + config.AddInMemoryCollection(initialData: new Dictionary + { + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY, + ["ServerConfiguration:ApiVersion"] = "1", + ["ServerConfiguration:BaseAddress"] = "http://localhost", + ["ServerConfiguration:Port"] = "5214" + }); + }); + builder.ConfigureServices(services => + { + // remove the typed HTTP client registration, so that the stub can take its place + ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray(); + foreach (ServiceDescriptor descriptor in apiClientDescriptors) + services.Remove(descriptor); + services.AddSingleton(ApiClientStub); + }); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs new file mode 100644 index 00000000..6ed6f97b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRoles_WhenCalledByAdminUser_ShouldReturnRolesJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []); + RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin"), new RoleDto(Guid.NewGuid(), "User")]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(2, json.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task GetRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs new file mode 100644 index 00000000..25f1c76d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture} and / routes served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeIndexEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeIndexEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Home_WhenCalledWithoutCulture_ShouldRedirectToDefaultCulture() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/en-us/", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task Home_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task Home_WhenCalledByAuthenticatedUser_ShouldReturnHomePage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("html", content); + } + + [Theory] + [InlineData("/de-de")] // German culture + [InlineData("/fr-fr")] // French culture + [InlineData("/ja-jp")] // Japanese culture + public async Task Home_WhenCalledByAuthenticatedUserWithLocalizedCulture_ShouldReturnHomePage(string culturePath) + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(culturePath); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..5f793a82 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnLibrariesJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto[] expectedLibraries = + [ + new LibraryDto { Id = Guid.NewGuid(), Title = "Books", LibraryType = "Book" }, + new LibraryDto { Id = Guid.NewGuid(), Title = "Movies", LibraryType = "Video" } + ]; + _apiFactory.ApiClientStub.RegisterGetResponse("libraries", expectedLibraries); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(2, data.GetArrayLength()); + Assert.Equal("Books", data[0].GetProperty("title").GetString()); + } + + [Fact] + public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-libraries"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetLibraries_WhenCalled_ShouldRequestLibrariesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("libraries", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("libraries", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs new file mode 100644 index 00000000..ceea2a3c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SaveLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SaveLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SaveLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldSaveLibraryAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto request = new() { Title = "New Books Library", LibraryType = "Book" }; + LibraryDto expectedResponse = new() { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType }; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(request) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs new file mode 100644 index 00000000..1fba9da5 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Language.SetLanguage; + +/// +/// Contains integration tests for the /{culture}/tools/language/set-language route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetLanguageEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetLanguage_WhenCalledByAuthenticatedUser_ShouldSetCultureCookieAndRedirectWithNewCulture() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string returnUrl = Uri.EscapeDataString("/en-us/tools/settings"); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/tools/language/set-language?newCulture=de-DE&returnUrl={returnUrl}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/de-de/tools/settings", response.Headers.Location!.ToString()); + Assert.Contains("de-DE", response.Headers.GetValues("Set-Cookie").First()); + } + + [Fact] + public async Task SetLanguage_WhenCalledByAuthenticatedUserWithoutReturnUrl_ShouldRedirectToHomePageWithNewCulture() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/tools/language/set-language?newCulture=de-DE"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/de-de", response.Headers.Location!.ToString()); + Assert.Contains("de-DE", response.Headers.GetValues("Set-Cookie").First()); + } + + [Fact] + public async Task SetLanguage_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/tools/language/set-language?newCulture=de-DE"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs new file mode 100644 index 00000000..2195b24c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains integration tests for the /{culture}/auth/api-login route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldSignInAndReturnRedirectUrl() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("/en-us/", json.RootElement.GetProperty("data").GetString()); + string allSetCookies = string.Join("; ", response.Headers.GetValues("Set-Cookie")); + Assert.Contains(".Lumina.Auth", allSetCookies); + Assert.Contains("Token=", allSetCookies); + } + + [Fact] + public async Task Login_WhenTotpRequired_ShouldReturnTotpRequiredSignal() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ProblemDetailsDto problemDetails = new() + { + Title = "General.Validation", + Detail = "OneOrMoreValidationErrorsOccurred", + Extensions = new Dictionary + { + ["errors"] = CreateErrorsElement(["InvalidTotpCode"]) + } + }; + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, "auth/login")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isTotpRequired").GetBoolean()); + } + + [Fact] + public async Task Login_WhenApiReturnsForbidden_ShouldReturnFailureJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "WrongPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString()); + } + + private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken) + { + HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login") + { + Content = JsonContent.Create(request) + }; + loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return loginRequest; + } + + private static JsonElement CreateErrorsElement(string[] errorCodes) + { + using MemoryStream stream = new(); + using (Utf8JsonWriter writer = new(stream)) + { + writer.WriteStartObject(); + writer.WriteStartArray("General.Validation"); + foreach (string errorCode in errorCodes) + writer.WriteStringValue(errorCode); + writer.WriteEndArray(); + writer.WriteEndObject(); + } + return JsonDocument.Parse(stream.ToArray()).RootElement.Clone(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs new file mode 100644 index 00000000..67cb7f45 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains integration tests for the /{culture}/auth/login/{returnUrl?} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LoginView_WhenCalled_ShouldRenderLoginPage() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/login"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("login-form", content); + } + + [Theory] + [InlineData("/de-de/auth/login")] // German culture + [InlineData("/fr-fr/auth/login")] // French culture + [InlineData("/zh-cn/auth/login")] // Chinese culture + public async Task LoginView_WhenCalledWithLocalizedCulture_ShouldRenderLoginPage(string culturePath) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await client.GetAsync(culturePath); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("login-form", content); + } + + [Fact] + public async Task LoginView_WhenCalledWithReturnUrl_ShouldPreserveReturnUrlInView() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/login/some-return-url"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("some-return-url", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj new file mode 100644 index 00000000..2ec3ddb4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Lumina.Presentation.Web.IntegrationTests.csproj @@ -0,0 +1,46 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs new file mode 100644 index 00000000..ba24862e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Common.Setup; + +/// +/// Factory for creating the Web application for security tests, with the remote API client replaced by a configurable stub. +/// +[ExcludeFromCodeCoverage] +public class LuminaWebFactory : WebApplicationFactory, IDisposable +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + + /// + /// Gets the stub used in place of the remote API client. + /// + public StubApiHttpClient ApiClientStub { get; } = new(); + + /// + /// Initializes a new instance of the class. + /// + public LuminaWebFactory() + { + } + + /// + /// Configures the web host for the security tests. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureAppConfiguration((context, config) => + { + // provide the application configuration values that the Web app validates on startup + config.AddInMemoryCollection(initialData: new Dictionary + { + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY, + ["ServerConfiguration:ApiVersion"] = "1", + ["ServerConfiguration:BaseAddress"] = "http://localhost", + ["ServerConfiguration:Port"] = "5214" + }); + }); + builder.ConfigureServices(services => + { + // remove the typed HTTP client registration, so that the stub can take its place + ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray(); + foreach (ServiceDescriptor descriptor in apiClientDescriptors) + services.Remove(descriptor); + services.AddSingleton(ApiClientStub); + }); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs new file mode 100644 index 00000000..7e021ace --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Contains security tests for the /{culture}/admin/api-get-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRoles_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetRoles_WhenCalledByAdminUser_ShouldReturnRolesData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []); + RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin")]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} + diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..ca7a3bf4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + [Fact] + public async Task DeleteLibrary_WhenCalledWithoutAuthentication_ShouldNotDeleteLibrary() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + private static HttpRequestMessage CreateDeleteRequest(Guid libraryId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/libraries/manage/api-item/{libraryId}") + { + // the front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs new file mode 100644 index 00000000..16917b88 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SaveLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SaveLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }); + saveRequest.Headers.Remove("RequestVerificationToken"); + saveRequest.Headers.Add("RequestVerificationToken", "invalid-antiforgery-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenCalledWithInjectionInLibraryTitle_ShouldRemainSecure() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto request = new() { Title = "'; DROP TABLE Libraries--", LibraryType = "Book" }; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", new LibraryDto { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(request); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", content); + } + + private static HttpRequestMessage CreateSaveRequest(LibraryDto request) + { + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(request) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return saveRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs new file mode 100644 index 00000000..4b186aa1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains security tests for the /{culture}/auth/api-login route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task Login_WithInjectionAttemptInUsername_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: maliciousUsername, Password: "Abcd123$"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", content); + Assert.DoesNotContain("Abcd123$", content); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldNotExposeSensitiveData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("TestPass123!", content); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + // the JWT token returned by the API must not be exposed in plaintext; it is stored encrypted in the Token cookie + Assert.DoesNotContain("test_jwt_token", content); + string allSetCookies = string.Join("; ", response.Headers.GetValues("Set-Cookie")); + Assert.Contains("Token=", allSetCookies); + Assert.DoesNotContain("test_jwt_token", allSetCookies); + } + + [Fact] + public async Task Login_WhenCalled_ShouldSetAuthenticationCookieWithSecurityAttributes() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(loginRequest); + + // Assert + response.EnsureSuccessStatusCode(); + string authCookie = response.Headers.GetValues("Set-Cookie").First(cookie => cookie.StartsWith(".Lumina.Auth", StringComparison.Ordinal)); + Assert.Contains("httponly", authCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("secure", authCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("samesite=strict", authCookie, StringComparison.OrdinalIgnoreCase); + string tokenCookie = response.Headers.GetValues("Set-Cookie").First(cookie => cookie.StartsWith("Token=", StringComparison.Ordinal) && !cookie.Contains("1970")); + Assert.Contains("httponly", tokenCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("secure", tokenCookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("samesite=strict", tokenCookie, StringComparison.OrdinalIgnoreCase); + } + + private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken) + { + HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login") + { + Content = JsonContent.Create(request) + }; + loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return loginRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj new file mode 100644 index 00000000..7a0745c3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Lumina.Presentation.Web.SecurityTests.csproj @@ -0,0 +1,46 @@ + + + + net10.0 + enable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index 61296609..47ee328b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -7,6 +7,7 @@ using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Boo using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -14,6 +15,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten /// /// Contains unit tests for the class. /// +[ExcludeFromCodeCoverage] public class BookMetadataDtoMappingTests { private readonly BookFixture _bookFixture = new(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs index cc9acf45..bc591850 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Common.Setup; @@ -9,6 +10,7 @@ namespace Lumina.Application.UnitTests.Common.Setup; /// /// Validator extension methods for for unit tests. /// +[ExcludeFromCodeCoverage] public static class ValidatorTestExtensions { /// diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs index 9821f0f5..fa2c46ea 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs @@ -6,6 +6,7 @@ using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Primitives; using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -16,6 +17,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins; /// /// Contains unit tests for the class. /// +[ExcludeFromCodeCoverage] public class LibraryMetadataProviderConfigurationRepositoryTests { private readonly LuminaDbContext _mockContext; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs index 0730c42e..a0ae9321 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs @@ -7,6 +7,7 @@ using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -17,6 +18,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins; /// /// Contains unit tests for the class. /// +[ExcludeFromCodeCoverage] public class PluginRepositoryTests { private readonly LuminaDbContext _mockContext; diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs new file mode 100644 index 00000000..b56c9832 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs @@ -0,0 +1,177 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ApiHttpClientTests +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + + [Fact] + public async Task GetAsync_WhenApiReturnsSuccess_ShouldDeserializeResponseContent() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + Lumina.Presentation.Web.Common.DTO.Libraries.LibraryDto[] result = await sut.GetAsync("libraries", CancellationToken.None); + + // Assert + Assert.Single(result); + Assert.Equal("Library One", result[0].Title); + Assert.Equal(new Uri("http://localhost:5214/api/v1/libraries"), messageHandler.Requests[0].RequestUri); + } + + [Fact] + public async Task GetAsync_WhenApiReturnsError_ShouldThrowApiExceptionWithProblemDetails() + { + // Arrange + string problemDetailsJson = """ + { + "type": "https://tools.ietf.org/html/rfc4918#section-11.2", + "title": "General.Validation", + "status": 422, + "detail": "OneOrMoreValidationErrorsOccurred" + } + """; + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.UnprocessableEntity, problemDetailsJson)); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + ApiException exception = await Assert.ThrowsAsync(() => sut.GetAsync("libraries", CancellationToken.None)); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, exception.HttpStatusCode); + Assert.NotNull(exception.ProblemDetails); + Assert.Equal("General.Validation", exception.ProblemDetails!.Title); + Assert.Equal(422, exception.ProblemDetails.Status); + Assert.Equal("OneOrMoreValidationErrorsOccurred", exception.ProblemDetails.Detail); + } + + [Fact] + public async Task GetAsync_WhenApiReturnsEmptyContent_ShouldReturnDefault() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(string.Empty) }); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + object? result = await sut.GetAsync("libraries", CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetAsync_WhenUserHasTokenClaim_ShouldSendAuthorizationHeader() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}")); + ApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token"); + + // Act + await sut.GetAsync("libraries", CancellationToken.None); + + // Assert + Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme); + Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter); + } + + [Fact] + public async Task PostAsync_WhenCalled_ShouldSerializePayloadAndDeserializeResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"success":true}""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + SuccessResponse result = await sut.PostAsync("auth/login", new { username = "testuser" }, CancellationToken.None); + + // Assert + Assert.True(result.Success); + Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method); + Assert.Equal("http://localhost:5214/api/v1/auth/login", messageHandler.Requests[0].RequestUri!.ToString()); + Assert.Contains("testuser", messageHandler.RequestBodies[0]); + } + + [Fact] + public async Task DeleteAsync_WhenApiReturnsError_ShouldThrowApiException() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.InternalServerError, """{"title":"General.Failure","status":500}""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + ApiException exception = await Assert.ThrowsAsync(() => sut.DeleteAsync("libraries/1", CancellationToken.None)); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode); + Assert.Equal("/api/v1/libraries/1", exception.RequestPath); + } + + [Fact] + public async Task GetBlobAsync_WhenApiReturnsSuccess_ShouldReturnBlobData() + { + // Arrange + byte[] imageBytes = Encoding.UTF8.GetBytes("fake-image-bytes"); + TestApiHttpMessageHandler messageHandler = new(_ => + { + HttpResponseMessage response = new(HttpStatusCode.OK) { Content = new ByteArrayContent(imageBytes) }; + response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); + return response; + }); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + BlobDataDto blob = await sut.GetBlobAsync("libraries/1/cover", CancellationToken.None); + + // Assert + Assert.Equal(imageBytes, blob.Data); + Assert.Equal("image/png", blob.ContentType); + } + + private static ApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null) + { + HttpClient httpClient = new(messageHandler); + IHttpContextAccessor httpContextAccessor = Substitute.For(); + if (token is not null) + { + DefaultHttpContext httpContext = new(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("Token", token)], "TestAuthentication")); + httpContextAccessor.HttpContext.Returns(httpContext); + } + IOptionsSnapshot serverConfigurationOptions = Substitute.For>(); + serverConfigurationOptions.Value.Returns(new ServerConfigurationDto { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 }); + return new ApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions); + } + + private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json) + { + return new HttpResponseMessage(statusCode) + { + Content = new StringContent(json, Encoding.UTF8, "application/json") + }; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationPoliciesTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationPoliciesTests.cs new file mode 100644 index 00000000..9421e58d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationPoliciesTests.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Authorization; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Authorization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationPoliciesTests +{ + [Fact] + public void PolicyNames_WhenRead_ShouldMatchExpectedPolicyNames() + { + // Act & Assert + Assert.Equal("RequireAdminRole", AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + Assert.Equal("RequireCreateLibrariesPermission", AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); + Assert.Equal("RequireInitialization", AuthorizationPolicies.REQUIRE_INITIALIZATION); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs new file mode 100644 index 00000000..de8002c4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Authorization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationServiceTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AuthorizationService _sut; + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public AuthorizationServiceTests() + { + _userId = Guid.NewGuid(); + _mockApiHttpClient = Substitute.For(); + IHttpContextAccessor httpContextAccessor = Substitute.For(); + DefaultHttpContext httpContext = new(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication")); + httpContextAccessor.HttpContext.Returns(httpContext); + _sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor); + } + + [Fact] + public async Task HasPermissionAsync_WhenUserHasPermission_ShouldReturnTrue() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanCreateLibraries])); + + // Act + bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None); + + // Assert + Assert.True(result); + } + + [Fact] + public async Task HasPermissionAsync_WhenUserDoesNotHavePermission_ShouldReturnFalse() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanViewUsers])); + + // Act + bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task IsInRoleAsync_WhenRoleMatches_ShouldReturnTrue() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [])); + + // Act + bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None); + + // Assert + Assert.True(result); + } + + [Fact] + public async Task IsInRoleAsync_WhenRoleDoesNotMatch_ShouldReturnFalse() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "User", [])); + + // Act + bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task HasPermissionAsync_WhenCalled_ShouldRequestAuthorizationForCurrentUser() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new GetAuthorizationResponse(_userId, "Admin", [])); + + // Act + await _sut.HasPermissionAsync(AuthorizationPermission.CanViewUsers, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Localization/CoreHtmlLocalizerFactoryTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Localization/CoreHtmlLocalizerFactoryTests.cs new file mode 100644 index 00000000..017b060e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Localization/CoreHtmlLocalizerFactoryTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Localization; +using Microsoft.AspNetCore.Mvc.Localization; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Localization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CoreHtmlLocalizerFactoryTests +{ + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly CoreHtmlLocalizerFactory _sut; + + /// + /// Initializes a new instance of the class. + /// + public CoreHtmlLocalizerFactoryTests() + { + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(Substitute.For()); + _sut = new CoreHtmlLocalizerFactory(_mockStringLocalizerFactory); + } + + [Fact] + public void Create_WhenBaseNameStartsWithLocationCorePrefix_ShouldStripCoreSegment() + { + // Act + IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Core.Views.Auth.Login", "Lumina.Presentation.Web"); + + // Assert + Assert.NotNull(localizer); + _mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Auth.Login", "Lumina.Presentation.Web"); + } + + [Fact] + public void Create_WhenBaseNameDoesNotStartWithLocationCorePrefix_ShouldKeepBaseNameUnchanged() + { + // Act + IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web"); + + // Assert + Assert.NotNull(localizer); + _mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web"); + } + + [Fact] + public void Create_WhenResourceSourceTypeProvided_ShouldCreateLocalizerForType() + { + // Arrange + _mockStringLocalizerFactory.Create(Arg.Any()).Returns(Substitute.For()); + + // Act + IHtmlLocalizer localizer = _sut.Create(typeof(TestLocalizationResource)); + + // Assert + Assert.NotNull(localizer); + _mockStringLocalizerFactory.Received(1).Create(typeof(TestLocalizationResource)); + } + + /// + /// Marker type used for the resource source based localizer creation test. + /// + [ExcludeFromCodeCoverage] + private sealed class TestLocalizationResource + { + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs new file mode 100644 index 00000000..6929a5f3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Security; +using Microsoft.Extensions.Options; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Security; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CryptographyServiceTests +{ + private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + private readonly CryptographyService _sut; + + /// + /// Initializes a new instance of the class. + /// + public CryptographyServiceTests() + { + EncryptionSettingsDto settings = new() { SecretKey = TEST_ENCRYPTION_KEY }; + _sut = new CryptographyService(Options.Create(settings)); + } + + [Fact] + public void Encrypt_WhenCalled_ShouldReturnCiphertextThatDecryptsToPlaintext() + { + // Arrange + const string plaintext = "sensitive-data"; + + // Act + string ciphertext = _sut.Encrypt(plaintext); + + // Assert + Assert.NotEqual(plaintext, ciphertext); + Assert.Equal(plaintext, _sut.Decrypt(ciphertext)); + } + + [Fact] + public void Encrypt_WhenCalledTwice_ShouldReturnDifferentCiphertexts() + { + // Arrange + const string plaintext = "sensitive-data"; + + // Act + string firstCiphertext = _sut.Encrypt(plaintext); + string secondCiphertext = _sut.Encrypt(plaintext); + + // Assert + Assert.NotEqual(firstCiphertext, secondCiphertext); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void Encrypt_WhenPlaintextIsNullOrEmpty_ShouldThrowArgumentException(string? plaintext) + { + // Act + ArgumentException exception = Assert.Throws(() => _sut.Encrypt(plaintext!)); + + // Assert + Assert.Equal("plaintext", exception.ParamName); + } + + [Fact] + public void Decrypt_WhenCiphertextIsNotValidBase64_ShouldThrowFormatException() + { + // Act + FormatException exception = Assert.Throws(() => _sut.Decrypt("not-valid-base64!!!")); + + // Assert + Assert.Contains("Base-64", exception.Message); + } + + [Fact] + public void Decrypt_WhenCiphertextIsTooShort_ShouldThrowArgumentException() + { + // Act + ArgumentException exception = Assert.Throws(() => _sut.Decrypt(Convert.ToBase64String([1, 2, 3]))); + + // Assert + Assert.Equal("Invalid ciphertext", exception.Message); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ScriptIdentifierHelperTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ScriptIdentifierHelperTests.cs new file mode 100644 index 00000000..7c2cf6a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ScriptIdentifierHelperTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Services; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScriptIdentifierHelperTests +{ + [Fact] + public void GenerateScriptId_WhenCalled_ShouldReturnScriptPrefixedIdentifier() + { + // Act + string scriptId = ScriptIdentifierHelper.GenerateScriptId(); + + // Assert + Assert.StartsWith("script_", scriptId); + Assert.True(Guid.TryParse(scriptId.AsSpan("script_".Length), out _)); + } + + [Fact] + public void GenerateScriptId_WhenCalledTwice_ShouldReturnDistinctIdentifiers() + { + // Act + string firstScriptId = ScriptIdentifierHelper.GenerateScriptId(); + string secondScriptId = ScriptIdentifierHelper.GenerateScriptId(); + + // Assert + Assert.NotEqual(firstScriptId, secondScriptId); + } + + [Fact] + public void ClearIdentifier_WhenCalledWithGeneratedIdentifier_ShouldNotThrow() + { + // Arrange + string scriptId = ScriptIdentifierHelper.GenerateScriptId(); + + // Act + ScriptIdentifierHelper.ClearIdentifier(scriptId); + + // Assert + Assert.NotNull(scriptId); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/UrlServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/UrlServiceTests.cs new file mode 100644 index 00000000..868dbfc5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/UrlServiceTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UrlServiceTests +{ + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly UrlService _sut; + + /// + /// Initializes a new instance of the class. + /// + public UrlServiceTests() + { + _mockHttpContextAccessor = Substitute.For(); + _sut = new UrlService(_mockHttpContextAccessor); + } + + [Fact] + public void GetAbsoluteUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException() + { + // Act + ArgumentException exception = Assert.Throws(() => _sut.GetAbsoluteUrl("/not-a-real-route")); + + // Assert + Assert.Contains("not defined in the WebRoutes constants", exception.Message); + } + + [Fact] + public void GetAbsoluteUrl_WhenHttpContextIsNull_ShouldReturnNull() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN); + + // Assert + Assert.Null(url); + } + + [Fact] + public void GetAbsoluteUrl_WhenCalled_ShouldReplaceCulturePlaceholderAndBuildAbsoluteUrl() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN); + + // Assert + Assert.Equal("http://localhost:5012/en-us/auth/api-login", url); + } + + [Fact] + public void GetAbsoluteUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + Guid id = Guid.NewGuid(); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id }); + + // Assert + Assert.Equal($"http://localhost:5012/en-us/libraries/manage/api-item/{id}", url); + } + + [Fact] + public void GetAbsoluteUrl_WhenPathBaseIsPresent_ShouldIncludePathBase() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "de-de", pathBase: "/lumina", host: "localhost:5012", scheme: "https"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW); + + // Assert + Assert.Equal("https://localhost:5012/lumina/de-de/auth/register", url); + } + + [Fact] + public void GetAbsoluteUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + string? url = _sut.GetAbsoluteUrl(WebRoutes.FileSystem.GET_TYPE); + + // Assert + Assert.Equal("http://localhost:5012/file-system/api-get-type", url); + } + + private static DefaultHttpContext CreateHttpContext(string culture, string pathBase, string host, string scheme) + { + DefaultHttpContext httpContext = new(); + httpContext.Request.RouteValues["culture"] = culture; + httpContext.Request.PathBase = pathBase; + httpContext.Request.Host = new HostString(host); + httpContext.Request.Scheme = scheme; + return httpContext; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs new file mode 100644 index 00000000..7f4999ac --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using FluentValidation.Results; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EncryptionSettingsModelValidatorTests +{ + private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + private readonly EncryptionSettingsModelValidator _validator = new(); + + [Fact] + public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError() + { + // Arrange + EncryptionSettingsDto settings = new() { SecretKey = string.Empty }; + + // Act + ValidationResult result = _validator.Validate(settings); + + // Assert + Assert.False(result.IsValid); + Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key cannot be empty!"); + } + + [Fact] + public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError() + { + // Arrange + EncryptionSettingsDto settings = new() { SecretKey = "not-base64-key!" }; + + // Act + ValidationResult result = _validator.Validate(settings); + + // Assert + Assert.False(result.IsValid); + Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key must be a base64 string!"); + } + + [Fact] + public void Validate_WhenSecretKeyIsValidBase64_ShouldNotHaveValidationError() + { + // Arrange + EncryptionSettingsDto settings = new() { SecretKey = VALID_BASE64_KEY }; + + // Act + ValidationResult result = _validator.Validate(settings); + + // Assert + Assert.True(result.IsValid); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs new file mode 100644 index 00000000..a4509ebf --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using FluentValidation.Results; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ServerConfigurationModelValidatorTests +{ + private readonly ServerConfigurationModelValidator _validator = new(); + + [Fact] + public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError() + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = string.Empty, Port = 5214 }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.False(result.IsValid); + Assert.Contains(result.Errors, error => error.PropertyName == nameof(ServerConfigurationDto.BaseAddress) && error.ErrorMessage == "Base address cannot be empty!"); + } + + [Theory] + [InlineData((ushort)0)] // minimum allowed value + [InlineData((ushort)65535)] // maximum allowed value + public void Validate_WhenPortIsAtBoundary_ShouldNotHaveValidationError(ushort port) + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = port }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.True(result.IsValid); + } + + [Theory] + [InlineData((char)0)] // minimum allowed API version + [InlineData((char)255)] // maximum allowed API version + public void Validate_WhenApiVersionIsAtBoundary_ShouldNotHaveValidationError(char apiVersion) + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = apiVersion, BaseAddress = "http://localhost", Port = 5214 }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.True(result.IsValid); + } + + [Fact] + public void Validate_WhenConfigurationIsValid_ShouldNotHaveValidationError() + { + // Arrange + ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 }; + + // Act + ValidationResult result = _validator.Validate(configuration); + + // Assert + Assert.True(result.IsValid); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs new file mode 100644 index 00000000..b3ac71bf --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.AddRole; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AddRoleEndpoint _sut; + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddRoleEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldCreateRoleViaApiAndReturnSuccess() + { + // Arrange + AddRoleRequest request = _addRoleRequestFixture.Create(); + RolePermissionsDto expectedResponse = new(new RoleDto(Guid.NewGuid(), request.RoleName!), [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)]); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Roles.CREATE_ROLE, + Arg.Is(role => role.RoleName == request.RoleName && role.Permissions!.SequenceEqual(request.Permissions!)), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs new file mode 100644 index 00000000..5a9cc33b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeleteRoleEndpoint _sut; + private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteRoleEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldDeleteRoleViaApiAndReturnSuccess() + { + // Arrange + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Roles.DELETE_ROLE.Replace("{roleId}", request.RoleId.ToString()); + await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs new file mode 100644 index 00000000..dbd0a3ce --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetRolesEndpoint _sut; + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetRolesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsRoles_ShouldReturnSuccessJsonWithRoles() + { + // Arrange + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLES, Arg.Any()) + .Returns(expectedRoles); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + RoleDto[]? returnedRoles = jsonDocument.RootElement.GetProperty("data").Deserialize(CreateCaseInsensitiveOptions()); + Assert.Equal(expectedRoles.Select(role => role.RoleName), returnedRoles!.Select(role => role.RoleName)); + } + + private static JsonSerializerOptions CreateCaseInsensitiveOptions() + { + return new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestRolesFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Roles.GET_ROLES, Arg.Any()) + .Returns([.. _roleDtoFixture.CreateMany(2)]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Roles.GET_ROLES, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs new file mode 100644 index 00000000..70cae537 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -0,0 +1,111 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.Fixtures.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BaseEndpointTests +{ + private readonly BaseEndpointFixture _sut; + + /// + /// Initializes a new instance of the class. + /// + public BaseEndpointTests() + { + _sut = Factory.Create(); + } + + [Fact] + public async Task TestJsonSuccess_WhenCalledWithData_ShouldReturnSuccessJsonEnvelopeWithData() + { + // Act + IResult result = _sut.TestJsonSuccess(new { itemId = "test-id" }); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("test-id", jsonDocument.RootElement.GetProperty("data").GetProperty("itemId").GetString()); + } + + [Fact] + public async Task TestJsonSuccess_WhenCalledWithoutData_ShouldReturnSuccessJsonEnvelope() + { + // Act + IResult result = _sut.TestJsonSuccess(); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public void TestView_WhenCalled_ShouldReturnRazorViewResult() + { + // Arrange + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/home"; + + // Act + IResult result = _sut.TestView("/Core/Views/Home/Index.cshtml"); + + // Assert + Assert.IsType(result); + } + + [Fact] + public void TestView_WhenCalled_ShouldStoreLastDisplayedViewInSession() + { + // Arrange + Microsoft.AspNetCore.Http.ISession session = TestHttpContextFactory.CreateSession(); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, session); + _sut.HttpContext.Request.Path = "/en-us/libraries/manage"; + + // Act + _sut.TestView("/Core/Views/Library/Management/Index.cshtml"); + + // Assert + session.Received(1).Set(HttpContextItemKeys.LAST_DISPLAYED_VIEW, Arg.Any()); + } + + [Fact] + public void TestCulture_WhenCultureRouteValuePresent_ShouldReturnCulture() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "de-DE"); + + // Act + string culture = _sut.TestCulture; + + // Assert + Assert.Equal("de-DE", culture); + } + + [Fact] + public void TestCulture_WhenCultureRouteValueMissing_ShouldReturnDefaultCulture() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, null); + + // Act + string culture = _sut.TestCulture; + + // Assert + Assert.Equal("en-US", culture); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..94b232f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetDirectoriesEndpoint _sut; + private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsDirectories_ShouldReturnSuccessJsonWithDirectories() + { + // Arrange + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: true); + DirectoryDto[] expectedDirectories = [new DirectoryDto { Path = "/media/books", Name = "books" }]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedDirectories); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=True"; + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(1, jsonDocument.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithoutHiddenElements_ShouldRequestWithoutHiddenElementsFlag() + { + // Arrange + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: false); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=False"; + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..a9da73d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ValidatePathEndpoint _sut; + private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ValidatePathEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiValidatesPath_ShouldReturnSuccessJsonWithIsValid() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(path: "/media/books"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PathValidDto(true)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Path.VALIDATE}?path={Uri.EscapeDataString(request.Path!)}"; + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenPathIsInvalid_ShouldReturnSuccessJsonWithIsValidFalse() + { + // Arrange + ValidatePathRequest request = _validatePathRequestFixture.Create(path: "C:/invalid|path"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PathValidDto(false)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.False(jsonDocument.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..76bcefb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeleteLibraryEndpoint _sut; + private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteLibraryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldDeleteLibraryViaApiAndReturnSuccess() + { + // Arrange + DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Libraries.DELETE_LIBRARY.Replace("{id}", request.Id.ToString()); + await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..14d32401 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibrariesEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibrariesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsLibraries_ShouldReturnSuccessJsonWithLibraries() + { + // Arrange + LibraryDto[] expectedLibraries = [.. _libraryDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any()) + .Returns(expectedLibraries); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize(new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + Assert.Equal(expectedLibraries.Select(library => library.Title), returnedLibraries!.Select(library => library.Title)); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestLibrariesFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any()) + .Returns([.. _libraryDtoFixture.CreateMany(2)]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs new file mode 100644 index 00000000..e3f7b830 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SaveLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SaveLibraryEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly SaveLibraryEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SaveLibraryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestHasId_ShouldUpdateLibraryViaApi() + { + // Arrange + LibraryDto request = _libraryDtoFixture.Create(); + LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Libraries.UPDATE_LIBRARY.Replace("{id}", request.Id!.Value.ToString()); + await _mockApiHttpClient.Received(1).PutAsync(expectedEndpoint, Arg.Is(library => library.Title == request.Title), Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestHasNoId_ShouldCreateLibraryViaApi() + { + // Arrange + LibraryDto request = _libraryDtoFixture.Create(); + request.Id = null; + LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync(ApiRoutes.Libraries.ADD_LIBRARY, Arg.Is(library => library.Title == request.Title), Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PutAsync(Arg.Any(), Arg.Any(), Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs new file mode 100644 index 00000000..13a5562f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Common; +using Lumina.Presentation.Web.Common.Requests.Libraries; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryItemsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryItemsEndpoint _sut; + private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryItemsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestLibraryItemsWithQueryParameters() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create( + currentPage: 2, + perPage: 48, + searchTerm: "the hobbit", + filterAlphaKey: "H", + ignoreThePrefixForAlphaPicker: true, + sortBy: "title", + sortOrder: SortOrder.Ascending); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PaginatedBookLiteDto()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => + endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) && + endpoint.Contains($"libraryId={request.LibraryId}") && + endpoint.Contains("currentPage=2") && + endpoint.Contains("perPage=48") && + endpoint.Contains("searchTerm=the%20hobbit") && + endpoint.Contains("filterAlphaKey=H") && + endpoint.Contains("ignoreThePrefixForAlphaPicker=True") && + endpoint.Contains("sortBy=title") && + endpoint.Contains("sortOrder=Ascending")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithOnlyLibraryId_ShouldRequestWithoutOptionalParameters() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new PaginatedBookLiteDto()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => + endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) && + endpoint.EndsWith($"libraryId={request.LibraryId}&ignoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) && + !endpoint.Contains("currentPage=") && + !endpoint.Contains("searchTerm=") && + !endpoint.Contains("sortBy=")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsPaginatedItems_ShouldReturnSuccessJsonWithItems() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + PaginatedBookLiteDto expectedResponse = new() + { + CurrentPage = 1, + PerPage = 48, + Count = 1, + NumberOfPages = 1, + Data = [new BookLiteDto { Id = Guid.NewGuid(), Title = "Test Book" }] + }; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetProperty("currentPage").GetInt32()); + Assert.Equal(1, data.GetProperty("data").GetArrayLength()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs new file mode 100644 index 00000000..bc80d5b6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksIndexViewEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IUrlService _mockUrlService; + private readonly BooksIndexViewEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BooksIndexViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _mockUrlService = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient, _mockUrlService); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books"; + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome() + { + // Arrange + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(null), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us", redirectResult.Url); + await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldReturnRazorViewResultWithLibraryModel() + { + // Arrange + LibraryDto expectedLibrary = _libraryDtoFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedLibrary); + + // Act + IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None); + + // Assert + Assert.IsType(result); + string expectedEndpoint = ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id!.Value.ToString()); + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs new file mode 100644 index 00000000..bb08ee79 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.GetPlugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetPluginsEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public GetPluginsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsPlugins_ShouldReturnSuccessJsonWithPlugins() + { + // Arrange + PluginDto[] expectedPlugins = [new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary", Author = "Test Author", Version = "1.0.0" }]; + _mockApiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any()) + .Returns(expectedPlugins); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PluginDto[]? returnedPlugins = jsonDocument.RootElement.GetProperty("data").Deserialize(new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + Assert.Equal(expectedPlugins.Select(plugin => plugin.Name), returnedPlugins!.Select(plugin => plugin.Name)); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestPluginsFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any()) + .Returns([new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary" }]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs new file mode 100644 index 00000000..a2534b6a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.UpdatePluginSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdatePluginSettingsEndpoint _sut; + private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePluginSettingsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldUpdatePluginSettingsViaApiAndReturnSuccess() + { + // Arrange + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()); + await _mockApiHttpClient.Received(1).PutAsync( + expectedEndpoint, + Arg.Is(settings => settings.PluginId == request.PluginId), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs new file mode 100644 index 00000000..6b839637 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Tools; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Localization; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Language.SetLanguage; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageEndpointTests +{ + private readonly SetLanguageEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public SetLanguageEndpointTests() + { + _sut = Factory.Create(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithoutReturnUrl_ShouldSetCultureCookieAndRedirectWithNewCulture() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", null), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("/de-de", redirectResult.Url); + Assert.True(redirectResult.AcceptLocalUrlOnly); + string setCookieHeader = _sut.HttpContext.Response.Headers.SetCookie.ToString(); + Assert.Contains(CookieRequestCultureProvider.DefaultCookieName, setCookieHeader); + Assert.Contains("de-DE", setCookieHeader); + } + + [Fact] + public async Task ExecuteAsync_WhenReturnUrlProvided_ShouldReplaceCultureInReturnUrl() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", "/en-us/tools/settings"), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("/de-de/tools/settings", redirectResult.Url); + } + + [Fact] + public async Task ExecuteAsync_WhenPathBasePresent_ShouldKeepPathBaseInRedirectUrl() + { + // Arrange + TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); + _sut.HttpContext.Request.PathBase = "/lumina"; + + // Act + IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("fr-FR", "/en-us/tools/settings"), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("/lumina/fr-fr/tools/settings", redirectResult.Url); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..b55cfc50 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetUserSettingsEndpoint _sut; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetUserSettingsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsSettings_ShouldReturnSuccessJsonWithSettings() + { + // Arrange + UserSettingsDto expectedSettings = _userSettingsDtoFixture.Create(); + _mockApiHttpClient.GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any()) + .Returns(expectedSettings); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(expectedSettings.ItemsPerPage, data.GetProperty("itemsPerPage").GetInt32()); + Assert.Equal(expectedSettings.IsPaginationEnabled, data.GetProperty("isPaginationEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestUserSettingsFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any()) + .Returns(_userSettingsDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..3691a19a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdateUserSettingsEndpoint _sut; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateUserSettingsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldUpdateSettingsViaApiAndReturnSuccess() + { + // Arrange + UserSettingsDto request = _userSettingsDtoFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Users.UPDATE_USER_SETTINGS, + Arg.Is(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs new file mode 100644 index 00000000..aa221b50 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginViewEndpointTests +{ + private readonly IUrlService _mockUrlService; + private readonly LoginViewEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public LoginViewEndpointTests() + { + _mockUrlService = Substitute.For(); + _sut = Factory.Create(_mockUrlService); + } + + [Fact] + public async Task ExecuteAsync_WhenUserAlreadyAuthenticated_ShouldRedirectToHome() + { + // Arrange + TestHttpContextFactory.ConfigureUser(_sut.HttpContext, TestHttpContextFactory.CreateAuthenticatedUser()); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us", redirectResult.Url); + _mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED); + } + + [Fact] + public async Task ExecuteAsync_WhenSuperAdminSetupPending_ShouldRedirectToRegisterView() + { + // Arrange + Microsoft.AspNetCore.Http.ISession session = Substitute.For(); + byte[] pendingBytes = Encoding.UTF8.GetBytes("true"); +#pragma warning disable CS8601 // possible null reference assignment in the NSubstitute out-argument stub + session.TryGetValue(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, out Arg.Any()).Returns(callInfo => + { + callInfo[1] = pendingBytes; + return true; + }); +#pragma warning restore CS8601 + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, session); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW).Returns("http://localhost/en-us/auth/register"); + + // Act + IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us/auth/register", redirectResult.Url); + _mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW); + } + + [Fact] + public async Task ExecuteAsync_WhenNotAuthenticatedAndInitialized_ShouldReturnRazorViewResult() + { + // Arrange + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + + // Act + IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + + // Assert + Assert.IsType(result); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..fad145e5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RecoverPasswordEndpoint _sut; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRecoverPasswordViaApiAndReturnSuccess() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + RecoverPasswordResponse expectedResponse = new(true); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Authentication.RECOVER_PASSWORD, + Arg.Is(recovery => recovery.Username == request.Username), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isPasswordReset").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..7db86624 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RegisterEndpoint _sut; + private readonly RegisterRequestFixture _registerRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RegisterEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenRegistrationTypeIsAdmin_ShouldSetupApplicationViaApi() + { + // Arrange + RegisterRequest request = _registerRequestFixture.Create(registrationType: "Admin"); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new RegisterResponse(request.Username, null)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Initialization.SETUP_APPLICATION, + Arg.Is(registration => registration.Username == request.Username), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenRegistrationTypeIsUser_ShouldRegisterAccountViaApi() + { + // Arrange + RegisterRequest request = _registerRequestFixture.Create(registrationType: "User"); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new RegisterResponse(request.Username, null)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Authentication.REGISTER_ACCOUNT, + Arg.Is(registration => registration.Username == request.Username), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj new file mode 100644 index 00000000..cac91d11 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Lumina.Presentation.Web.UnitTests.csproj @@ -0,0 +1,46 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + +