diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs index 66d67d7f..f7af1c16 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs @@ -19,9 +19,9 @@ public class UserAuthorizationEntity public required Guid UserId { get; init; } /// - /// Gets the collection of roles associated to the user. + /// Gets the role associated to the user. /// - public required IReadOnlySet Roles { get; init; } + public required string? Role { get; init; } /// /// Gets the collection of permissions associated to the user. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs index 68885e30..651d32bf 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs @@ -51,9 +51,9 @@ public class UserEntity : IStorageEntity, IAuditableEntity public required ICollection Libraries { get; init; } = []; /// - /// Gets the collection of user roles associations that include this user. + /// Gets the user roles association that includes this user. /// - public required ICollection UserRoles { get; init; } = []; + public required UserRoleEntity? UserRole { get; init; } /// /// Gets the collection of user permission associations that include this user. diff --git a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs index 7fada6c8..6c210728 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs @@ -25,5 +25,7 @@ public static partial class Errors public static Error PermissionIdCannotBeEmpty => Error.Validation(description: nameof(PermissionIdCannotBeEmpty)); public static Error RoleNameCannotBeEmpty => Error.Validation(description: nameof(RoleNameCannotBeEmpty)); public static Error RoleNameCannotBeNull => Error.Validation(description: nameof(RoleNameCannotBeNull)); + public static Error CannotRemoveLastAdmin => Error.Forbidden(description: nameof(CannotRemoveLastAdmin)); + public static Error UserMustHaveRoleOrDirectPermissions => Error.Forbidden(description: nameof(UserMustHaveRoleOrDirectPermissions)); } } diff --git a/src/Lumina.Application/Common/Mapping/Authorization/GetUserPermissionsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/GetUserPermissionsRequestMapping.cs new file mode 100644 index 00000000..2f2bcb47 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/GetUserPermissionsRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; +using Lumina.Contracts.Requests.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class GetUserPermissionsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetUserPermissionsQuery ToQuery(this GetUserPermissionsRequest request) + { + return new GetUserPermissionsQuery( + request.UserId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/GetUserRoleRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/GetUserRoleRequestMapping.cs new file mode 100644 index 00000000..a01e015a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/GetUserRoleRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; +using Lumina.Contracts.Requests.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class GetUserRoleRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetUserRoleQuery ToQuery(this GetUserRoleRequest request) + { + return new GetUserRoleQuery( + request.UserId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/UpdateUserRoleAndPermissionsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/UpdateUserRoleAndPermissionsRequestMapping.cs new file mode 100644 index 00000000..70434832 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/UpdateUserRoleAndPermissionsRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; +using Lumina.Contracts.Requests.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class UpdateUserRoleAndPermissionsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdateUserRoleAndPermissionsCommand ToCommand(this UpdateUserRoleAndPermissionsRequest request) + { + return new UpdateUserRoleAndPermissionsCommand( + request.UserId!.Value, + request.RoleId, + request.Permissions! + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs index c4d0eb8f..8070ff00 100644 --- a/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs @@ -19,7 +19,7 @@ public static class UserAuthorizationEntityMapping { return new AuthorizationResponse( repositoryEntity.UserId, - repositoryEntity.Roles, + repositoryEntity.Role, repositoryEntity.Permissions ); } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs index 7d28f7c5..a8245a5d 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs @@ -14,7 +14,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; /// /// The Id of the role. /// The name of the role. -/// The collection or permissions of the role. +/// The collection of Ids of the permissions of the role. [DebuggerDisplay("RoleName: {RoleName}")] public record UpdateRoleCommand( Guid RoleId, diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs index 8c21ea93..7305064c 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs @@ -51,6 +51,7 @@ public class GetRolePermissionsQueryHandler : IRequestHandler getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); if (getRoleResult.IsError) return getRoleResult.Errors; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index 17f2872b..c6d80a8a 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -87,8 +87,8 @@ public class SetupApplicationCommandHandler : IRequestHandler public AddLibraryCommandValidator() { RuleFor(x => x.UserId) - .NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description); + .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); RuleFor(x => x.LibraryType) .NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs index 5c2811e7..e72dd2aa 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs @@ -22,12 +22,12 @@ public class UpdateLibraryCommandValidator : AbstractValidator id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); RuleFor(x => x.CurrentUserId) - .NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description); + .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); RuleFor(x => x.OwnerId) - .NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description); + .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); RuleFor(x => x.LibraryType) .NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryValidator.cs index c45913d0..972d942a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryValidator.cs @@ -21,7 +21,7 @@ public class GetLibraryQueryValidator : AbstractValidator .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); RuleFor(x => x.UserId) - .NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description) - .Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description); + .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index ce13b85c..d265f111 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -80,7 +80,7 @@ public class RegisterUserCommandHandler : IRequestHandler +/// Command for updating the authorization role and permissions of a user. +/// +/// The Id of the user. +/// The Id of the role. +/// The collection of Ids of the permissions of the user. +[DebuggerDisplay("UserId: {UserId}")] +public record UpdateUserRoleAndPermissionsCommand( + Guid UserId, + Guid? RoleId, + List Permissions +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs new file mode 100644 index 00000000..fdd726ef --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandler.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; + +/// +/// Handler for the command to update an authorization role. +/// +public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public UpdateUserRoleAndPermissionsCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + } + + /// + /// Handles the command to update an authorization role. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully updated , or an error message. + /// + public async ValueTask> Handle(UpdateUserRoleAndPermissionsCommand request, CancellationToken cancellationToken) + { + // only admins can update user authorizations + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return ApplicationErrors.Authorization.NotAuthorized; + + // get repositories + IUserRepository userRepository = _unitOfWork.GetRepository(); + IRoleRepository roleRepository = _unitOfWork.GetRepository(); + IPermissionRepository permissionRepository = _unitOfWork.GetRepository(); + + // get the user to update + ErrorOr getUserResult = await userRepository.GetByIdAsync(request.UserId, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsError || getUserResult.Value is null) + return DomainErrors.Users.UserDoesNotExist; + + ErrorOr getRoleResult = default; + if (request.RoleId is not null) + { + // get the new role + getRoleResult = await roleRepository.GetByIdAsync(request.RoleId!.Value, cancellationToken).ConfigureAwait(false); + if (getRoleResult.IsError || getRoleResult.Value is null) + return ApplicationErrors.Authorization.RoleNotFound; + + // check if we're changing an admin's role and if this would leave us without admins + if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin") + { + // count how many admins we have + ErrorOr> getAllUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getAllUsersResult.IsError) + return getAllUsersResult.Errors; + + int adminCount = getAllUsersResult.Value.Count(user => user.UserRole?.Role.RoleName == "Admin"); + if (adminCount <= 1) + return ApplicationErrors.Authorization.CannotRemoveLastAdmin; + } + } + // get the permissions to assign + ErrorOr> getPermissionsResult = + await permissionRepository.GetByIdsAsync(request.Permissions, cancellationToken).ConfigureAwait(false); + if (getPermissionsResult.IsError) + return getPermissionsResult.Errors; + + // update the user + UserEntity userToUpdate = getUserResult.Value; + + UserRoleEntity? userRole = default!; + if (request.RoleId is not null) + { + userRole = new() + { + UserId = userToUpdate.Id, + RoleId = request.RoleId.Value, + Role = getRoleResult.Value!, + User = userToUpdate + }; + } + + UserEntity updatedUser = new() + { + Id = userToUpdate.Id, + Username = userToUpdate.Username, + Password = userToUpdate.Password, + TempPassword = userToUpdate.TempPassword, + TotpSecret = userToUpdate.TotpSecret, + TempPasswordCreated = userToUpdate.TempPasswordCreated, + Libraries = userToUpdate.Libraries, + UserRole = userRole, + UserPermissions = request.Permissions.Select(permissionId => new UserPermissionEntity + { + UserId = userToUpdate.Id, + PermissionId = permissionId, + Permission = getPermissionsResult.Value.First(permission => permission.Id == permissionId), + User = userToUpdate + }).ToList() + }; + + // save changes and return result + ErrorOr updateResult = await userRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false); + if (updateResult.IsError) + return updateResult.Errors; + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return new AuthorizationResponse( + userToUpdate.Id, + getRoleResult.Value?.RoleName, + userToUpdate.UserPermissions + .Select(up => up.Permission.PermissionName) + .ToHashSet() + ); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs new file mode 100644 index 00000000..d3c2625d --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidator.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using System; +using System.Linq; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateUserRoleAndPermissionsCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateUserRoleAndPermissionsCommandValidator() + { + RuleFor(x => x.UserId) + .NotEmpty().WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description); + + // validate Permissions only if provided + When(x => x.Permissions != null && x.Permissions.Count != 0, () => + { + RuleForEach(x => x.Permissions) + .NotEmpty().WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description); + }); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs index 1e0b9be6..5e4f81ba 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs @@ -51,7 +51,7 @@ public class GetAuthorizationQueryHandler : IRequestHandler role == "Admin")) + if (getCurrentUserPermissionResult.Value.Role != "Admin") return Errors.Authorization.NotAuthorized; } ErrorOr getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs new file mode 100644 index 00000000..f645e3c6 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQuery.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; + +/// +/// Query for retrieving the authorization permissions of a user identified by . +/// +/// The Id of the user for whom to get the authorization permissions. +[DebuggerDisplay("UserId: {UserId}")] +public record GetUserPermissionsQuery( + Guid? UserId +) : IRequest>>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs new file mode 100644 index 00000000..3fcdb9fb --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; + +/// +/// Handler for the query to retrieve the authorization permissions of a user. +/// +public class GetUserPermissionsQueryHandler : IRequestHandler>> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IUserRepository _userRepository; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetUserPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _userRepository = unitOfWork.GetRepository(); + } + + /// + /// Handles the query to retrieve the authorization permissions of a user. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error message. + /// + public async ValueTask>> Handle(GetUserPermissionsQuery request, CancellationToken cancellationToken) + { + // only admins can see the list of authorization permissions + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return Errors.Authorization.NotAuthorized; + // get the user from the repository and return its permissions + ErrorOr getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsError) + return getUserResult.Errors; + else if (getUserResult.Value is null) + return Errors.Authentication.UsernameDoesNotExist; + return ErrorOrFactory.From(getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission).ToResponses()); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs new file mode 100644 index 00000000..987e3052 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; + +/// +/// Validates the needed validation rules for . +/// +public class GetUserPermissionsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserPermissionsQueryValidator() + { + RuleFor(x => x.UserId) + .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs new file mode 100644 index 00000000..ded01e30 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQuery.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; + +/// +/// Query for retrieving the authorization role of a user identified by . +/// +/// The Id of the user for whom to get the authorization role. +[DebuggerDisplay("UserId: {UserId}")] +public record GetUserRoleQuery( + Guid? UserId +) : IRequest>; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs new file mode 100644 index 00000000..460e0210 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; + +/// +/// Handler for the query to retrieve the authorization role of a user. +/// +public class GetUserRoleQueryHandler : IRequestHandler> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IUserRepository _userRepository; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetUserRoleQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _userRepository = unitOfWork.GetRepository(); + } + + /// + /// Handles the query to retrieve the authorization role of a user. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a , or an error message. + /// + public async ValueTask> Handle(GetUserRoleQuery request, CancellationToken cancellationToken) + { + // only admins can see the authorization role + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return Errors.Authorization.NotAuthorized; + // get the user from the repository and return its roles + ErrorOr getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsError) + return getUserResult.Errors; + else if (getUserResult.Value is null) + return Errors.Authentication.UsernameDoesNotExist; + return ErrorOrFactory.From(getUserResult.Value.UserRole?.Role.ToResponse()); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs new file mode 100644 index 00000000..954bb659 --- /dev/null +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; + +/// +/// Validates the needed validation rules for . +/// +public class GetUserRoleQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserRoleQueryValidator() + { + RuleFor(x => x.UserId) + .NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs new file mode 100644 index 00000000..4820525c --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authorization/GetUserPermissionsRequest.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Requests.Authorization; + +/// +/// Represents the request model for retrieving the authorization permissions of a user identified by . +/// +/// The Id of the user for whom to get the authorization permissions. Required. +public record GetUserPermissionsRequest( + Guid? UserId +); diff --git a/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs new file mode 100644 index 00000000..c6000303 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authorization/GetUserRoleRequest.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Requests.Authorization; + +/// +/// Represents the request model for retrieving the authorization role of a user identified by . +/// +/// The Id of the user for whom to get the authorization role. Required. +public record GetUserRoleRequest( + Guid? UserId +); diff --git a/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs index bcd45fba..febad4d3 100644 --- a/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs +++ b/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs @@ -11,7 +11,7 @@ namespace Lumina.Contracts.Requests.Authorization; /// /// The Id of the role. Required. /// The name of the role. Required. -/// The collection or permissions of the role. Required. +/// The collection of Ids of the permissions of the role. Required. [DebuggerDisplay("RoleName: {RoleName}")] public record UpdateRoleRequest( Guid? RoleId, diff --git a/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs b/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs new file mode 100644 index 00000000..68742ee4 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authorization/UpdateUserRoleAndPermissionsRequest.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authorization; + +/// +/// Represents a request for updating the authorization role and permissions of a user. +/// +/// The Id of the user. Required. +/// The Id of the role. Required. +/// The collection of Ids of the permissions of the role. Required. +[DebuggerDisplay("UserId: {UserId}")] +public record UpdateUserRoleAndPermissionsRequest( + Guid? UserId, + Guid? RoleId, + List? Permissions +); diff --git a/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs b/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs index 68c4ce96..4f474ab4 100644 --- a/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs +++ b/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs @@ -11,11 +11,11 @@ namespace Lumina.Contracts.Responses.Authorization; /// Represents the response model for an account authorization request. /// /// The Id of the user for whom the authorization is retrieved. -/// The collection of roles associated to the user. +/// The collection of roles associated to the user. /// The collection of permissions associated to the user. [DebuggerDisplay("UserId: {UserId}")] public record AuthorizationResponse( Guid UserId, - IReadOnlySet Roles, + string? Role, IReadOnlySet Permissions ); diff --git a/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs index 038dd94a..a8e2eeca 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserConfiguration.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; @@ -51,10 +52,11 @@ public class UserConfiguration : IEntityTypeConfiguration .IsRequired() // a library must have a user .OnDelete(DeleteBehavior.Cascade); - builder.HasMany(user => user.UserRoles) - .WithOne(userRole => userRole.User) - .HasForeignKey(userRole => userRole.UserId) - .OnDelete(DeleteBehavior.Cascade); + builder.HasOne(user => user.UserRole) + .WithOne(userRole => userRole.User) + .HasForeignKey(userRole => userRole.UserId) + .IsRequired() + .OnDelete(DeleteBehavior.Cascade); builder.HasMany(user => user.UserPermissions) .WithOne(userPermission => userPermission.User) diff --git a/src/Lumina.DataAccess/Common/Configuration/UserRoleConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserRoleConfiguration.cs index 51ca6466..bf639d51 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserRoleConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserRoleConfiguration.cs @@ -19,19 +19,19 @@ public class UserRoleConfiguration : IEntityTypeConfiguration { builder.ToTable("UserRoles"); - // composite primary key - builder.HasKey(userRole => new { userRole.UserId, userRole.RoleId }); + // primary key + builder.HasKey(userRole => userRole.UserId ); builder.Ignore(userRole => userRole.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id - // foreign key: User + // foreign key: User (one-to-one relationship) builder.HasOne(userRole => userRole.User) - .WithMany(user => user.UserRoles) - .HasForeignKey(userRole => userRole.UserId) + .WithOne(user => user.UserRole) + .HasForeignKey(userRole => userRole.UserId) .IsRequired() - .OnDelete(DeleteBehavior.Cascade); // deleting a User deletes associated UserRoles + .OnDelete(DeleteBehavior.Cascade); // deleting a User deletes associated UserRole - // foreign key: Role + // foreign key: Role (many-to-one relationship) builder.HasOne(userRole => userRole.Role) .WithMany(role => role.UserRoles) .HasForeignKey(userRole => userRole.RoleId) diff --git a/src/Lumina.DataAccess/Common/Migrations/20241219160437_ChangesUserRolesToUserRole.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20241219160437_ChangesUserRolesToUserRole.Designer.cs new file mode 100644 index 00000000..62ecc589 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241219160437_ChangesUserRolesToUserRole.Designer.cs @@ -0,0 +1,698 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20241219160437_ChangesUserRolesToUserRole")] + partial class ChangesUserRolesToUserRole + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Created") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Updated") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole") + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241219160437_ChangesUserRolesToUserRole.cs b/src/Lumina.DataAccess/Common/Migrations/20241219160437_ChangesUserRolesToUserRole.cs new file mode 100644 index 00000000..86c0094f --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241219160437_ChangesUserRolesToUserRole.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class ChangesUserRolesToUserRole : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles", + columns: new[] { "UserId", "RoleId" }); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index d27adb31..06bfe597 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -188,9 +188,6 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("UserId") .HasColumnType("TEXT"); - b.Property("RoleId") - .HasColumnType("TEXT"); - b.Property("CreatedBy") .HasColumnType("TEXT") .HasColumnOrder(2); @@ -199,6 +196,9 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(1); + b.Property("RoleId") + .HasColumnType("TEXT"); + b.Property("UpdatedBy") .HasColumnType("TEXT") .HasColumnOrder(4); @@ -207,7 +207,7 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(3); - b.HasKey("UserId", "RoleId"); + b.HasKey("UserId"); b.HasIndex("RoleId"); @@ -548,8 +548,8 @@ namespace Lumina.DataAccess.Common.Migrations .IsRequired(); b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") - .WithMany("UserRoles") - .HasForeignKey("UserId") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); @@ -686,7 +686,8 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("UserPermissions"); - b.Navigation("UserRoles"); + b.Navigation("UserRole") + .IsRequired(); }); #pragma warning restore 612, 618 } diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs index f0428655..c59cd0c0 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.DataAccess.Core.UoW; @@ -7,6 +8,7 @@ using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -65,13 +67,11 @@ internal sealed class UserRepository : IUserRepository { return await _luminaDbContext.Users .Include(user => user.Libraries) - .ThenInclude(library => library.ContentLocations) + .ThenInclude(library => library.ContentLocations) .Include(user => user.UserPermissions) - .ThenInclude(userPermission => userPermission.Permission) - .Include(user => user.UserRoles) - .ThenInclude(userRole => userRole.Role) - .ThenInclude(role => role.RolePermissions) - .ThenInclude(rolePermission => rolePermission.Permission) + .ThenInclude(userPermission => userPermission.Permission) + .Include(user => user.UserRole!.Role.RolePermissions) + .ThenInclude(rolePermission => rolePermission.Permission) .FirstOrDefaultAsync(user => user.Username == username, cancellationToken) .ConfigureAwait(false); } @@ -86,21 +86,52 @@ internal sealed class UserRepository : IUserRepository { UserEntity? foundUser = await _luminaDbContext.Users .Include(user => user.Libraries) - .ThenInclude(library => library.ContentLocations) + .ThenInclude(library => library.ContentLocations) .Include(user => user.UserPermissions) - .ThenInclude(userPermission => userPermission.Permission) - .Include(user => user.UserRoles) - .ThenInclude(userRole => userRole.Role) - .ThenInclude(role => role.RolePermissions) - .ThenInclude(rolePermission => rolePermission.Permission) + .ThenInclude(userPermission => userPermission.Permission) + .Include(user => user.UserRole!.Role.RolePermissions) + .ThenInclude(rolePermission => rolePermission.Permission) .FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken) .ConfigureAwait(false); if (foundUser is null) return Errors.Users.UserDoesNotExist; + + // update scalar properties _luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data); + + // update user permissions + List existingPermissions = [.. foundUser.UserPermissions]; + foreach (UserPermissionEntity permission in existingPermissions) + _luminaDbContext.UserPermissions.Remove(permission); + + foreach (UserPermissionEntity permission in data.UserPermissions) + { + _luminaDbContext.UserPermissions.Add(new UserPermissionEntity + { + UserId = foundUser.Id, + PermissionId = permission.PermissionId, + Permission = permission.Permission, + User = foundUser + }); + } + + // update user role + if (foundUser.UserRole != null) + _luminaDbContext.UserRoles.Remove(foundUser.UserRole); + if (data.UserRole is not null) + { + _luminaDbContext.UserRoles.Add(new UserRoleEntity + { + UserId = foundUser.Id, + RoleId = data.UserRole.RoleId, + Role = data.UserRole.Role, + User = foundUser + }); + } return Result.Updated; } + /// /// Gets a identified by from the storage medium. /// @@ -111,13 +142,11 @@ internal sealed class UserRepository : IUserRepository { return await _luminaDbContext.Users .Include(user => user.Libraries) - .ThenInclude(library => library.ContentLocations) + .ThenInclude(library => library.ContentLocations) .Include(user => user.UserPermissions) - .ThenInclude(userPermission => userPermission.Permission) - .Include(user => user.UserRoles) - .ThenInclude(userRole => userRole.Role) - .ThenInclude(role => role.RolePermissions) - .ThenInclude(rolePermission => rolePermission.Permission) + .ThenInclude(userPermission => userPermission.Permission) + .Include(user => user.UserRole!.Role.RolePermissions) + .ThenInclude(rolePermission => rolePermission.Permission) .FirstOrDefaultAsync(user => user.Id == id, cancellationToken) .ConfigureAwait(false); } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index aa97b3d1..a941299f 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -12,7 +12,6 @@ public static partial class Errors public static class Library { public static Error LibraryIdCannotBeEmpty => Error.Forbidden(description: nameof(LibraryIdCannotBeEmpty)); - public static Error UserIdCannotBeEmpty => Error.Forbidden(description: nameof(UserIdCannotBeEmpty)); public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists)); public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound)); public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index 36594360..bdad2fa5 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -55,9 +55,8 @@ public class AuthorizationService : IAuthorizationService return true; // check if any of the user's roles grant the permission - return getUserResult.Value.UserRoles - .SelectMany(userRole => userRole.Role.RolePermissions) - .Any(rolePermission => rolePermission.Permission.PermissionName == permission); + return getUserResult.Value.UserRole?.Role.RolePermissions + .Any(rolePermission => rolePermission.Permission.PermissionName == permission) == true; } /// @@ -72,7 +71,7 @@ public class AuthorizationService : IAuthorizationService ErrorOr getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError || getUserResult.Value is null) return false; - return getUserResult.Value.UserRoles.Any(userRole => userRole.Role.RoleName == role); + return getUserResult.Value.UserRole?.Role.RoleName == role; } /// @@ -106,9 +105,7 @@ public class AuthorizationService : IAuthorizationService return Errors.Users.UserDoesNotExist; // get all roles - HashSet roles = getUserResult.Value.UserRoles - .Select(userRole => userRole.Role.RoleName) - .ToHashSet(); + string? role = getUserResult.Value.UserRole?.Role.RoleName; // get direct user permissions HashSet directPermissions = getUserResult.Value.UserPermissions @@ -116,20 +113,17 @@ public class AuthorizationService : IAuthorizationService .ToHashSet(); // get permissions from roles - HashSet rolePermissions = getUserResult.Value.UserRoles - .SelectMany(userRole => userRole.Role.RolePermissions) + HashSet? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions .Select(rolePermission => rolePermission.Permission.PermissionName) .ToHashSet(); // combine all permissions - HashSet allPermissions = directPermissions - .Union(rolePermissions) - .ToHashSet(); + HashSet allPermissions = rolePermissions is not null ? directPermissions.Union(rolePermissions).ToHashSet() : directPermissions; return new UserAuthorizationEntity { UserId = userId, - Roles = roles, + Role = role, Permissions = allPermissions }; } diff --git a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authorization.cs b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authorization.cs index 28252caf..903356d5 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authorization.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/UsersManagement/ApiRoutes.Authorization.cs @@ -10,6 +10,9 @@ public static partial class ApiRoutes /// 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.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs index 9158b6c4..8e6a046f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs @@ -36,7 +36,7 @@ public class UpdateRoleEndpointSummary : Summary r.RoleId, "The Id of the role. Required."); RequestParam(r => r.RoleName, "The name of the role. Required."); - RequestParam(r => r.Permissions, "The collection or permissions of the role. Required."); + RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Required."); ResponseParam(r => r.Role, "The authorization role entity."); ResponseParam(r => r.Permissions, "The list of permissions of the role entity."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs index f5daca88..e8ee6ec9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs @@ -22,7 +22,7 @@ public class GetAuthorizationEndpointSummary : Summary r.UserId, "The Id of the user for whom to get the authorization. Required."); - Response(200, "The authorization roles and permissions of the account are returned.", + Response(200, "The authorization role and permissions of the account are returned.", example: new AuthorizationResponse( UserId: Guid.NewGuid(), - Roles: new HashSet() { "Admin" }, + Role: "Admin", Permissions: new HashSet() { AuthorizationPermission.CanRegisterUsers, AuthorizationPermission.CanDeleteUsers } )); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs new file mode 100644 index 00000000..dd9b8f94 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Contracts.Requests.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserPermissions; + +/// +/// API endpoint for the /auth/users/{userId}/permissions route. +/// +public class GetUserPermissionsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetUserPermissionsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Authorization.GET_USER_PERMISSIONS_BY_USER_ID); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the authorization permissions of a user. + /// + /// The request containing the user for whom to get the authorization permissions. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetUserPermissionsRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs new file mode 100644 index 00000000..9d04572f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Enums.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserPermissions; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserPermissionsEndpointSummary() + { + Summary = "Gets the authorization permissions of a user."; + Description = "Gets the authorization ropermissionsle of a user."; + + ExampleRequest = new GetUserPermissionsRequest( + UserId: Guid.NewGuid() + ); + + RequestParam(r => r.UserId, "The Id of the user for whom to get the authorization permissions. Required."); + + Response(200, "The authorization permissions of the user are returned.", + example: new[] { + new PermissionResponse(Id: Guid.NewGuid(), AuthorizationPermission.CanViewUsers), + new PermissionResponse(Id: Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers), + new PermissionResponse(Id: Guid.NewGuid(), AuthorizationPermission.CanRegisterUsers) + }); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/auth/users/{userId}/permissions" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/auth/users/{userId}/permissions" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/auth/users/{userId}/permissions" + } + } + ); + + Response(403, "The request failed because the current user is not an Admin.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/auth/users/{userId}/permissions", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the provided user does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "UsernameDoesNotExist", + instance = "/auth/users/{userId}/permissions", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/auth/users/{userId}/permissions", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "UserIdCannotBeEmpty" + } + } + }, + traceId = "00-839f81e411d7eb91ed5aa91e56b00bbb-7c8bd5dfabdaf2dc-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs new file mode 100644 index 00000000..8c2e8542 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Contracts.Requests.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserRole; + +/// +/// API endpoint for the /auth/users/{userId}/role route. +/// +public class GetUserRoleEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetUserRoleEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Authorization.GET_USER_ROLE_BY_USER_ID); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the authorization role of a user. + /// + /// The request containing the user for whom to get the authorization role. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetUserRoleRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs new file mode 100644 index 00000000..00f441d1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Enums.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetUserRole; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUserRoleEndpointSummary() + { + Summary = "Gets the authorization role of a user."; + Description = "Gets the authorization role of a user."; + + ExampleRequest = new GetUserRoleRequest( + UserId: Guid.NewGuid() + ); + + RequestParam(r => r.UserId, "The Id of the user for whom to get the authorization role. Required."); + + Response(200, "The authorization role of the user is returned.", + example: new RoleResponse( + Id: Guid.NewGuid(), + RoleName: "Admin" + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/auth/users/{userId}/role" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/auth/users/{userId}/role" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/auth/users/{userId}/role" + } + } + ); + + Response(403, "The request failed because the current user is not an Admin.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/auth/users/{userId}/role", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the provided user does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "UsernameDoesNotExist", + instance = "/api/v1/auth/users/{userId}/role", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/auth/users/{userId}/role", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "UserIdCannotBeEmpty" + } + } + }, + traceId = "00-839f81e411d7eb91ed5aa91e56b00bbb-7c8bd5dfabdaf2dc-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs new file mode 100644 index 00000000..7ebd5a3c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Contracts.Requests.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Presentation.Api.Common.Routes.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// API endpoint for the /auth/users/{userId}/role-and-permissions route. +/// +public class UpdateUserRoleAndPermissionsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public UpdateUserRoleAndPermissionsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.PUT); + Routes(ApiRoutes.Authorization.UPDATE_USER_ROLE_AND_PERMISSIONS_BY_USER_ID); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates an the authorization role and permissions of a user. + /// + /// The request containing the authorization role and permission of the user to be updated. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateUserRoleAndPermissionsRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs new file mode 100644 index 00000000..39ee8627 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointSummary.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Requests.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Enums.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateUserRoleAndPermissionsEndpointSummary() + { + Summary = "Updates the authorization role and permissions of a user."; + Description = "Updates the authorization role and permissions of a user, and returns the details."; + + ExampleRequest = new UpdateUserRoleAndPermissionsRequest( + UserId: Guid.NewGuid(), + RoleId: Guid.NewGuid(), + Permissions: [ + Guid.NewGuid(), + Guid.NewGuid(), + ] + ); + + RequestParam(r => r.UserId, "The Id of the user. Required."); + RequestParam(r => r.RoleId, "The Id of the role. Required."); + RequestParam(r => r.Permissions, "The collection of Ids of the permissions of the role. Required."); + + ResponseParam(r => r.UserId, "The id of the user whose role and permissions were updated."); + ResponseParam(r => r.Role, "The authorization role entity."); + ResponseParam(r => r.Permissions, "The list of permissions of the user."); + + + Response(200, "The authorization role and permissions of the user were successfully updated.", example: + new AuthorizationResponse( + UserId: Guid.NewGuid(), + Role: "Editor", + Permissions: new HashSet() { AuthorizationPermission.CanRegisterUsers, AuthorizationPermission.CanDeleteUsers } + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/auth/users/{userId}/role-and-permissions" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/auth/users/{userId}/role-and-permissions" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/auth/users/{userId}/role-and-permissions" + } + } + ); + + Response(403, "The request failed because the current user is not an Admin, or changing the user's role would result in no user with an Admin account.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized | CannotRemoveLastAdmin | UserMustHaveRoleOrDirectPermissions", + instance = "/api/v1/auth/users/{userId}/role-and-permissions", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the provided role or user do not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "RoleNotFound | UserDoesNotExist", + instance = "/api/v1/auth/users/{userId}/role-and-permissions", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/auth/users/{userId}/role-and-permissions", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "UserIdCannotBeEmpty", + "RoleIdCannotBeEmpty", + "PermissionIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index cfb60cc9..87e6c801 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.IO; +using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; @@ -206,7 +207,12 @@ public class ApiHttpClient : IApiHttpClient string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); // if the response is successful, deserialize the content to TResponse and return it if (response.IsSuccessStatusCode) + { + // handle empty content case + if (string.IsNullOrEmpty(content)) + return default!; return JsonSerializer.Deserialize(content, _jsonOptions)!; + } else { ProblemDetailsModel? problemDetails = null; diff --git a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs index 614a3425..f6357404 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs @@ -52,7 +52,7 @@ public class AuthorizationService : IAuthorizationService public async Task IsInRoleAsync(string role, CancellationToken cancellationToken) { GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(cancellationToken).ConfigureAwait(false); - return authorization.Roles.Contains(role); + return authorization.Role == role; } /// @@ -75,7 +75,7 @@ public class AuthorizationService : IAuthorizationService { GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(CancellationToken.None); - if (requirement.Roles?.Length > 0 && !requirement.Roles.Any(role => authorization.Roles?.Contains(role) == true)) + 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))) diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs index d59c761d..e1b743e0 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs @@ -10,11 +10,11 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; /// Represents the response model for an account authorization request. /// /// The Id of the user for whom the authorization is retrieved. -/// The collection of roles associated to the user. +/// The role associated to the user. /// The collection of permissions associated to the user. [DebuggerDisplay("UserId: {UserId}")] public record GetAuthorizationResponse( Guid UserId, - string[] Roles, + string? Role, AuthorizationPermission[] Permissions ); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs index 115e18a0..ac0496e4 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs @@ -1,15 +1,13 @@ #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 role. +/// Represents a model for an authorization role with its permissions. /// -/// The Id of the authorization role. /// The authorization role. +/// The permissions of the authorization role. public record RolePermissionsModel( RoleModel Role, PermissionModel[] Permissions diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs index c2cc74fe..3fa994fd 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.cs @@ -10,7 +10,7 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; /// /// The Id of the role. /// The name of the role. -/// The collection or permissions of the role. +/// The collection of Ids of the permissions of the role. public record UpdateRoleRequestModel( Guid RoleId, string? RoleName, diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs new file mode 100644 index 00000000..9342aaf8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateUserRoleAndPermissionsRequestModel.cs @@ -0,0 +1,18 @@ +#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 Id of the user. +/// The Id 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/Authorization/UserPermissionsModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/UserPermissionsModel.cs new file mode 100644 index 00000000..71f0e249 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/UserPermissionsModel.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.UsersManagement; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Authorization; + +/// +/// Represents a model for a user with its authorization permissions. +/// +/// The user. +/// The authorization permissions of the user. +public record UserPermissionsModel( + UserModel User, + PermissionModel[] Permissions +); diff --git a/src/Lumina.Presentation.Web/Controllers/AdminController.cs b/src/Lumina.Presentation.Web/Controllers/AdminController.cs index 9a9adc64..b83e9591 100644 --- a/src/Lumina.Presentation.Web/Controllers/AdminController.cs +++ b/src/Lumina.Presentation.Web/Controllers/AdminController.cs @@ -40,7 +40,7 @@ public class AdminController : Controller { // get the list of roles and permissions from the API ViewData["roles"] = await _apiHttpClient.GetAsync($"roles/", cancellationToken).ConfigureAwait(false); - ViewData["rolePermissions"] = await _apiHttpClient.GetAsync($"permissions/", cancellationToken).ConfigureAwait(false); + ViewData["permissions"] = await _apiHttpClient.GetAsync($"permissions/", cancellationToken).ConfigureAwait(false); return View(); } @@ -53,6 +53,7 @@ public class AdminController : Controller { ViewData["users"] = await _apiHttpClient.GetAsync($"auth/users", cancellationToken).ConfigureAwait(false); ViewData["roles"] = await _apiHttpClient.GetAsync($"roles/", cancellationToken).ConfigureAwait(false); + ViewData["permissions"] = await _apiHttpClient.GetAsync($"permissions/", cancellationToken).ConfigureAwait(false); return View(); } @@ -68,6 +69,30 @@ public class AdminController : Controller return Json(new { success = true, data = response }); } + /// + /// Gets the authorization permissions of a user identified by . + /// + /// The Id of the user for whom to get the list of permissions. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-permissions-by-user-id/{userId}")] + 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 Id of the user for whom to get the role. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-role-by-user-id/{userId}")] + 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. /// @@ -114,4 +139,16 @@ public class AdminController : Controller await _apiHttpClient.DeleteAsync($"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("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/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 2056881e..4e35f2b6 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -141,6 +141,9 @@ Navigation nach oben nicht möglich! + + Der letzte zugewiesene Admin-Rolle kann nicht entfernt werden! + Codec darf nicht leer sein! @@ -516,6 +519,9 @@ Benutzer-ID darf nicht leer sein! + + Benutzer muss entweder Rollen- oder direkte Berechtigungen haben! + Benutzername existiert bereits! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 294177a5..cf429712 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -141,6 +141,9 @@ Cannot navigate up! + + Cannot remove the last Admin role assigned to a user! + Codec cannot be empty! @@ -516,6 +519,9 @@ User Id cannot be empty! + + User must have permissions either from role permissions or direct user permissions + Username already exists! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index e4103588..af94dbd3 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -141,6 +141,9 @@ ¡No se puede navegar hacia arriba! + + ¡No se puede eliminar el último rol de Admin asignado al usuario! + ¡El códec no puede estar vacío! @@ -516,6 +519,9 @@ ¡El ID de usuario no puede estar vacío! + + ¡El usuario debe tener permisos de rol o permisos directos! + ¡El nombre de usuario ya existe! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 8f7eb643..14d01457 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -141,6 +141,9 @@ Impossible de remonter le dossier ! + + Impossible de supprimer le dernier rôle Admin attribué à l'utilisateur! + Le codec ne peut pas être vide ! @@ -516,6 +519,9 @@ L'identifiant utilisateur ne peut pas être vide ! + + L'utilisateur doit avoir des permissions de rôle ou des permissions directes! + Le nom d'utilisateur existe déjà! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 5e866ae4..41489661 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -141,6 +141,9 @@ Impossibile navigare verso l'alto! + + Impossibile rimuovere l'ultimo ruolo Admin assegnato all'utente! + Il codec non può essere vuoto! @@ -516,6 +519,9 @@ L'ID utente non può essere vuoto! + + L'utente deve avere permessi da ruolo o permessi diretti! + Il nome utente esiste già! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index f2b85a76..b5c7eb36 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -141,6 +141,9 @@ 上の階層に移動できません! + + 最後の管理者権限を削除できません! + コーデックを空にすることはできません! @@ -516,6 +519,9 @@ ユーザーIDを空にすることはできません! + + ユーザーにはロール権限か直接権限のいずれかが必要です! + このユーザー名は既に使用されています! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 099db804..51b66fad 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -141,6 +141,9 @@ Cannot navigate up! + + Cannot remove the last Admin role assigned to a user! + Codec cannot be empty! @@ -516,6 +519,9 @@ User Id cannot be empty! + + User must have permissions either from role permissions or direct user permissions + Username already exists! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index be845649..0b13bb89 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -141,6 +141,9 @@ Nu se poate naviga în sus! + + Nu se poate elimina ultimul rol de Admin atribuit unui utilizator! + Codecul nu poate fi gol! @@ -516,6 +519,9 @@ ID-ul utilizatorului nu poate fi gol! + + Utilizatorul trebuie să aibă permisiuni din rol sau permisiuni directe! + Numele de utilizator există deja! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index 64347b3d..bbe9306a 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -141,6 +141,9 @@ Невозможно перейти на уровень выше! + + Невозможно удалить последнюю роль администратора, назначенную пользователю! + Кодек не может быть пустым! @@ -516,6 +519,9 @@ Идентификатор пользователя не может быть пустым! + + У пользователя должны быть разрешения роли или прямые разрешения! + Имя пользователя уже существует! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index b55e2162..1ea6f1ed 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -141,6 +141,9 @@ 无法向上导航! + + 无法删除用户的最后一个管理员角色! + 编解码器不能为空! @@ -516,6 +519,9 @@ 用户ID不能为空! + + 用户必须具有角色权限或直接权限! + 用户名已存在! diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.de-DE.resx new file mode 100644 index 00000000..765a5384 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.de-DE.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Kann Benutzer löschen + + + Kann Benutzer registrieren + + + Kann Benutzer anzeigen + + + Rollen + + + Wählen Sie eine Rolle + + + Benutzer auswählen + + + Aktualisieren + + + Benutzerberechtigung aktualisiert! + + + Benutzer + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.en-US.resx new file mode 100644 index 00000000..1ba01825 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.en-US.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Can delete users + + + Can register users + + + Can view users + + + Roles + + + Select a role + + + Select a user + + + Update + + + User authorization updated! + + + Users + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.es-ES.resx new file mode 100644 index 00000000..71d285c2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.es-ES.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Puede eliminar usuarios + + + Puede registrar usuarios + + + Puede ver usuarios + + + Roles + + + Selecciona un rol + + + Seleccionar usuario + + + Actualizar + + + ¡Autorización de usuario actualizada! + + + Usuarios + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.fr-FR.resx new file mode 100644 index 00000000..30b59ac8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.fr-FR.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Peut supprimer des utilisateurs + + + Peut enregistrer des utilisateurs + + + Peut voir les utilisateurs + + + Rôles + + + Sélectionnez un rôle + + + Sélectionner un utilisateur + + + Mettre à jour + + + Autorisation utilisateur mise à jour! + + + Utilisateurs + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.it-IT.resx new file mode 100644 index 00000000..e5bfea1c --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.it-IT.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Può eliminare utenti + + + Può registrare utenti + + + Può visualizzare utenti + + + Ruoli + + + Seleziona un ruolo + + + Seleziona utente + + + Aggiorna + + + Autorizzazione utente aggiornata! + + + Utenti + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ja-JP.resx new file mode 100644 index 00000000..b1dba7cc --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ja-JP.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + ユーザーを削除できます + + + ユーザーを登録できます + + + ユーザーを表示できます + + + ロール + + + ロールを選択してください + + + ユーザーを選択 + + + 更新 + + + ユーザー権限を更新しました! + + + ユーザー + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.resx new file mode 100644 index 00000000..1ba01825 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Can delete users + + + Can register users + + + Can view users + + + Roles + + + Select a role + + + Select a user + + + Update + + + User authorization updated! + + + Users + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ro-RO.resx new file mode 100644 index 00000000..b6a988d8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ro-RO.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Poate șterge utilizatori + + + Poate înregistra utilizatori + + + Poate vizualiza utilizatori + + + Roluri + + + Selectare rol + + + Selectare utilizator + + + Actualizare + + + Autorizare utilizator actualizată! + + + Utilizatori + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ru-RU.resx new file mode 100644 index 00000000..f04a30ac --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.ru-RU.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Может удалять пользователей + + + Может регистрировать пользователей + + + Может просматривать пользователей + + + Роли + + + Выберите роль + + + Выбрать пользователя + + + Обновить + + + Авторизация пользователя обновлена! + + + Пользователи + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.zh-CN.resx new file mode 100644 index 00000000..eb9218a9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManagePermissions.zh-CN.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 可以删除用户 + + + 可以注册用户 + + + 可以查看用户 + + + 角色 + + + 选择一个角色 + + + 选择用户 + + + 更新 + + + 用户授权已更新! + + + 用户 + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml b/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml index b8c43d98..a8624e26 100644 --- a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml +++ b/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml @@ -2,100 +2,231 @@ /admin/manage-permissions/ *@ -@using Lumina.Presentation.Web.Common.Models.Authorization +@using Lumina.Presentation.Web.Common.Models.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 rolePermissions = ViewData["rolePermissions"] as PermissionModel[]; -} + var users = ViewData["users"] as UserModel[]; + var permissions = ViewData["permissions"] as PermissionModel[]; + // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); +} @inject IViewLocalizer _localizer +@inject IUrlService _urlService -
- - -
- + +
+ + + +
+ -
-
- - -
-
-
@_localizer["SelectARole"]
- @if (roles is not null) - { - @for (int i = 0; i < roles.Length; i++) +
+
+ + +
+
+
@_localizer["SelectAUser"]
+ @if (users is not null) { -
@roles[i].RoleName
- } - } -
-
-
- - -
- - -
- - -
-
-
- @if (rolePermissions is not null) - { - @foreach (var rolePermission in rolePermissions) - { -
- -
- } - } -
-
-
- - -
- - -
- - -@*
-
-
- @Html.AntiForgeryToken() - @{ -
-
-
- - -
-
-
@_localizer["None"]
- @foreach (var item in aa!) + @for (int i = 0; i < users.Length; i++) { -
@_localizer[item.ToString()]
+
@users[i].Username
+ } + } +
+
+
+ + +
+ + +
+
+ + +
+
+
@_localizer["SelectARole"]
+ @if (roles is not null) + { + @for (int i = 0; i < roles.Length; i++) + { +
@roles[i].RoleName
+ } + } +
+
+
+ + +
+
+
+
+ @if (permissions is not null) + { + @foreach (var permission in permissions) + { +
+ +
+ } }
- } -

a

+
-
-
*@ + +
+ +
+
+ + +@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css b/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css index 5f282702..812d5578 100644 --- a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css +++ b/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css @@ -1 +1,46 @@ - \ No newline at end of file +#authorization-permissions-container { + display: flex; + margin: auto; + width: 100%; + height: 100%; + flex-direction: column; + flex-wrap: nowrap; +} + +#authorization-permissions-permissions-container { + flex-grow: 1; + min-width: 135px; + min-height: 0px; +} + +#authorization-permissions-permissions { + border: 1px solid var(--border-color-light-high); + border-top: 1px solid var(--border-color-dark); + border-left: 1px solid var(--border-color-dark); + margin: auto; + padding-left: 5px; + width: 100%; + height: 100%; + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: left; + align-items: stretch; +} + +#authorization-permissions-permissions-scroll { + background-color: #232323; + margin: auto; + width: 100%; + height: 100%; +} + +#authorization-permissions-permissions-list { + margin: 1px; + display: flex; + flex-direction: column; + flex-wrap: wrap; + border: 0px solid black; + padding: 0px; + gap: 0px 10px; +} diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml b/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml index 5a4bf223..71ee543a 100644 --- a/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml +++ b/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml @@ -8,7 +8,7 @@ @{ var roles = ViewData["roles"] as RoleModel[]; - var rolePermissions = ViewData["rolePermissions"] as PermissionModel[]; + var permissions = ViewData["permissions"] as PermissionModel[]; // 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(); } @@ -54,15 +54,15 @@
- @if (rolePermissions is not null) + @if (permissions is not null) { - @foreach (var rolePermission in rolePermissions) + @foreach (var permission in permissions) {
} @@ -82,28 +82,20 @@ @section Scripts { } diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml index 390e4047..5f5eedb4 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml @@ -70,30 +70,22 @@
@section Scripts { } diff --git a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml index 745ca064..70b2627e 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Login.cshtml @@ -64,28 +64,21 @@
@section Scripts { } diff --git a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml index a0779cbf..f2f903ca 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/RecoverPassword.cshtml @@ -58,29 +58,21 @@
@section Scripts { } diff --git a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml index 66eaaaeb..7474c99d 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/Register.cshtml @@ -99,28 +99,23 @@
@section Scripts { } diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml index c1a2b906..25f82330 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml @@ -138,24 +138,18 @@
@section Scripts { } diff --git a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml index 71523b8d..4043efe0 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -4,11 +4,16 @@ @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.Services @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.AspNetCore.Components @using System.Text.Json @using System.Text +@{ + var componentScriptId = ScriptIdentifierHelper.GenerateScriptId(); +} + @inject IViewLocalizer _localizer
@@ -522,14 +527,23 @@
- - + diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml index fd2f1255..a1bdff7b 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml @@ -29,6 +29,7 @@
@RenderBody()
+
@if (User?.Identity?.IsAuthenticated == true) diff --git a/src/Lumina.Presentation.Web/wwwroot/js/dialogs.js b/src/Lumina.Presentation.Web/wwwroot/js/dialogs.js index d043377d..081c8a93 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/dialogs.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/dialogs.js @@ -47,12 +47,6 @@ class DialogService { constructor() { this.dialogQueue = []; this.isDialogOpen = false; - - // create dialog container inside the article element - const articleElement = document.querySelector('article'); - this.container = document.createElement('div'); - this.container.className = 'dialog-container'; - articleElement.appendChild(this.container); } /** @@ -104,7 +98,7 @@ class DialogService { displayDialog(dialog) { const modalBackground = document.getElementById('modal-background-article'); modalBackground.style.display = 'block'; - this.container.style.display = 'block'; + document.querySelector('.dialog-container').style.display = 'block'; const dialogElement = document.createElement('div'); dialogElement.className = 'dialog'; @@ -164,7 +158,7 @@ class DialogService { }; document.addEventListener('keydown', keyHandler); - this.container.appendChild(dialogElement); + document.querySelector('.dialog-container').appendChild(dialogElement); } /** @@ -174,7 +168,7 @@ class DialogService { */ handleButtonClick(buttonType) { const currentDialog = this.dialogQueue.shift(); - const dialogElement = this.container.querySelector('.dialog'); + const dialogElement = document.querySelector('.dialog-container').querySelector('.dialog'); if (dialogElement) dialogElement.remove(); @@ -182,7 +176,7 @@ class DialogService { if (this.dialogQueue.length === 0) { const modalBackground = document.getElementById('modal-background-article'); modalBackground.style.display = 'none'; - this.container.style.display = 'none'; + document.querySelector('.dialog-container').style.display = 'none'; } currentDialog.resolve(buttonType); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js index fa6bbec8..851c8e29 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js @@ -1,460 +1,706 @@ -//+======================================================================================+ -//| DOM Elements | -//+======================================================================================+ +// because this script can be reused many times and only when needed, we need not polute the global space with the declarations - +// wrap everything in an IIFE (Immediately Invoked Function Expression), which creates a scope each time +(function () { + console.log('Loaded File System Explorer script'); -const modalBackgroundMenu = document.getElementById('modal-background-menu'); -const modalBackgroundArticle = document.getElementById('modal-background-article'); -const fileSystemBrowserDialog = document.getElementById('file-system-browser-dialog'); -const fileSystemBrowserTreeview = document.getElementById('file-system-browser-treeview'); -const pathSegmentsContainer = document.getElementById('navigator-path-segments'); -const article = document.querySelector('article'); -const menubar = document.getElementsByClassName('menubar')[0]; + //+======================================================================================+ + //| DOM Elements | + //+======================================================================================+ -const fileSystemTreeViewContainer = document.getElementById('file-system-browser-file-system-treeview-container'); -const fileSystemExplorerContainer = document.getElementById('file-system-browser-file-system-explorer-container'); -const fileSystemExplorer = document.getElementById('file-system-browser-file-system-explorer'); -const fileSystemDetailsHeader = document.getElementById('file-system-browser-file-system-explorer-details-header'); + const modalBackgroundMenu = document.getElementById('modal-background-menu'); + const modalBackgroundArticle = document.getElementById('modal-background-article'); + const fileSystemBrowserDialog = document.getElementById('file-system-browser-dialog'); + const fileSystemBrowserTreeview = document.getElementById('file-system-browser-treeview'); + const pathSegmentsContainer = document.getElementById('navigator-path-segments'); + const article = document.querySelector('article'); + const menubar = document.getElementsByClassName('menubar')[0]; -const addressBarInput = document.getElementById('navigator-address-bar-input'); -const addressBar = document.getElementById('navigator-address-bar'); + const fileSystemTreeViewContainer = document.getElementById('file-system-browser-file-system-treeview-container'); + const fileSystemExplorerContainer = document.getElementById('file-system-browser-file-system-explorer-container'); + const fileSystemExplorer = document.getElementById('file-system-browser-file-system-explorer'); + const fileSystemDetailsHeader = document.getElementById('file-system-browser-file-system-explorer-details-header'); -const btnNavigatorNavigateBack = document.getElementById('navigator-navigate-back'); -const btnNavigatorNavigateForward = document.getElementById('navigator-navigate-forward'); -const btnNavigatorNavigateUp = document.getElementById('navigator-navigate-up'); + const addressBarInput = document.getElementById('navigator-address-bar-input'); + const addressBar = document.getElementById('navigator-address-bar'); -const btnNavigatorToggleTreeView = document.getElementById('navigator-toggle-tree-view-button'); -const btnNavigatorToggleThumbnails = document.getElementById('navigator-toggle-thumbnails-button'); -const btnNavigatorToggleSelectionMode = document.getElementById('navigator-toggle-selection-button'); -const btnNavigatorHiddenElements = document.getElementById('navigator-toggle-hidden-button'); -const btnEditPath = document.getElementById('navigator-edit-path-button'); + const btnNavigatorNavigateBack = document.getElementById('navigator-navigate-back'); + const btnNavigatorNavigateForward = document.getElementById('navigator-navigate-forward'); + const btnNavigatorNavigateUp = document.getElementById('navigator-navigate-up'); -const svgTreeView = document.querySelectorAll('.navigator-icon-fill.tree-view'); -const svgThumbnails = document.querySelectorAll('.navigator-icon-fill.thumbnails'); -const svgSelectionMode = document.querySelectorAll('.navigator-icon-fill.selection-mode'); -const svgHiddenElements = document.querySelectorAll('.navigator-icon-fill.hidden-elements'); -const svgListView = document.querySelectorAll('.navigator-icon-fill.list'); -const svgDetailsView = document.querySelectorAll('.navigator-icon-fill.details'); -const svgSmallIconsView = document.querySelectorAll('.navigator-icon-fill.small-icons'); -const svgMediumIconsView = document.querySelectorAll('.navigator-icon-fill.medium-icons'); -const svgLargeIconsView = document.querySelectorAll('.navigator-icon-fill.large-icons'); -const svgExtraLargeIconsView = document.querySelectorAll('.navigator-icon-fill.extra-large-icons'); + const btnNavigatorToggleTreeView = document.getElementById('navigator-toggle-tree-view-button'); + const btnNavigatorToggleThumbnails = document.getElementById('navigator-toggle-thumbnails-button'); + const btnNavigatorToggleSelectionMode = document.getElementById('navigator-toggle-selection-button'); + const btnNavigatorHiddenElements = document.getElementById('navigator-toggle-hidden-button'); + const btnEditPath = document.getElementById('navigator-edit-path-button'); -const btnListView = document.getElementById('navigator-list-view'); -const btnDetailsView = document.getElementById('navigator-details-view'); -const btnSmallIconsView = document.getElementById('navigator-small-icons-view'); -const btnMediumIconsView = document.getElementById('navigator-medium-icons-view'); -const btnLargeIconsView = document.getElementById('navigator-large-icons-view'); -const btnExtraLargeIconsView = document.getElementById('navigator-extra-large-icons-view'); + const svgTreeView = document.querySelectorAll('.navigator-icon-fill.tree-view'); + const svgThumbnails = document.querySelectorAll('.navigator-icon-fill.thumbnails'); + const svgSelectionMode = document.querySelectorAll('.navigator-icon-fill.selection-mode'); + const svgHiddenElements = document.querySelectorAll('.navigator-icon-fill.hidden-elements'); + const svgListView = document.querySelectorAll('.navigator-icon-fill.list'); + const svgDetailsView = document.querySelectorAll('.navigator-icon-fill.details'); + const svgSmallIconsView = document.querySelectorAll('.navigator-icon-fill.small-icons'); + const svgMediumIconsView = document.querySelectorAll('.navigator-icon-fill.medium-icons'); + const svgLargeIconsView = document.querySelectorAll('.navigator-icon-fill.large-icons'); + const svgExtraLargeIconsView = document.querySelectorAll('.navigator-icon-fill.extra-large-icons'); -const btnFileSystemBrowserEditPath = document.getElementById('navigator-edit-path-button'); -const btnFileSystemBrowserSubmitPath = document.getElementById('navigator-navigate-button'); -const btnFileSystemBrowserConfirm = document.getElementById('file-system-browser-confirm-button'); -const btnFileSystemBrowserCancel = document.getElementById('file-system-browser-cancel-button'); + const btnListView = document.getElementById('navigator-list-view'); + const btnDetailsView = document.getElementById('navigator-details-view'); + const btnSmallIconsView = document.getElementById('navigator-small-icons-view'); + const btnMediumIconsView = document.getElementById('navigator-medium-icons-view'); + const btnLargeIconsView = document.getElementById('navigator-large-icons-view'); + const btnExtraLargeIconsView = document.getElementById('navigator-extra-large-icons-view'); -const selectedFileSystemElementsInput = document.getElementById('file-system-browser-selected-element'); + const btnFileSystemBrowserEditPath = document.getElementById('navigator-edit-path-button'); + const btnFileSystemBrowserSubmitPath = document.getElementById('navigator-navigate-button'); + const btnFileSystemBrowserConfirm = document.getElementById('file-system-browser-confirm-button'); + const btnFileSystemBrowserCancel = document.getElementById('file-system-browser-cancel-button'); -const selectionRectangle = document.getElementById('selection-rectangle'); -const visibleSelectionRectangle = document.getElementById('visible-selection-rectangle'); + const selectedFileSystemElementsInput = document.getElementById('file-system-browser-selected-element'); -//+======================================================================================+ -//| Variables | -//+======================================================================================+ + const selectionRectangle = document.getElementById('selection-rectangle'); + const visibleSelectionRectangle = document.getElementById('visible-selection-rectangle'); -// current icon pack theme -const CURRENT_ICON_THEME = "Lyra"; -// mapping of file extensions to SVG image paths -const FILE_ICONS = { - "ai": "application-postscript.svg", - "apk": "android-package-archive.svg", - "appimage": "application-vnd.appimage.svg", - "atom": "application-atom+xml.svg", - "avif": "application-image.svg", - "bmp": "application-image.svg", - "bz": "application-x-7z-ace.svg", - "chm": "application-vnd.ms-htmlhelp.svg", - "dicom": "application-dicom.svg", - "dll": "application-octet-stream.svg", - "dot": "application-msword-template.svg", - "doc": "application-msword-template.svg", - "docx": "application-msword-template.svg", - "eps": "application-postscript.svg", - "epub": "application-epub+zip.svg", - "exe": "application-octet-stream.svg", - "flac": "application-ogg.svg", - "gif": "application-image.svg", - "gz": "application-x-7z-ace.svg", - "ico": "application-image.svg", - "infopath": "application-vnd.ms-infopath.svg", - "jpeg": "application-image.svg", - "jpg": "application-image.svg", - "json": "application-json.svg", - "mdb": "application-vnd.ms-access.svg", - "mp3": "application-ogg.svg", - "ogg": "application-ogg.svg", - "otp": "application-vnd.oasis.opendocument.presentation-template.svg", - "ods": "application-vnd.oasis.opendocument.spreadsheet-template.svg", - "ots": "application-vnd.oasis.opendocument.spreadsheet-template.svg", - "ott": "application-vnd.oasis.opendocument.text-template.svg", - "otw": "application-vnd.oasis.opendocument.web-template.svg", - "p7s": "application-pgp-signature.svg", - "pdf": "application-pdf.svg", - "pict": "application-image.svg", - "pgp": "application-pgp.svg", - "png": "application-image.svg", - "ppt": "application-vnd.ms-powerpoint.svg", - "ps": "application-postscript.svg", - "psd": "application-photoshop.svg", - "pub": "application-vnd.ms-publisher.svg", - "rar": "application-x-7z-ace.svg", - "ref": "application-vnd.flatpak.ref.svg", - "sendfile": "application-vnd.kde.bluedevil-sendfile.svg", - "snap": "application-vnd.snap.svg", - "stream": "application-octet-stream.svg", - "svg": "application-image.svg", - "sql": "application-sql.svg", - "sqlite": "application-sql.svg", - "tar": "application-x-7z-ace.svg", - "tga": "application-image.svg", - "tiff": "application-image.svg", - "txt": "application-pgp-signature.svg", - "wav": "application-ogg.svg", - "webp": "application-image.svg", - "xdgapp": "application-vnd.xdgapp.svg", - "xls": "application-vnd.ms-excel.svg", - "xlsx": "application-vnd.ms-excel.svg", - "xml": "application-atom+xml.svg", - "zip": "application-x-7z-ace.svg" -}; + //+======================================================================================+ + //| Variables | + //+======================================================================================+ -let serverBasePath; -let clientBasePath; -let _path; -let pathSeparator = '/'; -let platformType = 'Unix'; -let showFileSystemTreeView = true; // TODO: take from config -let showHiddenElements = true; // TODO: take from config -let includeFiles = true; // TODO: take from config -let viewMode = 'list-icons'; // TODO: take from config -let undoStack = []; -let redoStack = []; + // current icon pack theme + const CURRENT_ICON_THEME = "Lyra"; + // mapping of file extensions to SVG image paths + const FILE_ICONS = { + "ai": "application-postscript.svg", + "apk": "android-package-archive.svg", + "appimage": "application-vnd.appimage.svg", + "atom": "application-atom+xml.svg", + "avif": "application-image.svg", + "bmp": "application-image.svg", + "bz": "application-x-7z-ace.svg", + "chm": "application-vnd.ms-htmlhelp.svg", + "dicom": "application-dicom.svg", + "dll": "application-octet-stream.svg", + "dot": "application-msword-template.svg", + "doc": "application-msword-template.svg", + "docx": "application-msword-template.svg", + "eps": "application-postscript.svg", + "epub": "application-epub+zip.svg", + "exe": "application-octet-stream.svg", + "flac": "application-ogg.svg", + "gif": "application-image.svg", + "gz": "application-x-7z-ace.svg", + "ico": "application-image.svg", + "infopath": "application-vnd.ms-infopath.svg", + "jpeg": "application-image.svg", + "jpg": "application-image.svg", + "json": "application-json.svg", + "mdb": "application-vnd.ms-access.svg", + "mp3": "application-ogg.svg", + "ogg": "application-ogg.svg", + "otp": "application-vnd.oasis.opendocument.presentation-template.svg", + "ods": "application-vnd.oasis.opendocument.spreadsheet-template.svg", + "ots": "application-vnd.oasis.opendocument.spreadsheet-template.svg", + "ott": "application-vnd.oasis.opendocument.text-template.svg", + "otw": "application-vnd.oasis.opendocument.web-template.svg", + "p7s": "application-pgp-signature.svg", + "pdf": "application-pdf.svg", + "pict": "application-image.svg", + "pgp": "application-pgp.svg", + "png": "application-image.svg", + "ppt": "application-vnd.ms-powerpoint.svg", + "ps": "application-postscript.svg", + "psd": "application-photoshop.svg", + "pub": "application-vnd.ms-publisher.svg", + "rar": "application-x-7z-ace.svg", + "ref": "application-vnd.flatpak.ref.svg", + "sendfile": "application-vnd.kde.bluedevil-sendfile.svg", + "snap": "application-vnd.snap.svg", + "stream": "application-octet-stream.svg", + "svg": "application-image.svg", + "sql": "application-sql.svg", + "sqlite": "application-sql.svg", + "tar": "application-x-7z-ace.svg", + "tga": "application-image.svg", + "tiff": "application-image.svg", + "txt": "application-pgp-signature.svg", + "wav": "application-ogg.svg", + "webp": "application-image.svg", + "xdgapp": "application-vnd.xdgapp.svg", + "xls": "application-vnd.ms-excel.svg", + "xlsx": "application-vnd.ms-excel.svg", + "xml": "application-atom+xml.svg", + "zip": "application-x-7z-ace.svg" + }; -let selectionStartPosition = { x: 0, y: 0 }; -let currentMousePosition = { x: 0, y: 0 }; -let isSelecting = false; -let isSelectionMode = false; + let serverBasePath; + let clientBasePath; + let _path; + let pathSeparator = '/'; + let platformType = 'Unix'; + let showFileSystemTreeView = true; // TODO: take from config + let showHiddenElements = true; // TODO: take from config + let includeFiles = true; // TODO: take from config + let viewMode = 'list-icons'; // TODO: take from config + let undoStack = []; + let redoStack = []; -let scrollTimeout; // timeout to delay thumbnail loading after scrolling -let resizeTimeout; // timeout to delay thumbnail loading after resizing -let abortController; // allows the cancellation of thumbnail retrieval jobs -let hasScrolledAfterModeChange = false; // flag to track if scrolling occurred after a mode change -let showThumbnails = true; // whether to show thumbnails or not -let scrollThumbnailRetrievalTimeout = 1000; // the time span to wait after the last scroll, before getting thumbnails -let inspectFileForThumbnails = false; // whether to check the actual header bytes in order to determine if a file is an image, rather than its extension -let thumbnailsRetrievalBatchSize = 20; // the number of thumbnails to ask from the server, concurrently -let imagePreviewsQuality = 70; // the quality used for image thumbnails -let fullImageQuality = 90; // the quality used for full images + let selectionStartPosition = { x: 0, y: 0 }; + let currentMousePosition = { x: 0, y: 0 }; + let isSelecting = false; + let isSelectionMode = false; + + let scrollTimeout; // timeout to delay thumbnail loading after scrolling + let resizeTimeout; // timeout to delay thumbnail loading after resizing + let abortController; // allows the cancellation of thumbnail retrieval jobs + let hasScrolledAfterModeChange = false; // flag to track if scrolling occurred after a mode change + let showThumbnails = true; // whether to show thumbnails or not + let scrollThumbnailRetrievalTimeout = 1000; // the time span to wait after the last scroll, before getting thumbnails + let inspectFileForThumbnails = false; // whether to check the actual header bytes in order to determine if a file is an image, rather than its extension + let thumbnailsRetrievalBatchSize = 20; // the number of thumbnails to ask from the server, concurrently + let imagePreviewsQuality = 70; // the quality used for image thumbnails + let fullImageQuality = 90; // the quality used for full images -//+======================================================================================+ -//| Initialization | -//+======================================================================================+ + //+======================================================================================+ + //| Initialization | + //+======================================================================================+ -/** - * Initializes the values needed by the file sytem browser. - * @param {any} serverBasePathValue The base path of the server API. - * @param {any} clientBasePathValue The base path of the client app API. - * @param {any} initialPath The initial path of the file system browser. - * @param {any} viewModeValue The initial view mode of he file system browser. - * @param {any} iconSizeValue The initial icon size of the file system browser. - */ -async function initFileSystemBrowser(serverBasePathValue, clientBasePathValue, initialPath, viewModeValue, iconSizeValue) { - serverBasePath = serverBasePathValue; - clientBasePath = clientBasePathValue; - await getFileSystemPropertiesAsync(); - if (!initialPath.endsWith(pathSeparator)) - initialPath += pathSeparator; + /** + * Initializes the values needed by the file sytem browser. + * @param {any} serverBasePathValue The base path of the server API. + * @param {any} clientBasePathValue The base path of the client app API. + * @param {any} initialPath The initial path of the file system browser. + * @param {any} viewModeValue The initial view mode of he file system browser. + * @param {any} iconSizeValue The initial icon size of the file system browser. + */ + async function initFileSystemBrowser(serverBasePathValue, clientBasePathValue, initialPath, viewModeValue, iconSizeValue) { + serverBasePath = serverBasePathValue; + clientBasePath = clientBasePathValue; + await getFileSystemPropertiesAsync(); + if (!initialPath.endsWith(pathSeparator)) + initialPath += pathSeparator; - _path = initialPath; - addressBarInput.value = initialPath; - showFileSystemTreeView = true; // TODO: take from config + _path = initialPath; + addressBarInput.value = initialPath; + showFileSystemTreeView = true; // TODO: take from config - addHorizontalScrolling(addressBar); - //switchViewMode('list', null, true); - switchViewMode(viewModeValue, viewModeValue === 'list' ? null : iconSizeValue, true); -} - -/** - * Shows the file system browser dialog. - */ -async function showFileSystemBrowserDialogAsync(path, showHiddenElementsValue, includeFilesValue, onConfirmCallback) { - if (path !== undefined && path !== null) { - showHiddenElements = showHiddenElementsValue; - includeFiles = includeFilesValue; - modalBackgroundMenu.style.display = 'block'; - modalBackgroundArticle.style.display = 'block'; - fileSystemBrowserDialog.style.display = 'block'; - if (!path.endsWith(pathSeparator)) - path += pathSeparator; - addressBarInput.value = path; - await toggleShowFileSystemHiddenElementsAsync(false); - await toggleFileSystemTreeViewAsync(false); - await toggleShowFileSystemElementsThumbnailsAsync(false); - await navigateToPathAsync(path, false, false); - // add click handler for confirm button - btnFileSystemBrowserConfirm.onclick = function () { - const selectedPaths = selectedFileSystemElementsInput.value; - if (onConfirmCallback && typeof onConfirmCallback === 'function') - onConfirmCallback(selectedPaths); - // hide dialog - hideFileSystemBrowserDialog(); - }; - btnFileSystemBrowserCancel.onclick = hideFileSystemBrowserDialog; - } else - notificationService.Show("Path cannot be null!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented -} - -/** - * Hides the file system browser dialog. - */ -function hideFileSystemBrowserDialog() { - modalBackgroundMenu.style.display = 'none'; - modalBackgroundArticle.style.display = 'none'; - fileSystemBrowserDialog.style.display = 'none'; -} - -/** - * Retrieves file system properties from the server, asynchronously. - * @returns {Promise} A promise that resolves once the properties have been fetched. - */ -async function getFileSystemPropertiesAsync() { - // call the API to get the file system type (platform type) - const fileSystemTypeResponse = await callApiGetAsync(`${clientBasePath}file-system/get-type`); - if (fileSystemTypeResponse !== undefined) - platformType = fileSystemTypeResponse.platformType; - // call the API to get the path separator for the file system - const pathSeparatorResponse = await callApiGetAsync(`${clientBasePath}path/get-path-separator`); - if (pathSeparatorResponse !== undefined) - pathSeparator = pathSeparatorResponse.pathSeparator; -} - -/** - * Checks if the specified path is a valid file system path, and exists. - * @param {any} path The path to validate and check. - * @returns {Promise} A promise that resolves to whether the path is valid and exists, or not. - */ -async function checkPathAsync(path) { - const pathValidResponse = await callApiGetAsync(`${clientBasePath}path/validate?path=${encodeURIComponent(path)}`); - if (pathValidResponse !== undefined) { - if (!pathValidResponse.isValid) { - notificationService.show("Specified path is not valid!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented - addressBarInput.value = _path; - if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; - } else { - const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/check-path-exists?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`); - if (pathExistsResponse !== undefined && !pathExistsResponse.exists) { - notificationService.show("Specified path does not exist!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented - return false; - } - } - return pathValidResponse.isValid; + addHorizontalScrolling(addressBar); + //switchViewMode('list', null, true); + switchViewMode(viewModeValue, viewModeValue === 'list' ? null : iconSizeValue, true); } -} -/** - * Navigates to the specified path, - * @param {any} path The path o navigate to. - * @param {any} isForwardNavigation Whether the Forward button was clicked, and navigation is done to a history location or not. - * @param {any} isBackwardNavigation Whether the Back button was clicked, and navigation is done to a history location or not. - */ -async function navigateToPathAsync(path, isForwardNavigation, isBackwardNavigation) { - if (await checkPathAsync(path)) { - // if there was a job for thumbnails retrieval, cancel it first - if (abortController) { - abortController.abort(); - abortController = null; - } - // check if backward navigation is possible - if (isBackwardNavigation) { - if (undoStack.length > 0) { - // get the first path in the backward navigation list - const backwardPath = undoStack.pop(); - // put the current path in the forward navigationlist, before navigating to the backward path - if (addressBarInput.value !== null) { - if (!addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; - redoStack.push(addressBarInput.value); + /** + * Shows the file system browser dialog. + */ + async function showFileSystemBrowserDialogAsync(path, showHiddenElementsValue, includeFilesValue, onConfirmCallback) { + if (path !== undefined && path !== null) { + showHiddenElements = showHiddenElementsValue; + includeFiles = includeFilesValue; + modalBackgroundMenu.style.display = 'block'; + modalBackgroundArticle.style.display = 'block'; + fileSystemBrowserDialog.style.display = 'block'; + if (!path.endsWith(pathSeparator)) + path += pathSeparator; + addressBarInput.value = path; + await toggleShowFileSystemHiddenElementsAsync(false); + await toggleFileSystemTreeViewAsync(false); + await toggleShowFileSystemElementsThumbnailsAsync(false); + await navigateToPathAsync(path, false, false); + // add click handler for confirm button + btnFileSystemBrowserConfirm.onclick = function () { + const selectedPaths = selectedFileSystemElementsInput.value; + if (onConfirmCallback && typeof onConfirmCallback === 'function') + onConfirmCallback(selectedPaths); + // hide dialog + hideFileSystemBrowserDialog(); + }; + btnFileSystemBrowserCancel.onclick = hideFileSystemBrowserDialog; + } else + notificationService.Show("Path cannot be null!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented + } + + /** + * Hides the file system browser dialog. + */ + function hideFileSystemBrowserDialog() { + modalBackgroundMenu.style.display = 'none'; + modalBackgroundArticle.style.display = 'none'; + fileSystemBrowserDialog.style.display = 'none'; + } + + /** + * Retrieves file system properties from the server, asynchronously. + * @returns {Promise} A promise that resolves once the properties have been fetched. + */ + async function getFileSystemPropertiesAsync() { + // call the API to get the file system type (platform type) + const fileSystemTypeResponse = await callApiGetAsync(`${clientBasePath}file-system/get-type`); + if (fileSystemTypeResponse !== undefined) + platformType = fileSystemTypeResponse.platformType; + // call the API to get the path separator for the file system + const pathSeparatorResponse = await callApiGetAsync(`${clientBasePath}path/get-path-separator`); + if (pathSeparatorResponse !== undefined) + pathSeparator = pathSeparatorResponse.pathSeparator; + } + + /** + * Checks if the specified path is a valid file system path, and exists. + * @param {any} path The path to validate and check. + * @returns {Promise} A promise that resolves to whether the path is valid and exists, or not. + */ + async function checkPathAsync(path) { + const pathValidResponse = await callApiGetAsync(`${clientBasePath}path/validate?path=${encodeURIComponent(path)}`); + if (pathValidResponse !== undefined) { + if (!pathValidResponse.isValid) { + notificationService.show("Specified path is not valid!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented + addressBarInput.value = _path; + if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + } else { + const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/check-path-exists?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`); + if (pathExistsResponse !== undefined && !pathExistsResponse.exists) { + notificationService.show("Specified path does not exist!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented + return false; } - path = backwardPath; - } else - return; - } else if (isForwardNavigation) { // check if forward navigation is possible - if (redoStack.length > 0) { - // get the first path in the forward navigation list - const forwardPath = redoStack.pop(); - // put the current path in the backward navigation list, before navigating to the forward path - if (addressBarInput.value !== null) { - if (!addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; + } + return pathValidResponse.isValid; + } + } + + /** + * Navigates to the specified path, + * @param {any} path The path o navigate to. + * @param {any} isForwardNavigation Whether the Forward button was clicked, and navigation is done to a history location or not. + * @param {any} isBackwardNavigation Whether the Back button was clicked, and navigation is done to a history location or not. + */ + async function navigateToPathAsync(path, isForwardNavigation, isBackwardNavigation) { + if (await checkPathAsync(path)) { + // if there was a job for thumbnails retrieval, cancel it first + if (abortController) { + abortController.abort(); + abortController = null; + } + // check if backward navigation is possible + if (isBackwardNavigation) { + if (undoStack.length > 0) { + // get the first path in the backward navigation list + const backwardPath = undoStack.pop(); + // put the current path in the forward navigationlist, before navigating to the backward path + if (addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + redoStack.push(addressBarInput.value); + } + path = backwardPath; + } else + return; + } else if (isForwardNavigation) { // check if forward navigation is possible + if (redoStack.length > 0) { + // get the first path in the forward navigation list + const forwardPath = redoStack.pop(); + // put the current path in the backward navigation list, before navigating to the forward path + if (addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== addressBarInput.value)) + undoStack.push(addressBarInput.value); + } + path = forwardPath; + } else + return; + } else { // navigation to a brand new location (up, directory browse, manual path edit, etc) + redoStack = []; + if (addressBarInput.value !== null && addressBarInput.value !== path) { // when navigating up, addressBarInput.value will be set after navigation if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== addressBarInput.value)) undoStack.push(addressBarInput.value); + } else if (_path !== null && _path !== path) { // when editing the address, addressBarInput.value already comes set, check against control value + if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== _path)) + undoStack.push(_path); } - path = forwardPath; - } else - return; - } else { // navigation to a brand new location (up, directory browse, manual path edit, etc) - redoStack = []; - if (addressBarInput.value !== null && addressBarInput.value !== path) { // when navigating up, addressBarInput.value will be set after navigation - if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== addressBarInput.value)) - undoStack.push(addressBarInput.value); - } else if (_path !== null && _path !== path) { // when editing the address, addressBarInput.value already comes set, check against control value - if (undoStack.length === 0 || (undoStack.length > 0 && undoStack[undoStack.length - 1] !== _path)) - undoStack.push(_path); + } + _path = path; // we are about to navigate to the new path, store its value in the control variable + addressBarInput.style.display = 'none'; // hide #address-bar-input + addressBar.style.display = 'block'; // show #address-bar + await getNavigatorPathAsync(path); + await getFileSystemItemsAsync(path); + if (showFileSystemTreeView) + await getFileSystemTreeViewAsync(path); + if (showThumbnails) + getFileSystemVisibleItems(); + } + addressBarInput.value = _path; + if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + } + + /** + * Navigates up one level from the current path + */ + async function navigateUpAsync() { + if (addressBarInput.value !== null) { + // ask the API for the parent path + const parentLocationResponse = await callApiGetAsync(`${clientBasePath}path/get-path-parent?path=${encodeURIComponent(addressBarInput.value)}`); + if (parentLocationResponse !== undefined && parentLocationResponse.pathSegments !== null) { + // if the answer was valid, and we can navigate up, reconstruct the provided path from its segments, and navigate to it + platformType = parentLocationResponse.pathSegments; + let parentConcatenatedPath = parentLocationResponse.pathSegments[0].path; + for (var i = 1; i < parentLocationResponse.pathSegments.length; i++) + parentConcatenatedPath = (parentConcatenatedPath !== pathSeparator ? parentConcatenatedPath : '') + pathSeparator + parentLocationResponse.pathSegments[i].path; + if (!parentConcatenatedPath.endsWith(pathSeparator)) + parentConcatenatedPath += pathSeparator; + await navigateToPathAsync(parentConcatenatedPath, false, false); } } - _path = path; // we are about to navigate to the new path, store its value in the control variable - addressBarInput.style.display = 'none'; // hide #address-bar-input - addressBar.style.display = 'block'; // show #address-bar - await getNavigatorPathAsync(path); - await getFileSystemItemsAsync(path); - if (showFileSystemTreeView) - await getFileSystemTreeViewAsync(path); - if (showThumbnails) - getFileSystemVisibleItems(); } - addressBarInput.value = _path; - if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; -} -/** - * Navigates up one level from the current path - */ -async function navigateUpAsync() { - if (addressBarInput.value !== null) { - // ask the API for the parent path - const parentLocationResponse = await callApiGetAsync(`${clientBasePath}path/get-path-parent?path=${encodeURIComponent(addressBarInput.value)}`); - if (parentLocationResponse !== undefined && parentLocationResponse.pathSegments !== null) { - // if the answer was valid, and we can navigate up, reconstruct the provided path from its segments, and navigate to it - platformType = parentLocationResponse.pathSegments; - let parentConcatenatedPath = parentLocationResponse.pathSegments[0].path; - for (var i = 1; i < parentLocationResponse.pathSegments.length; i++) - parentConcatenatedPath = (parentConcatenatedPath !== pathSeparator ? parentConcatenatedPath : '') + pathSeparator + parentLocationResponse.pathSegments[i].path; - if (!parentConcatenatedPath.endsWith(pathSeparator)) - parentConcatenatedPath += pathSeparator; - await navigateToPathAsync(parentConcatenatedPath, false, false); + + //+======================================================================================+ + //| Navigator | + //+======================================================================================+ + + /** + * Gets the navigator path segments. + * @param {any} path The path for which to get the navigator path segments. + */ + async function getNavigatorPathAsync(path) { + const pathSplitResponse = await callApiGetAsync(`${clientBasePath}path/split?path=${encodeURIComponent(path)}`); + if (pathSplitResponse !== undefined) + renderAddressBar(pathSplitResponse.pathSegments); + } + + /** + * Render the address bar based on the provided path segments. + * @param {Array} pathSegments - An array of path segments. + */ + function renderAddressBar(pathSegments) { + pathSegmentsContainer.removeEventListener('change', handlePathSegmentComboboxChangeAsync); // remove previous listeners + pathSegmentsContainer.addEventListener('change', handlePathSegmentComboboxChangeAsync); // add new listener + pathSegmentsContainer.innerHTML = ""; // clear existing segments + if (pathSegments !== null) { + pathSegments.forEach((segment, index) => { + const li = document.createElement("li"); + li.id = `path-segment-${index}`; + // create the combobox + const combobox = document.createElement("div"); + combobox.className = "navigator-combobox inline-block"; + // the shine effect + const shineEffect = document.createElement("div"); + shineEffect.className = "shine-effect"; + shineEffect.style.top = "1px"; + combobox.appendChild(shineEffect); + const toggleCheckbox = document.createElement("input"); + toggleCheckbox.type = "checkbox"; + toggleCheckbox.className = "navigator-toggle-checkbox"; + toggleCheckbox.id = `segment-toggle-${index}`; + combobox.appendChild(toggleCheckbox); + const toggleLabel = document.createElement("label"); + toggleLabel.className = "navigator-toggle"; + toggleLabel.htmlFor = `segment-toggle-${index}`; + const span = document.createElement("span"); + span.className = "navigator-selected-text"; + span.innerText = segment.path; + toggleLabel.appendChild(span); + // add the arrow element + const arrowSpan = document.createElement("span"); + arrowSpan.className = "navigator-arrow"; + toggleLabel.appendChild(arrowSpan); + combobox.appendChild(toggleLabel); + const dropdown = document.createElement("div"); + dropdown.className = "navigator-dropdown"; + dropdown.id = `navigator-dropdown-${index}`; + dropdown.setAttribute('data-path-segment-id', `path-segment-${index}`); + // get the segments from start to the current one (on UNIX, start with path separator char!) + const concatenatedPath = (platformType === "Unix" ? '/' : '') + pathSegments.slice(0, index + 1).map(seg => seg.path).join(pathSeparator); + combobox.setAttribute('data-path', concatenatedPath + (!concatenatedPath.endsWith(pathSeparator) ? pathSeparator : '')); + combobox.appendChild(dropdown); + li.appendChild(combobox); + pathSegmentsContainer.appendChild(li); + }); + } else + pathSegmentsContainer.querySelectorAll('li').forEach(li => li.remove()); // no address, clear path segments + } + + /** + * Handle the change event for the comboboxes inside the path-segments. + * This function is triggered when any of the comboboxes (checkboxes) in the navigation bar is toggled. + * @param {Event} e - The change event object. + */ + async function handlePathSegmentComboboxChangeAsync(e) { + // ensure the event was triggered by an element with the 'navigator-toggle-checkbox' class + if (e.target.classList.contains('navigator-toggle-checkbox')) { + const comboboxId = e.target.id; + const dropdownId = comboboxId.replace('segment-toggle-', 'navigator-dropdown-'); + const dropdown = document.getElementById(dropdownId); + reattachDropdown(); + if (!e.target.checked) + return; + const comboboxElement = e.target.closest('.navigator-combobox'); // get the closest parent (or self) with the specified class + const pathValue = comboboxElement.getAttribute('data-path'); // retrieve the data-path attribute value + // clear any existing dropdown elements + dropdown.innerHTML = ""; + showBusyIndicator(); + setupDropdown(dropdown, e.target); + + // add combobox entry for current directory + addDirectoryOption(dropdown, pathValue, ".", async () => { + addressBarInput.value = pathValue; + await navigateToPathAsync(pathValue, false, false); + }); + + // add combobox entry for parent directory + addDirectoryOption(dropdown, pathValue, "..", async () => { + addressBarInput.value = pathValue; + await navigateUpAsync(); + }); + + // fetch directory data for the path + try { + await fetchFileSystemDirectoriesAsync(pathValue, (parsedItem) => { + addDirectoryOption(dropdown, pathValue, parsedItem.name, async () => { + const newPath = pathValue + (!pathValue.endsWith(pathSeparator) ? pathSeparator : '') + parsedItem.name + pathSeparator; + addressBarInput.value = newPath; + await navigateToPathAsync(newPath, false, false); + }); + }); + } catch (error) { + console.error('Error:', error); + notificationService.show(error, NotificationType.ERROR); + } finally { + hideBusyIndicator(); + } } } -} + /** + * Configures and positions the dropdown for directory navigation. + * @param {HTMLElement} dropdown - The dropdown element to set up. + * @param {HTMLElement} toggleElement - The element that triggered the dropdown. + */ + function setupDropdown(dropdown, toggleElement) { + // when drop down opens, need to show address bar overflow, otherwise clipping of drop down occurs + // store the id of the parent combobox of the dropdown - the dropdown will be reparented + // because of manadatory "overflow hidden" of scrollable area and clipping isues + dropdown.setAttribute('data-parent', toggleElement.id); + dropdown.setAttribute('data-detached', true); + const position = toggleElement.closest('.navigator-combobox').getBoundingClientRect(); + // detach dropdown and reposition + document.body.appendChild(dropdown); + dropdown.style.position = 'absolute'; + dropdown.style.top = `${position.bottom}px`; + dropdown.style.left = `${position.left}px`; + dropdown.style.display = 'block'; + // handle addressBar scroll to adjust dropdown position + addressBar.addEventListener('scroll', adjustDropdownPosition); + } -//+======================================================================================+ -//| Navigator | -//+======================================================================================+ + /** + * Adds a directory option to the dropdown. + * @param {HTMLElement} dropdown - The dropdown to add the option to. + * @param {string} pathValue - The current path. + * @param {string} name - The name of the directory option. + * @param {Function} clickHandler - Function to call when the option is clicked. + */ + function addDirectoryOption(dropdown, pathValue, name, clickHandler) { + const directoryDiv = document.createElement('div'); + directoryDiv.className = "navigator-option"; + directoryDiv.dataset.value = pathValue + (name !== "." && name !== ".." ? name : ""); + directoryDiv.textContent = name; + directoryDiv.addEventListener('click', clickHandler); + dropdown.appendChild(directoryDiv); + } -/** - * Gets the navigator path segments. - * @param {any} path The path for which to get the navigator path segments. - */ -async function getNavigatorPathAsync(path) { - const pathSplitResponse = await callApiGetAsync(`${clientBasePath}path/split?path=${encodeURIComponent(path)}`); - if (pathSplitResponse !== undefined) - renderAddressBar(pathSplitResponse.pathSegments); -} + /** + * Re-attaches the detached visible drop down to the path segment or platform combobox it originally belonged to + */ + function reattachDropdown() { + // when the combobox closes, re-attach the detached dropdown + const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"], .enlightenment-dropdown[data-detached="true"]'); + if (dropdown) { + // reset its absolute positioning and stuff + dropdown.style.position = ''; + dropdown.style.top = ''; + dropdown.style.left = ''; + dropdown.style.display = ''; + // re-attach it to original parent + const dataParent = dropdown.getAttribute('data-parent'); + dropdown.removeAttribute('data-detached'); + const originalParent = document.getElementById(dataParent).parentNode; + if (originalParent) + originalParent.appendChild(dropdown); + // remove scroll event listener from the addressBar + addressBar.removeEventListener('scroll', adjustDropdownPosition); + } + } -/** - * Render the address bar based on the provided path segments. - * @param {Array} pathSegments - An array of path segments. - */ -function renderAddressBar(pathSegments) { - pathSegmentsContainer.removeEventListener('change', handlePathSegmentComboboxChangeAsync); // remove previous listeners - pathSegmentsContainer.addEventListener('change', handlePathSegmentComboboxChangeAsync); // add new listener - pathSegmentsContainer.innerHTML = ""; // clear existing segments - if (pathSegments !== null) { - pathSegments.forEach((segment, index) => { - const li = document.createElement("li"); - li.id = `path-segment-${index}`; - // create the combobox - const combobox = document.createElement("div"); - combobox.className = "navigator-combobox inline-block"; - // the shine effect - const shineEffect = document.createElement("div"); - shineEffect.className = "shine-effect"; - shineEffect.style.top = "1px"; - combobox.appendChild(shineEffect); - const toggleCheckbox = document.createElement("input"); - toggleCheckbox.type = "checkbox"; - toggleCheckbox.className = "navigator-toggle-checkbox"; - toggleCheckbox.id = `segment-toggle-${index}`; - combobox.appendChild(toggleCheckbox); - const toggleLabel = document.createElement("label"); - toggleLabel.className = "navigator-toggle"; - toggleLabel.htmlFor = `segment-toggle-${index}`; - const span = document.createElement("span"); - span.className = "navigator-selected-text"; - span.innerText = segment.path; - toggleLabel.appendChild(span); - // add the arrow element - const arrowSpan = document.createElement("span"); - arrowSpan.className = "navigator-arrow"; - toggleLabel.appendChild(arrowSpan); - combobox.appendChild(toggleLabel); - const dropdown = document.createElement("div"); - dropdown.className = "navigator-dropdown"; - dropdown.id = `navigator-dropdown-${index}`; - dropdown.setAttribute('data-path-segment-id', `path-segment-${index}`); - // get the segments from start to the current one (on UNIX, start with path separator char!) - const concatenatedPath = (platformType === "Unix" ? '/' : '') + pathSegments.slice(0, index + 1).map(seg => seg.path).join(pathSeparator); - combobox.setAttribute('data-path', concatenatedPath + (!concatenatedPath.endsWith(pathSeparator) ? pathSeparator : '')); - combobox.appendChild(dropdown); - li.appendChild(combobox); - pathSegmentsContainer.appendChild(li); - }); - } else - pathSegmentsContainer.querySelectorAll('li').forEach(li => li.remove()); // no address, clear path segments -} + /** + * Adjusts the position of a detached drop down, such that it is always just under its original + * path segment combobox, even when this parent is moved through scrolling + */ + function adjustDropdownPosition() { + const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"]'); + if (dropdown) { + const comboboxElement = document.getElementById(dropdown.getAttribute('data-parent')); // get the related combobox + const position = comboboxElement.parentNode.getBoundingClientRect(); + dropdown.style.top = position.bottom + 'px'; + dropdown.style.left = position.left + 'px'; + } + } -/** - * Handle the change event for the comboboxes inside the path-segments. - * This function is triggered when any of the comboboxes (checkboxes) in the navigation bar is toggled. - * @param {Event} e - The change event object. - */ -async function handlePathSegmentComboboxChangeAsync(e) { - // ensure the event was triggered by an element with the 'navigator-toggle-checkbox' class - if (e.target.classList.contains('navigator-toggle-checkbox')) { - const comboboxId = e.target.id; - const dropdownId = comboboxId.replace('segment-toggle-', 'navigator-dropdown-'); - const dropdown = document.getElementById(dropdownId); - reattachDropdown(); - if (!e.target.checked) - return; - const comboboxElement = e.target.closest('.navigator-combobox'); // get the closest parent (or self) with the specified class - const pathValue = comboboxElement.getAttribute('data-path'); // retrieve the data-path attribute value - // clear any existing dropdown elements - dropdown.innerHTML = ""; - showBusyIndicator(); - setupDropdown(dropdown, e.target); + /** + * Updates the position and height of the dropdown relative to the specified path segment. + * @param {string} pathSegmentId - The ID of the path segment element to position the dropdown relative to. + */ + function updateDropdownPosition(pathSegmentId, dropdown) { + const element = document.getElementById(pathSegmentId); + if (element && dropdown) { + const rect = getElementOffset(pathSegmentId); + dropdown.style.top = `${rect.top + rect.height}px`; + dropdown.style.left = `${rect.left}px`; + } + } - // add combobox entry for current directory - addDirectoryOption(dropdown, pathValue, ".", async () => { - addressBarInput.value = pathValue; - await navigateToPathAsync(pathValue, false, false); - }); + //+======================================================================================+ + //| Tree View | + //+======================================================================================+ - // add combobox entry for parent directory - addDirectoryOption(dropdown, pathValue, "..", async () => { - addressBarInput.value = pathValue; - await navigateUpAsync(); - }); + /** + * Gets the file system tree view + * @param {string} initialPath - The initial path to expand in the tree view (optional). + * @returns {Promise} + */ + async function getFileSystemTreeViewAsync(initialPath) { + // clear the existing tree view + fileSystemBrowserTreeview.innerHTML = ''; + // fetch available drives asynchronously + const drives = await getFileSystemDrivesAsync(); + // iterate through each drive and add it to the tree view as root node + for (const drive of drives) { + // create a tree node for the drive + const driveNode = createFileSystemTreeViewTreeNode(drive); + // append the drive node to the tree view + fileSystemBrowserTreeview.appendChild(driveNode); + // if the initial path starts with this drive's path, expand the tree view to show the initial path + if (initialPath.toLowerCase().startsWith(drive.path.toLowerCase())) + await expandInitialTreeViewPathAsync(driveNode, initialPath); + } + } - // fetch directory data for the path + /** + * Asynchronously fetches the list of available drives from the server. + * @returns {Promise|undefined>} A promise that resolves to an array of drive objects, or undefined if the API call fails. + */ + async function getFileSystemDrivesAsync() { + const getDrivesResponse = await callApiGetAsync(`${clientBasePath}drives/get-drives`); + if (getDrivesResponse !== undefined) + return getDrivesResponse.drives; + } + + /** + * Creates a tree node element for the file system tree view. + * @param {Object} nodeData - Data for the node (path, itemType, name). + * @returns {HTMLElement} The created tree node element. + */ + function createFileSystemTreeViewTreeNode(nodeData) { + const treeNodeDiv = document.createElement("div"); + treeNodeDiv.className = "tree-node"; + treeNodeDiv.setAttribute('data-path', nodeData.path); + + const nodeContent = document.createElement("span"); + nodeContent.className = "node-content"; + nodeContent.addEventListener('click', handleNodeClickAsync); + + const expandButton = document.createElement("span"); + expandButton.className = nodeData.itemType !== 'File' ? "expand-button" : "spacer"; + expandButton.addEventListener('click', toggleFileSysemTreeViewNodeExpandAsync); + + const nodeIcon = document.createElement("span"); + nodeIcon.className = "node-icon"; + nodeIcon.textContent = getNodeIcon(nodeData); + + const nodeName = document.createElement("span"); + nodeName.className = "node-name"; + nodeName.textContent = nodeData.name; + + // assemble the node structure + nodeContent.appendChild(expandButton); + nodeContent.appendChild(nodeIcon); + nodeContent.appendChild(nodeName); + treeNodeDiv.appendChild(nodeContent); + + const childNodes = document.createElement("div"); + childNodes.className = "child-nodes"; + treeNodeDiv.appendChild(childNodes); + + return treeNodeDiv; + } + + /** + * Handles click events on tree nodes. + * @param {Event} e - The click event object. + */ + async function handleNodeClickAsync(e) { + // get the node that was clicked + const treeNode = e.target.closest('.tree-node'); + // retrieve the path stored on the clicked node + selectedPath = treeNode.getAttribute('data-path'); + if (selectedPath !== null) { + // ensure path ends with separator + if (!selectedPath.endsWith(pathSeparator)) + selectedPath += pathSeparator; + // set the retrieved path as the navigator path, and navigate to it + addressBarInput.value = selectedPath; + await navigateToPathAsync(selectedPath, false, false); + } + } + + /** + * Toggles the expansion of a file system tree view node. + * @param {Event} e - The click event on the expand button. + */ + async function toggleFileSysemTreeViewNodeExpandAsync(e) { + e.stopPropagation(); + // get the node that was clicked + const treeNode = e.target.closest('.tree-node'); + const treeNodeIcon = treeNode.querySelector('.node-icon'); + const nodeData = { itemType: 'Directory' }; + + const expandButton = e.target; + // get the div that hosts child nodes in tthe clicked node + const childNodes = treeNode.querySelector('.child-nodes'); + const path = treeNode.getAttribute('data-path'); + // get the current expanded state of the clicked node, and toggle it + const isExpanded = expandButton.classList.contains('expanded'); + nodeData.isExpanded = !isExpanded; + treeNodeIcon.textContent = getNodeIcon(nodeData); + // expand or collapse the node + if (isExpanded) { + expandButton.classList.remove('expanded'); + childNodes.style.display = 'none'; + } else { + expandButton.classList.add('expanded'); + childNodes.style.display = 'block'; + // if node is expanded and child nodes are not yet loaded, load them + if (childNodes.children.length === 0) + await loadFileSystemTreeViewChildNodesAsync(treeNode, path); + } + } + + /** + * Loads child nodes for a given parent node in the file system tree view. + * @param {HTMLElement} parentNode - The parent node element in the tree view. + * @param {string} path - The file system path to load children from. + */ + async function loadFileSystemTreeViewChildNodesAsync(parentNode, path) { + // get the div that hosts child nodes + const childNodes = parentNode.querySelector('.child-nodes'); + // clear existing child nodes + childNodes.innerHTML = ''; try { - await fetchFileSystemDirectoriesAsync(pathValue, (parsedItem) => { - addDirectoryOption(dropdown, pathValue, parsedItem.name, async () => { - const newPath = pathValue + (!pathValue.endsWith(pathSeparator) ? pathSeparator : '') + parsedItem.name + pathSeparator; - addressBarInput.value = newPath; - await navigateToPathAsync(newPath, false, false); - }); + showBusyIndicator(); + // fetch directory information and create nodes for each + await fetchFileSystemDirectoriesAsync(path, (dir) => { + dir.itemType = 'Directory'; + const dirNode = createFileSystemTreeViewTreeNode(dir); + childNodes.appendChild(dirNode); }); } catch (error) { console.error('Error:', error); @@ -463,1129 +709,893 @@ async function handlePathSegmentComboboxChangeAsync(e) { hideBusyIndicator(); } } -} -/** - * Configures and positions the dropdown for directory navigation. - * @param {HTMLElement} dropdown - The dropdown element to set up. - * @param {HTMLElement} toggleElement - The element that triggered the dropdown. - */ -function setupDropdown(dropdown, toggleElement) { - // when drop down opens, need to show address bar overflow, otherwise clipping of drop down occurs - // store the id of the parent combobox of the dropdown - the dropdown will be reparented - // because of manadatory "overflow hidden" of scrollable area and clipping isues - dropdown.setAttribute('data-parent', toggleElement.id); - dropdown.setAttribute('data-detached', true); - const position = toggleElement.closest('.navigator-combobox').getBoundingClientRect(); - // detach dropdown and reposition - document.body.appendChild(dropdown); - dropdown.style.position = 'absolute'; - dropdown.style.top = `${position.bottom}px`; - dropdown.style.left = `${position.left}px`; - dropdown.style.display = 'block'; - // handle addressBar scroll to adjust dropdown position - addressBar.addEventListener('scroll', adjustDropdownPosition); -} - -/** - * Adds a directory option to the dropdown. - * @param {HTMLElement} dropdown - The dropdown to add the option to. - * @param {string} pathValue - The current path. - * @param {string} name - The name of the directory option. - * @param {Function} clickHandler - Function to call when the option is clicked. - */ -function addDirectoryOption(dropdown, pathValue, name, clickHandler) { - const directoryDiv = document.createElement('div'); - directoryDiv.className = "navigator-option"; - directoryDiv.dataset.value = pathValue + (name !== "." && name !== ".." ? name : ""); - directoryDiv.textContent = name; - directoryDiv.addEventListener('click', clickHandler); - dropdown.appendChild(directoryDiv); -} - -/** - * Re-attaches the detached visible drop down to the path segment or platform combobox it originally belonged to - */ -function reattachDropdown() { - // when the combobox closes, re-attach the detached dropdown - const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"], .enlightenment-dropdown[data-detached="true"]'); - if (dropdown) { - // reset its absolute positioning and stuff - dropdown.style.position = ''; - dropdown.style.top = ''; - dropdown.style.left = ''; - dropdown.style.display = ''; - // re-attach it to original parent - const dataParent = dropdown.getAttribute('data-parent'); - dropdown.removeAttribute('data-detached'); - const originalParent = document.getElementById(dataParent).parentNode; - if (originalParent) - originalParent.appendChild(dropdown); - // remove scroll event listener from the addressBar - addressBar.removeEventListener('scroll', adjustDropdownPosition); + /** + * Fetches directory information from the server for a given path. + * @param {string} path - The path to get directories from. + * @param {Function} callback - Function to call for each directory received. + */ + async function fetchFileSystemDirectoriesAsync(path, callback) { + await fetchJsonDataAsync(`${clientBasePath}directories/get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory'); } -} -/** - * Adjusts the position of a detached drop down, such that it is always just under its original - * path segment combobox, even when this parent is moved through scrolling - */ -function adjustDropdownPosition() { - const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"]'); - if (dropdown) { - const comboboxElement = document.getElementById(dropdown.getAttribute('data-parent')); // get the related combobox - const position = comboboxElement.parentNode.getBoundingClientRect(); - dropdown.style.top = position.bottom + 'px'; - dropdown.style.left = position.left + 'px'; + /** + * Fetches file information from the server for a given path. + * @param {string} path - The path to get files from. + * @param {Function} callback - Function to call for each file received. + */ + async function fetchFileSystemFilesAsync(path, callback) { + await fetchJsonDataAsync(`${clientBasePath}files/get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File'); } -} -/** - * Updates the position and height of the dropdown relative to the specified path segment. - * @param {string} pathSegmentId - The ID of the path segment element to position the dropdown relative to. - */ -function updateDropdownPosition(pathSegmentId, dropdown) { - const element = document.getElementById(pathSegmentId); - if (element && dropdown) { - const rect = getElementOffset(pathSegmentId); - dropdown.style.top = `${rect.top + rect.height}px`; - dropdown.style.left = `${rect.left}px`; - } -} - -//+======================================================================================+ -//| Tree View | -//+======================================================================================+ - -/** - * Gets the file system tree view - * @param {string} initialPath - The initial path to expand in the tree view (optional). - * @returns {Promise} - */ -async function getFileSystemTreeViewAsync(initialPath) { - // clear the existing tree view - fileSystemBrowserTreeview.innerHTML = ''; - // fetch available drives asynchronously - const drives = await getFileSystemDrivesAsync(); - // iterate through each drive and add it to the tree view as root node - for (const drive of drives) { - // create a tree node for the drive - const driveNode = createFileSystemTreeViewTreeNode(drive); - // append the drive node to the tree view - fileSystemBrowserTreeview.appendChild(driveNode); - // if the initial path starts with this drive's path, expand the tree view to show the initial path - if (initialPath.toLowerCase().startsWith(drive.path.toLowerCase())) - await expandInitialTreeViewPathAsync(driveNode, initialPath); - } -} - -/** - * Asynchronously fetches the list of available drives from the server. - * @returns {Promise|undefined>} A promise that resolves to an array of drive objects, or undefined if the API call fails. - */ -async function getFileSystemDrivesAsync() { - const getDrivesResponse = await callApiGetAsync(`${clientBasePath}drives/get-drives`); - if (getDrivesResponse !== undefined) - return getDrivesResponse.drives; -} - -/** - * Creates a tree node element for the file system tree view. - * @param {Object} nodeData - Data for the node (path, itemType, name). - * @returns {HTMLElement} The created tree node element. - */ -function createFileSystemTreeViewTreeNode(nodeData) { - const treeNodeDiv = document.createElement("div"); - treeNodeDiv.className = "tree-node"; - treeNodeDiv.setAttribute('data-path', nodeData.path); - - const nodeContent = document.createElement("span"); - nodeContent.className = "node-content"; - nodeContent.addEventListener('click', handleNodeClickAsync); - - const expandButton = document.createElement("span"); - expandButton.className = nodeData.itemType !== 'File' ? "expand-button" : "spacer"; - expandButton.addEventListener('click', toggleFileSysemTreeViewNodeExpandAsync); - - const nodeIcon = document.createElement("span"); - nodeIcon.className = "node-icon"; - nodeIcon.textContent = getNodeIcon(nodeData); - - const nodeName = document.createElement("span"); - nodeName.className = "node-name"; - nodeName.textContent = nodeData.name; - - // assemble the node structure - nodeContent.appendChild(expandButton); - nodeContent.appendChild(nodeIcon); - nodeContent.appendChild(nodeName); - treeNodeDiv.appendChild(nodeContent); - - const childNodes = document.createElement("div"); - childNodes.className = "child-nodes"; - treeNodeDiv.appendChild(childNodes); - - return treeNodeDiv; -} - -/** - * Handles click events on tree nodes. - * @param {Event} e - The click event object. - */ -async function handleNodeClickAsync(e) { - // get the node that was clicked - const treeNode = e.target.closest('.tree-node'); - // retrieve the path stored on the clicked node - selectedPath = treeNode.getAttribute('data-path'); - if (selectedPath !== null) { - // ensure path ends with separator - if (!selectedPath.endsWith(pathSeparator)) - selectedPath += pathSeparator; - // set the retrieved path as the navigator path, and navigate to it - addressBarInput.value = selectedPath; - await navigateToPathAsync(selectedPath, false, false); - } -} - -/** - * Toggles the expansion of a file system tree view node. - * @param {Event} e - The click event on the expand button. - */ -async function toggleFileSysemTreeViewNodeExpandAsync(e) { - e.stopPropagation(); - // get the node that was clicked - const treeNode = e.target.closest('.tree-node'); - const treeNodeIcon = treeNode.querySelector('.node-icon'); - const nodeData = { itemType: 'Directory' }; - - const expandButton = e.target; - // get the div that hosts child nodes in tthe clicked node - const childNodes = treeNode.querySelector('.child-nodes'); - const path = treeNode.getAttribute('data-path'); - // get the current expanded state of the clicked node, and toggle it - const isExpanded = expandButton.classList.contains('expanded'); - nodeData.isExpanded = !isExpanded; - treeNodeIcon.textContent = getNodeIcon(nodeData); - // expand or collapse the node - if (isExpanded) { - expandButton.classList.remove('expanded'); - childNodes.style.display = 'none'; - } else { - expandButton.classList.add('expanded'); - childNodes.style.display = 'block'; - // if node is expanded and child nodes are not yet loaded, load them - if (childNodes.children.length === 0) - await loadFileSystemTreeViewChildNodesAsync(treeNode, path); - } -} - -/** - * Loads child nodes for a given parent node in the file system tree view. - * @param {HTMLElement} parentNode - The parent node element in the tree view. - * @param {string} path - The file system path to load children from. - */ -async function loadFileSystemTreeViewChildNodesAsync(parentNode, path) { - // get the div that hosts child nodes - const childNodes = parentNode.querySelector('.child-nodes'); - // clear existing child nodes - childNodes.innerHTML = ''; - try { - showBusyIndicator(); - // fetch directory information and create nodes for each - await fetchFileSystemDirectoriesAsync(path, (dir) => { - dir.itemType = 'Directory'; - const dirNode = createFileSystemTreeViewTreeNode(dir); - childNodes.appendChild(dirNode); - }); - } catch (error) { - console.error('Error:', error); - notificationService.show(error, NotificationType.ERROR); - } finally { - hideBusyIndicator(); - } -} - -/** - * Fetches directory information from the server for a given path. - * @param {string} path - The path to get directories from. - * @param {Function} callback - Function to call for each directory received. - */ -async function fetchFileSystemDirectoriesAsync(path, callback) { - await fetchJsonDataAsync(`${clientBasePath}directories/get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory'); -} - -/** - * Fetches file information from the server for a given path. - * @param {string} path - The path to get files from. - * @param {Function} callback - Function to call for each file received. - */ -async function fetchFileSystemFilesAsync(path, callback) { - await fetchJsonDataAsync(`${clientBasePath}files/get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File'); -} - -/** - * Fetches and processes JSON data from a given URL. - * This function handles the data by processing all items in the response.data array - * and passing them through the callback function. - * - * @param {string} url - The URL to fetch JSON data from. - * @param {Function} callback - Function to call for each processed item. - * @param {string} itemType - Type of item being processed ('File' or 'Directory'). - */ -async function fetchJsonDataAsync(url, callback, itemType) { - const response = await callApiGetAsync(url); - if (response !== undefined) { - // process each item in the response.data array - for (let item of response) { - // manually specify the type to the parsed object - item.itemType = itemType; - // call the provided callback function with the processed item - callback(item); - } - } -} - -/** - * Expands the tree view to a specific target path. - * @param {HTMLElement} node - The starting node in the tree view. - * @param {string} targetPath - The full path to expand to. - */ -async function expandInitialTreeViewPathAsync(node, targetPath) { - const nodePath = node.getAttribute('data-path'); - // exit if the target path doesn't start with the node path - if (!targetPath.toLowerCase().startsWith(nodePath.toLowerCase())) - return; - // expand the current node if it's not already expanded - const expandButton = node.querySelector('.expand-button'); - if (expandButton && !expandButton.classList.contains('expanded')) - await toggleFileSysemTreeViewNodeExpandAsync({ target: expandButton, stopPropagation: () => { } }); - // split the remaining path into segments - const pathSegments = targetPath.slice(nodePath.length).split('\\').filter(Boolean); - let currentNode = node; - // iterate through each path segment - for (let i = 0; i < pathSegments.length; i++) { - const segment = pathSegments[i]; - const childNodes = currentNode.querySelector('.child-nodes'); - let found = false; - // search for the child node matching the current path segment - for (const childNode of childNodes.children) { - if (childNode.querySelector('.node-name').textContent.toLowerCase() === segment.toLowerCase()) { - currentNode = childNode; - found = true; - if (i === pathSegments.length - 1) { - // if this is the last segment (target node) - childNode.scrollIntoView(); // bring it into view, if its not already - // mark it as selected - childNode.querySelector('.node-content').classList.add('selected'); - // toggle this last node, because all its children will be loaded - const expandChildButton = childNode.querySelector('.expand-button'); - if (expandChildButton) - await toggleFileSysemTreeViewNodeExpandAsync({ target: expandChildButton, stopPropagation: () => { } }); - // load the node's children - await loadFileSystemTreeViewChildNodesAsync(childNode, childNode.getAttribute('data-path')); - } - else { - // if this is an intermediate node, expand it if necessary - const childExpandButton = childNode.querySelector('.expand-button'); - if (childExpandButton && !childExpandButton.classList.contains('expanded')) - await toggleFileSysemTreeViewNodeExpandAsync({ target: childExpandButton, stopPropagation: () => { } }); - } - break; + /** + * Fetches and processes JSON data from a given URL. + * This function handles the data by processing all items in the response.data array + * and passing them through the callback function. + * + * @param {string} url - The URL to fetch JSON data from. + * @param {Function} callback - Function to call for each processed item. + * @param {string} itemType - Type of item being processed ('File' or 'Directory'). + */ + async function fetchJsonDataAsync(url, callback, itemType) { + const response = await callApiGetAsync(url); + if (response !== undefined) { + // process each item in the response.data array + for (let item of response) { + // manually specify the type to the parsed object + item.itemType = itemType; + // call the provided callback function with the processed item + callback(item); } } - // if the current segment wasn't found, stop expanding - if (!found) - break; } -} -//+======================================================================================+ -//| File System | -//+======================================================================================+ - -/** - * Fetches and displays file system items for a given path. - * @param {string} path - The path to fetch items from. - */ -async function getFileSystemItemsAsync(path) { - // clear the current contents of the file system explorer - fileSystemExplorer.innerHTML = ''; - - try { - showBusyIndicator(); - // fetch file system items and create explorer items for each - await fetchFileSystemItemsAsync(path, (item) => { - const newItem = createFileSystemExplorerItem(item); - fileSystemExplorer.appendChild(newItem); - }); - } catch (error) { - console.error('Error:', error); - notificationService.show(error, NotificationType.ERROR); - } finally { - hideBusyIndicator(); - } -} - -/** - * Fetches both directories and files from a specified path. - * @param {string} path - The file system path to fetch items from. - * @param {Function} callback - Function to call for each item (directory or file) received. - */ -async function fetchFileSystemItemsAsync(path, callback) { - await fetchFileSystemDirectoriesAsync(path, callback); - if (includeFiles) - await fetchFileSystemFilesAsync(path, callback); -} - -/** - * Creates a DOM element representing a file system item (file or directory). - * @param {Object} item - The file system item data. - * @returns {HTMLElement} The created DOM element for the file system item. - */ -function createFileSystemExplorerItem(item) { - const itemDiv = document.createElement('div'); - const itemType = item.itemType; - // set up the main item div with appropriate classes and data attributes - itemDiv.className = `e ${viewMode}`; - itemDiv.setAttribute('data-path', item.path); - itemDiv.setAttribute('data-type', itemType); - // create and set up the icon div - const iconDiv = document.createElement('div'); - iconDiv.className = 'icon'; - iconDiv.innerHTML = ``; - // create and set up the text div - const textDiv = document.createElement('div'); - textDiv.className = 'text'; - // use different class for directory ('d') and file ('f') - textDiv.innerHTML = `${item.name}`; - // assemble the item structure - itemDiv.appendChild(iconDiv); - itemDiv.appendChild(textDiv); - // add event listeners for mouse interactions - itemDiv.onmouseup = handleFileSystemEntityMouseUpAsync; - itemDiv.onmousedown = handleFileSystemEntityMouseDown; - return itemDiv; -} - -/** - * Handles mouse up events on file system entities in the explorer view. - * Manages selection, double-click actions, and navigation. - * @param {MouseEvent} e - The mouse event. - */ -async function handleFileSystemEntityMouseUpAsync(e) { - e.preventDefault(); - if (!isSelecting) - e.stopPropagation(); - const allEClassElements = Array.from(fileSystemExplorer.querySelectorAll('.e')); - const currentIndex = allEClassElements.indexOf(e.currentTarget); - - // if a previous click timestamp exists, check the time difference - const previousTime = parseInt(e.currentTarget.dataset.selectionStartTime || 0); - const currentTime = new Date().getTime(); - const timeDifference = currentTime - previousTime; - - // TODO: needs to account for when the element is already selected, and a double click occurs - on first click it would check the difference and go to rename - - // maybe just wait half second before performing action - - // if time difference is less than 300ms, treat it as a double-click - if (timeDifference < 300) { - if (e.currentTarget.dataset.type === 'Directory') { // directories - addressBarInput.value = e.currentTarget.dataset.path; - await navigateToPathAsync(addressBarInput.value, false, false); // TODO: add to undo + /** + * Expands the tree view to a specific target path. + * @param {HTMLElement} node - The starting node in the tree view. + * @param {string} targetPath - The full path to expand to. + */ + async function expandInitialTreeViewPathAsync(node, targetPath) { + const nodePath = node.getAttribute('data-path'); + // exit if the target path doesn't start with the node path + if (!targetPath.toLowerCase().startsWith(nodePath.toLowerCase())) return; - } else { // files - - } - // reset the timestamp used to track double clicks - e.currentTarget.dataset.selectionStartTime = 0; - return; - } - else - e.currentTarget.dataset.selectionStartTime = currentTime; // element was single clicked, update the selection start time to now - if (e.ctrlKey || isSelectionMode) { // when CTRL key is pressed - // toggle selection for the current clicked item - e.currentTarget.classList.toggle('selected'); - // set the selection start if it's not already set - if (fileSystemExplorer.dataset.selectionStart === undefined) - fileSystemExplorer.dataset.selectionStart = currentIndex; - } - else if ((e.shiftKey && fileSystemExplorer.dataset.selectionStart !== undefined) || isSelectionMode) { // when SHIFT key is pressed - const start = parseInt(fileSystemExplorer.dataset.selectionStart); - // remove all selections - allEClassElements.forEach(elem => { - elem.classList.remove('selected'); - }); - // define the range to select items from and to - const [from, to] = start < currentIndex ? [start, currentIndex] : [currentIndex, start]; - // add the 'selected' class to items in the range - for (let i = from; i <= to; i++) - allEClassElements[i].classList.add('selected'); - } - else { // when neither CTRL nor SHIFT keys are pressed - if (!isSelectionMode) { - // get all elements that are selected - const selectedElements = allEClassElements.filter(element => element.classList.contains('selected')); - // add 'selected' class to the current clicked item - e.currentTarget.classList.add('selected'); - // if there are no selected elements, or if there are more than one, deselect all of them, and select just the clicked one - if ((selectedElements.length === 1 && e.currentTarget !== selectedElements[0]) || selectedElements.length !== 1) { - // deselect all items - selectedElements.forEach(elem => { - if (elem !== e.currentTarget) { - elem.classList.remove('selected'); - // remove selectionStartTime from all items - delete elem.dataset.selectionStartTime; + // expand the current node if it's not already expanded + const expandButton = node.querySelector('.expand-button'); + if (expandButton && !expandButton.classList.contains('expanded')) + await toggleFileSysemTreeViewNodeExpandAsync({ target: expandButton, stopPropagation: () => { } }); + // split the remaining path into segments + const pathSegments = targetPath.slice(nodePath.length).split('\\').filter(Boolean); + let currentNode = node; + // iterate through each path segment + for (let i = 0; i < pathSegments.length; i++) { + const segment = pathSegments[i]; + const childNodes = currentNode.querySelector('.child-nodes'); + let found = false; + // search for the child node matching the current path segment + for (const childNode of childNodes.children) { + if (childNode.querySelector('.node-name').textContent.toLowerCase() === segment.toLowerCase()) { + currentNode = childNode; + found = true; + if (i === pathSegments.length - 1) { + // if this is the last segment (target node) + childNode.scrollIntoView(); // bring it into view, if its not already + // mark it as selected + childNode.querySelector('.node-content').classList.add('selected'); + // toggle this last node, because all its children will be loaded + const expandChildButton = childNode.querySelector('.expand-button'); + if (expandChildButton) + await toggleFileSysemTreeViewNodeExpandAsync({ target: expandChildButton, stopPropagation: () => { } }); + // load the node's children + await loadFileSystemTreeViewChildNodesAsync(childNode, childNode.getAttribute('data-path')); } - }); - // set the current item as the selection start + else { + // if this is an intermediate node, expand it if necessary + const childExpandButton = childNode.querySelector('.expand-button'); + if (childExpandButton && !childExpandButton.classList.contains('expanded')) + await toggleFileSysemTreeViewNodeExpandAsync({ target: childExpandButton, stopPropagation: () => { } }); + } + break; + } + } + // if the current segment wasn't found, stop expanding + if (!found) + break; + } + } + + //+======================================================================================+ + //| File System | + //+======================================================================================+ + + /** + * Fetches and displays file system items for a given path. + * @param {string} path - The path to fetch items from. + */ + async function getFileSystemItemsAsync(path) { + // clear the current contents of the file system explorer + fileSystemExplorer.innerHTML = ''; + + try { + showBusyIndicator(); + // fetch file system items and create explorer items for each + await fetchFileSystemItemsAsync(path, (item) => { + const newItem = createFileSystemExplorerItem(item); + fileSystemExplorer.appendChild(newItem); + }); + } catch (error) { + console.error('Error:', error); + notificationService.show(error, NotificationType.ERROR); + } finally { + hideBusyIndicator(); + } + } + + /** + * Fetches both directories and files from a specified path. + * @param {string} path - The file system path to fetch items from. + * @param {Function} callback - Function to call for each item (directory or file) received. + */ + async function fetchFileSystemItemsAsync(path, callback) { + await fetchFileSystemDirectoriesAsync(path, callback); + if (includeFiles) + await fetchFileSystemFilesAsync(path, callback); + } + + /** + * Creates a DOM element representing a file system item (file or directory). + * @param {Object} item - The file system item data. + * @returns {HTMLElement} The created DOM element for the file system item. + */ + function createFileSystemExplorerItem(item) { + const itemDiv = document.createElement('div'); + const itemType = item.itemType; + // set up the main item div with appropriate classes and data attributes + itemDiv.className = `e ${viewMode}`; + itemDiv.setAttribute('data-path', item.path); + itemDiv.setAttribute('data-type', itemType); + // create and set up the icon div + const iconDiv = document.createElement('div'); + iconDiv.className = 'icon'; + iconDiv.innerHTML = ``; + // create and set up the text div + const textDiv = document.createElement('div'); + textDiv.className = 'text'; + // use different class for directory ('d') and file ('f') + textDiv.innerHTML = `${item.name}`; + // assemble the item structure + itemDiv.appendChild(iconDiv); + itemDiv.appendChild(textDiv); + // add event listeners for mouse interactions + itemDiv.onmouseup = handleFileSystemEntityMouseUpAsync; + itemDiv.onmousedown = handleFileSystemEntityMouseDown; + return itemDiv; + } + + /** + * Handles mouse up events on file system entities in the explorer view. + * Manages selection, double-click actions, and navigation. + * @param {MouseEvent} e - The mouse event. + */ + async function handleFileSystemEntityMouseUpAsync(e) { + e.preventDefault(); + if (!isSelecting) + e.stopPropagation(); + const allEClassElements = Array.from(fileSystemExplorer.querySelectorAll('.e')); + const currentIndex = allEClassElements.indexOf(e.currentTarget); + + // if a previous click timestamp exists, check the time difference + const previousTime = parseInt(e.currentTarget.dataset.selectionStartTime || 0); + const currentTime = new Date().getTime(); + const timeDifference = currentTime - previousTime; + + // TODO: needs to account for when the element is already selected, and a double click occurs - on first click it would check the difference and go to rename - + // maybe just wait half second before performing action + + // if time difference is less than 300ms, treat it as a double-click + if (timeDifference < 300) { + if (e.currentTarget.dataset.type === 'Directory') { // directories + addressBarInput.value = e.currentTarget.dataset.path; + await navigateToPathAsync(addressBarInput.value, false, false); // TODO: add to undo + return; + } else { // files + + } + // reset the timestamp used to track double clicks + e.currentTarget.dataset.selectionStartTime = 0; + return; + } + else + e.currentTarget.dataset.selectionStartTime = currentTime; // element was single clicked, update the selection start time to now + if (e.ctrlKey || isSelectionMode) { // when CTRL key is pressed + // toggle selection for the current clicked item + e.currentTarget.classList.toggle('selected'); + // set the selection start if it's not already set + if (fileSystemExplorer.dataset.selectionStart === undefined) fileSystemExplorer.dataset.selectionStart = currentIndex; - // store the current timestamp for future double-click checks - e.currentTarget.dataset.selectionStartTime = currentTime; + } + else if ((e.shiftKey && fileSystemExplorer.dataset.selectionStart !== undefined) || isSelectionMode) { // when SHIFT key is pressed + const start = parseInt(fileSystemExplorer.dataset.selectionStart); + // remove all selections + allEClassElements.forEach(elem => { + elem.classList.remove('selected'); + }); + // define the range to select items from and to + const [from, to] = start < currentIndex ? [start, currentIndex] : [currentIndex, start]; + // add the 'selected' class to items in the range + for (let i = from; i <= to; i++) + allEClassElements[i].classList.add('selected'); + } + else { // when neither CTRL nor SHIFT keys are pressed + if (!isSelectionMode) { + // get all elements that are selected + const selectedElements = allEClassElements.filter(element => element.classList.contains('selected')); + // add 'selected' class to the current clicked item + e.currentTarget.classList.add('selected'); + // if there are no selected elements, or if there are more than one, deselect all of them, and select just the clicked one + if ((selectedElements.length === 1 && e.currentTarget !== selectedElements[0]) || selectedElements.length !== 1) { + // deselect all items + selectedElements.forEach(elem => { + if (elem !== e.currentTarget) { + elem.classList.remove('selected'); + // remove selectionStartTime from all items + delete elem.dataset.selectionStartTime; + } + }); + // set the current item as the selection start + fileSystemExplorer.dataset.selectionStart = currentIndex; + // store the current timestamp for future double-click checks + e.currentTarget.dataset.selectionStartTime = currentTime; + } + } + else // if its selection mode, just toggle selection of item, when clicked + e.currentTarget.classList.toggle('selected'); + } + const selectedElements = document.querySelectorAll('.e.selected'); + btnFileSystemBrowserConfirm.disabled = selectedElements.length === 0; // disable Confirm button if no item is selected + if (selectedElements.length > 0) { + var selectedPaths = '"'; + selectedElements.forEach((element) => { + selectedPaths += element.dataset.path + '","'; + }); + selectedFileSystemElementsInput.value = selectedPaths.substring(0, selectedPaths.length - 2); + } + else + selectedFileSystemElementsInput.value = ''; + } + + /** + * Handler for the mouse down event of file system browser dialog files and directories elements. + * @param {MouseEvent} e - The mouse event whose propagation is stopped. + */ + function handleFileSystemEntityMouseDown(e) { + // stop the event from bubbling up to the explorer - we dont want to start selection rectangles when clicking files or directories + e.stopPropagation(); + } + + //+======================================================================================+ + //| View Mode | + //+======================================================================================+ + + /** + * Switches to a different view mode. + * @param {string} mode - The view mode to switch to ('list', 'details', or 'icons'). + * @param {string|null} iconSize - The icon size for 'icons' mode ('small', 'medium', 'large', 'extra-large'). Use null for non-icon modes. + * @param {boolean} isManualSet - Indicates whether the mode change is triggered manually (by clicking a mode change icon) or automatically. + */ + function switchViewMode(mode, iconSize, isManualSet) { + hasScrolledAfterModeChange = false; // reset the flag indicating a mode change + setViewMode(mode, iconSize); + // check if content has been scrolled after the mode change; since scroll is the one triggering thumbnails retrieval, + // and there is no initial scroll when mode is changed, we need to trigger the retrieval manually + setTimeout(() => { + if (!hasScrolledAfterModeChange && showThumbnails && isManualSet) getFileSystemVisibleItems(); + }, 50); // wait 50ms to ensure all other events have processed + } + + /** + * Sets the explorer view mode. + * @param {string} mode - View mode ('list', 'details', or 'icons'). + * @param {string} [iconSize] - Icon size for 'icons' mode ('small', 'medium', 'large', 'extra-large'). + */ + function setViewMode(mode, iconSize) { + if (!fileSystemExplorer) + return; + const isIconMode = mode === 'icons'; + const viewClass = isIconMode ? 'details' : mode; + const iconClass = isIconMode ? `${iconSize}-icons` : `${mode}-icons`; + viewMode = iconClass; + fileSystemExplorer.className = `${viewClass}`; + fileSystemExplorer.style.flexDirection = mode === 'list' ? 'column' : isIconMode ? 'row' : 'column'; + + fileSystemExplorerContainer.classList.toggle('scroll-horizontal', mode === 'list'); + fileSystemExplorerContainer.classList.toggle('scroll-vertical', mode !== 'list'); + + fileSystemDetailsHeader.style.height = mode === 'details' ? '20px' : '0px'; + fileSystemDetailsHeader.style.position = mode === 'details' ? 'sticky' : 'static'; + fileSystemDetailsHeader.style.top = mode === 'details' ? '-1px' : ''; + + setEnabledViewModeIcon(isIconMode ? `${iconSize}-icons` : mode); + mode === 'list' ? addHorizontalScrolling(fileSystemExplorer) : removeHorizontalScrolling(fileSystemExplorer); + + fileSystemExplorer.querySelectorAll('.e').forEach(el => { + el.className = `e ${iconClass}`; + }); + mode === 'details' ? showExtraDetails() : hideExtraDetails(); + } + + /** + * Hides additional item details such as date modified, type, and size. + */ + function hideExtraDetails() { + fileSystemExplorer.querySelectorAll('.date-modified, .type, .size').forEach(el => { + el.style.display = 'none'; + }); + } + + /** + * Shows additional item details such as date modified, type, and size. + */ + function showExtraDetails() { + fileSystemExplorer.querySelectorAll('.date-modified, .type, .size').forEach(el => { + el.style.display = 'flex'; + }); + } + + /** + * Sets the enabled view mode icon. + * @param {string} viewType - The type of view to enable ('list', 'details', 'small-icons', 'medium-icons', 'large-icons', 'extra-large-icons'). + */ + function setEnabledViewModeIcon(viewType) { + const allViews = [ + svgListView, + svgDetailsView, + svgSmallIconsView, + svgMediumIconsView, + svgLargeIconsView, + svgExtraLargeIconsView + ]; + + allViews.forEach((view, index) => { + view.forEach(element => { + if (index === ['list', 'details', 'small-icons', 'medium-icons', 'large-icons', 'extra-large-icons'].indexOf(viewType)) + element.classList.add('enabled'); + else + element.classList.remove('enabled'); + }); + }); + } + + //+======================================================================================+ + //| Selection | + //+======================================================================================+ + + /** + * Handler for the file system browser dialog selection start. + * @param {MouseEvent} e - The mousedown event object. + */ + function startSelection(e) { + const explorerScrollbars = hasScrollbars(fileSystemExplorer); + const containerExplorerScrollbars = hasScrollbars(fileSystemExplorerContainer); + // check if clicked on the horizontal or vertical scrollbar + if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) + return; + if (containerExplorerScrollbars.vertical && e.clientX > fileSystemExplorerContainer.getBoundingClientRect().left + fileSystemExplorerContainer.offsetWidth - scrollbarWidth) + return; + // store information about selection start + isSelecting = true; + document.body.style.overflowY = 'hidden'; // needed in order to not put a vertical scrollbar on the document, while in vertical layout selection + document.documentElement.style.overflowY = 'hidden'; + selectionStartPosition.x = e.pageX + fileSystemExplorer.scrollLeft; + selectionStartPosition.y = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + fileSystemExplorerContainer.scrollTop; // not a mistake - in vertical mode, this is the overflow container! + // place the selection rectangle at the clicked location (relative to the whole page, and taking into account scroll offset), with 0 size + visibleSelectionRectangle.style.left = e.pageX + 'px'; + visibleSelectionRectangle.style.top = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + 'px'; + visibleSelectionRectangle.style.width = '0px'; + visibleSelectionRectangle.style.height = '0px'; + visibleSelectionRectangle.style.visibility = 'visible'; + + selectionRectangle.style.left = e.pageX + 'px'; + selectionRectangle.style.top = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + 'px'; + selectionRectangle.style.width = '0px'; + selectionRectangle.style.height = '0px'; + } + + /** + * Handler for the file system browser dialog selection update. + * @param {MouseEvent} e - The mousemove event object. + */ + function updateSelection(e) { + if (!isSelecting) + return; + currentMousePosition.x = e.pageX; + currentMousePosition.y = e.pageY - parseInt(window.getComputedStyle(menubar).height); + handleSelection(); + } + + /** + * Handler for the file system browser dialog selection end. + */ + function endSelection() { + // selection ended, hide the selection rectangle + isSelecting = false; + document.body.style.removeProperty('overflow-y'); + document.documentElement.style.removeProperty('overflow-y'); + + visibleSelectionRectangle.style.visibility = 'hidden'; + selectionRectangle.style.visibility = 'hidden'; + + selectionRectangle.style.left = '0px'; + selectionRectangle.style.top = '0px'; + selectionRectangle.style.width = '0px'; + selectionRectangle.style.height = '0px'; + visibleSelectionRectangle.style.left = '0px'; + visibleSelectionRectangle.style.top = '0px'; + visibleSelectionRectangle.style.width = '0px'; + visibleSelectionRectangle.style.height = '0px'; + // go through each .e item that was inside the selection rectangle, and mark it as selected + fileSystemExplorer.querySelectorAll('.e.selection-hover').forEach(item => { + item.classList.add('selected'); + item.classList.remove('selection-hover'); + }); + const selectedElements = document.querySelectorAll('.e.selected'); + btnFileSystemBrowserConfirm.disabled = selectedElements.length === 0; // disable Confirm button if no item is selected + if (selectedElements.length > 0) { + var selectedPaths = '"'; + selectedElements.forEach((element) => { + selectedPaths += element.dataset.path + '","'; + }); + selectedFileSystemElementsInput.value = selectedPaths.substring(0, selectedPaths.length - 2); + } + else + selectedFileSystemElementsInput.value = ''; + } + + /** + * Function for handling the file system browser dialog selection. + */ + function handleSelection() { + if (!isSelecting) // only relevant when we have a selection initialized + return; + // calculate dimensions of the selection rectangle + const currentX = currentMousePosition.x; + const currentY = currentMousePosition.y; + const width = currentX - (selectionStartPosition.x - fileSystemExplorer.scrollLeft); + const height = currentY - (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop); + + // update selection rectangle dimensions + visibleSelectionRectangle.style.width = Math.abs(width) + 'px'; + visibleSelectionRectangle.style.height = Math.abs(height) + 'px'; + selectionRectangle.style.width = Math.abs(width) + 'px'; + selectionRectangle.style.height = Math.abs(height) + 'px'; + + // adjust position based on selection direction + if (width < 0) { + selectionRectangle.style.left = currentX + 'px'; + visibleSelectionRectangle.style.left = currentX + 'px'; + } else { + selectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; + visibleSelectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; + } + if (height < 0) { + selectionRectangle.style.top = currentY + 'px'; + visibleSelectionRectangle.style.top = currentY + 'px'; + } else { + selectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; + visibleSelectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; + } + + // do not let the selection rectangle go outside of explorer container, clip it if needed + const containerRect = fileSystemExplorerContainer.getBoundingClientRect(); + const left = parseFloat(visibleSelectionRectangle.style.left); + const top = parseFloat(visibleSelectionRectangle.style.top) + 1; + const right = left + parseFloat(visibleSelectionRectangle.style.width); + const bottom = top + parseFloat(visibleSelectionRectangle.style.height); + + if (left < containerRect.left) { + const difference = containerRect.left - left; + visibleSelectionRectangle.style.width = (parseFloat(visibleSelectionRectangle.style.width) - difference) + 'px'; + visibleSelectionRectangle.style.left = containerRect.left + 'px'; + } + if (right > containerRect.right) + visibleSelectionRectangle.style.width = (containerRect.right - left) + 'px'; + + if (top < containerRect.top - parseInt(window.getComputedStyle(menubar).height)) { + const difference = containerRect.top - top - parseInt(window.getComputedStyle(menubar).height); + visibleSelectionRectangle.style.height = (parseFloat(visibleSelectionRectangle.style.height) - difference) + 'px'; + visibleSelectionRectangle.style.top = (containerRect.top - parseInt(window.getComputedStyle(menubar).height)) + 'px'; + } + if (bottom > containerRect.bottom) + visibleSelectionRectangle.style.height = (containerRect.bottom - top) + 'px'; + + // change color of items that fall within selection rectangle + const selectionRect = selectionRectangle.getBoundingClientRect(); + // go through each .e item which has not had its thumbnail retrieved yet + fileSystemExplorer.querySelectorAll('.e').forEach(item => { + const itemRect = item.getBoundingClientRect(); + // check if the item is fully or partially visible horizontally and vertically + const isFullyVisibleHorizontally = itemRect.left >= selectionRect.left && itemRect.right <= selectionRect.right; + const isFullyVisibleVertically = itemRect.top >= selectionRect.top && itemRect.bottom <= selectionRect.bottom; + const isPartiallyVisibleHorizontally = itemRect.left < selectionRect.right && itemRect.right > selectionRect.left; + const isPartiallyVisibleVertically = itemRect.top < selectionRect.bottom && itemRect.bottom > selectionRect.top; + // if the item is fully or partially visible in both directions, add it to our list + if ((isFullyVisibleHorizontally || isPartiallyVisibleHorizontally) && (isFullyVisibleVertically || isPartiallyVisibleVertically)) + item.classList.add('selection-hover'); + else + item.classList.remove('selection-hover'); + }); + } + + /** + * Enables or disables the display of the file system tree view. + * @param {MouseEvent} e - The mouseup event object. + */ + function toggleFileSystemSelectionMode(e) { + isSelectionMode = !isSelectionMode; + e.preventDefault(); + e.stopPropagation(); + + svgSelectionMode.forEach(element => { + isSelectionMode ? element.classList.add('enabled') : element.classList.remove('enabled'); + }); + } + + /** + * Handler for the mouse up event of the file system browser dialog explorer + * @param {MouseEvent} e - The mouseup event object. + */ + function handleFileSystemExplorerMouseUp(e) { + const explorerScrollbars = hasScrollbars(fileSystemExplorer); + // check if clicked on the horizontal scrollbar + if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) + return; + if (!e.ctrlKey && !e.shiftKey && !isSelectionMode) { + // deselect all file system elements when their explorer is clicked + fileSystemExplorer.querySelectorAll('.e.selected').forEach(item => { + item.classList.remove('selected'); + }); + // do not store information about what item was clicked first, in context of Shift-selection + fileSystemExplorer.removeAttribute('data-selection-start'); + btnFileSystemBrowserConfirm.disabled = document.querySelectorAll('.e.selected').length === 0; // disable Confirm button if no item is selected + } + } + + /** + * Handles the scroll event for the explorer or explorerContainer. + * Clears any previous timeout and creates a new one to fetch visible items. + */ + function handleFileSystemBrowserScrollEvent() { + // clear any previously set timeouts to debounce the getFileSystemVisibleItems call + if (scrollTimeout) clearTimeout(scrollTimeout); + // if there's an ongoing operation, abort it + if (abortController) { + abortController.abort(); + abortController = null; + } + // set a timeout to call getFileSystemVisibleItems once the user stops scrolling + scrollTimeout = setTimeout(() => { + if (showThumbnails) + getFileSystemVisibleItems(); + }, scrollThumbnailRetrievalTimeout); + hasScrolledAfterModeChange = true; + } + + /** + * Handles the window's resize event. + * Clears any previous timeout and creates a new one to fetch file system browser visible items. + */ + function handleFileSystemBrowserResizeEvent() { + // clear any previously set timeouts to debounce the getFileSystemVisibleItems call during resize + if (resizeTimeout) clearTimeout(resizeTimeout); + // if there's an ongoing operation, abort it + if (abortController) { + abortController.abort(); + abortController = null; + } + // set a timeout to call getFileSystemVisibleItems once the user stops resizing + resizeTimeout = setTimeout(() => { + if (showThumbnails) + getFileSystemVisibleItems(); + }, scrollThumbnailRetrievalTimeout); + } + + //+======================================================================================+ + //| Thumbnails | + //+======================================================================================+ + + /** + * Identifies items within the explorerContainer that are either fully or partially visible. + * Items with thumbnails already retrieved are excluded. + * Populates a list of such visible items and passes them for further processing. + */ + function getFileSystemVisibleItems() { + const containerRect = fileSystemExplorerContainer.getBoundingClientRect(); + const visibleItems = []; + // go through each .e item which has not had its thumbnail retrieved yet + const fileElements = Array.from(fileSystemExplorer.querySelectorAll('.e:not([data-thumbnail-retrieved])[data-type="File"]')); + // if the option for checking file header bytes is disabled, filter images by extension + const itemsToProcess = inspectFileForThumbnails ? fileElements : fileElements.filter(item => isImageFile(item.getAttribute('data-path'))); + itemsToProcess.forEach(item => { + const itemPath = item.getAttribute('data-path'); + const itemRect = item.getBoundingClientRect(); + // check if the item is fully or partially visible horizontally and vertically + const isFullyVisibleHorizontally = itemRect.left >= containerRect.left && itemRect.right <= containerRect.right; + const isFullyVisibleVertically = itemRect.top >= containerRect.top && itemRect.bottom <= containerRect.bottom; + const isPartiallyVisibleHorizontally = itemRect.left < containerRect.right && itemRect.right > containerRect.left; + const isPartiallyVisibleVertically = itemRect.top < containerRect.bottom && itemRect.bottom > containerRect.top; + // if the item is fully or partially visible in both directions, add it to our list + if ((isFullyVisibleHorizontally || isPartiallyVisibleHorizontally) && + (isFullyVisibleVertically || isPartiallyVisibleVertically)) { + const imgElement = item.querySelector('img'); + visibleItems.push({ + path: itemPath, + img: imgElement + }); + } + }); + // process the list of visible items + processVisibleItems(visibleItems); + } + + /** + * Processes a given item by retrieving its thumbnail from an API and updating the item's thumbnail image. + * If there are more items in the visibleItems list, it continues to process the next item. + * If an error occurs during the retrieval process (including an aborted fetch operation), it is handled gracefully. + * @param {Object} item - The item containing its path and corresponding image element. + * @param {Array} visibleItems - List of remaining visible items to process. + * @throws {AbortError} - Indicates the fetch operation was aborted. + * @throws {Error} - Catches and logs other errors that might occur during the thumbnail retrieval. + */ + async function processItem(item, visibleItems) { + try { + const result = await getThumbnailApiCall(item.path, imagePreviewsQuality); + // update the item's thumbnail using the retrieved data + if (typeof result.base64Data !== "undefined") + item.img.src = `data:${result.mimeType};base64,${result.base64Data}`; + item.img.closest('.e').setAttribute('data-thumbnail-retrieved', 'true'); + // continue with next item if there are more in the queue + if (visibleItems.length > 0) { + const nextItem = visibleItems.shift(); + processItem(nextItem, visibleItems); + } + } catch (error) { + if (error.name === 'AbortError') { + // console.log('Fetch operation was aborted.'); + } else { + // on error, revert the icons to the default ones + let itemType = item.img.closest('.e').getAttribute('data-type'); + if (itemType === 'directory') + item.img.src = clientBasePath + "images/icons/" + CURRENT_ICON_THEME + "/directory.svg"; + else if (itemType === 'file') + item.img.src = clientBasePath + "images/icons/" + CURRENT_ICON_THEME + "/file.svg"; + console.error('Error processing item:', error); } } - else // if its selection mode, just toggle selection of item, when clicked - e.currentTarget.classList.toggle('selected'); } - const selectedElements = document.querySelectorAll('.e.selected'); - btnFileSystemBrowserConfirm.disabled = selectedElements.length === 0; // disable Confirm button if no item is selected - if (selectedElements.length > 0) { - var selectedPaths = '"'; - selectedElements.forEach((element) => { - selectedPaths += element.dataset.path + '","'; + + /** + * Makes an API call to retrieve a thumbnail for the given item. + * @param {string} path - The path of the item for which the thumbnail needs to be fetched. + * @returns {Promise} - Returns a Promise resolving to an object containing base64Data and mimeType. + * @throws {Error} - Throws an error if the API call fails. + */ + async function getThumbnailApiCall(path, quality) { + // fetch the thumbnail for the given item from the server + const response = await fetch(`${serverBasePath}thumbnails/get-thumbnail?path=` + encodeURIComponent(path) + '&quality=' + quality, { + signal: abortController.signal // use the abort signal }); - selectedFileSystemElementsInput.value = selectedPaths.substring(0, selectedPaths.length - 2); - } - else - selectedFileSystemElementsInput.value = ''; -} - -/** - * Handler for the mouse down event of file system browser dialog files and directories elements. - * @param {MouseEvent} e - The mouse event whose propagation is stopped. - */ -function handleFileSystemEntityMouseDown(e) { - // stop the event from bubbling up to the explorer - we dont want to start selection rectangles when clicking files or directories - e.stopPropagation(); -} - -//+======================================================================================+ -//| View Mode | -//+======================================================================================+ - -/** - * Switches to a different view mode. - * @param {string} mode - The view mode to switch to ('list', 'details', or 'icons'). - * @param {string|null} iconSize - The icon size for 'icons' mode ('small', 'medium', 'large', 'extra-large'). Use null for non-icon modes. - * @param {boolean} isManualSet - Indicates whether the mode change is triggered manually (by clicking a mode change icon) or automatically. - */ -function switchViewMode(mode, iconSize, isManualSet) { - hasScrolledAfterModeChange = false; // reset the flag indicating a mode change - setViewMode(mode, iconSize); - // check if content has been scrolled after the mode change; since scroll is the one triggering thumbnails retrieval, - // and there is no initial scroll when mode is changed, we need to trigger the retrieval manually - setTimeout(() => { - if (!hasScrolledAfterModeChange && showThumbnails && isManualSet) getFileSystemVisibleItems(); - }, 50); // wait 50ms to ensure all other events have processed -} - -/** - * Sets the explorer view mode. - * @param {string} mode - View mode ('list', 'details', or 'icons'). - * @param {string} [iconSize] - Icon size for 'icons' mode ('small', 'medium', 'large', 'extra-large'). - */ -function setViewMode(mode, iconSize) { - if (!fileSystemExplorer) - return; - const isIconMode = mode === 'icons'; - const viewClass = isIconMode ? 'details' : mode; - const iconClass = isIconMode ? `${iconSize}-icons` : `${mode}-icons`; - viewMode = iconClass; - fileSystemExplorer.className = `${viewClass}`; - fileSystemExplorer.style.flexDirection = mode === 'list' ? 'column' : isIconMode ? 'row' : 'column'; - - fileSystemExplorerContainer.classList.toggle('scroll-horizontal', mode === 'list'); - fileSystemExplorerContainer.classList.toggle('scroll-vertical', mode !== 'list'); - - fileSystemDetailsHeader.style.height = mode === 'details' ? '20px' : '0px'; - fileSystemDetailsHeader.style.position = mode === 'details' ? 'sticky' : 'static'; - fileSystemDetailsHeader.style.top = mode === 'details' ? '-1px' : ''; - - setEnabledViewModeIcon(isIconMode ? `${iconSize}-icons` : mode); - mode === 'list' ? addHorizontalScrolling(fileSystemExplorer) : removeHorizontalScrolling(fileSystemExplorer); - - fileSystemExplorer.querySelectorAll('.e').forEach(el => { - el.className = `e ${iconClass}`; - }); - mode === 'details' ? showExtraDetails() : hideExtraDetails(); -} - -/** - * Hides additional item details such as date modified, type, and size. - */ -function hideExtraDetails() { - fileSystemExplorer.querySelectorAll('.date-modified, .type, .size').forEach(el => { - el.style.display = 'none'; - }); -} - -/** - * Shows additional item details such as date modified, type, and size. - */ -function showExtraDetails() { - fileSystemExplorer.querySelectorAll('.date-modified, .type, .size').forEach(el => { - el.style.display = 'flex'; - }); -} - -/** - * Sets the enabled view mode icon. - * @param {string} viewType - The type of view to enable ('list', 'details', 'small-icons', 'medium-icons', 'large-icons', 'extra-large-icons'). - */ -function setEnabledViewModeIcon(viewType) { - const allViews = [ - svgListView, - svgDetailsView, - svgSmallIconsView, - svgMediumIconsView, - svgLargeIconsView, - svgExtraLargeIconsView - ]; - - allViews.forEach((view, index) => { - view.forEach(element => { - if (index === ['list', 'details', 'small-icons', 'medium-icons', 'large-icons', 'extra-large-icons'].indexOf(viewType)) - element.classList.add('enabled'); - else - element.classList.remove('enabled'); - }); - }); -} - -//+======================================================================================+ -//| Selection | -//+======================================================================================+ - -/** - * Handler for the file system browser dialog selection start. - * @param {MouseEvent} e - The mousedown event object. - */ -function startSelection(e) { - const explorerScrollbars = hasScrollbars(fileSystemExplorer); - const containerExplorerScrollbars = hasScrollbars(fileSystemExplorerContainer); - // check if clicked on the horizontal or vertical scrollbar - if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) - return; - if (containerExplorerScrollbars.vertical && e.clientX > fileSystemExplorerContainer.getBoundingClientRect().left + fileSystemExplorerContainer.offsetWidth - scrollbarWidth) - return; - // store information about selection start - isSelecting = true; - document.body.style.overflowY = 'hidden'; // needed in order to not put a vertical scrollbar on the document, while in vertical layout selection - document.documentElement.style.overflowY = 'hidden'; - selectionStartPosition.x = e.pageX + fileSystemExplorer.scrollLeft; - selectionStartPosition.y = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + fileSystemExplorerContainer.scrollTop; // not a mistake - in vertical mode, this is the overflow container! - // place the selection rectangle at the clicked location (relative to the whole page, and taking into account scroll offset), with 0 size - visibleSelectionRectangle.style.left = e.pageX + 'px'; - visibleSelectionRectangle.style.top = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + 'px'; - visibleSelectionRectangle.style.width = '0px'; - visibleSelectionRectangle.style.height = '0px'; - visibleSelectionRectangle.style.visibility = 'visible'; - - selectionRectangle.style.left = e.pageX + 'px'; - selectionRectangle.style.top = (e.pageY - parseInt(window.getComputedStyle(menubar).height)) + 'px'; - selectionRectangle.style.width = '0px'; - selectionRectangle.style.height = '0px'; -} - -/** - * Handler for the file system browser dialog selection update. - * @param {MouseEvent} e - The mousemove event object. - */ -function updateSelection(e) { - if (!isSelecting) - return; - currentMousePosition.x = e.pageX; - currentMousePosition.y = e.pageY - parseInt(window.getComputedStyle(menubar).height); - handleSelection(); -} - -/** - * Handler for the file system browser dialog selection end. - */ -function endSelection() { - // selection ended, hide the selection rectangle - isSelecting = false; - document.body.style.removeProperty('overflow-y'); - document.documentElement.style.removeProperty('overflow-y'); - - visibleSelectionRectangle.style.visibility = 'hidden'; - selectionRectangle.style.visibility = 'hidden'; - - selectionRectangle.style.left = '0px'; - selectionRectangle.style.top = '0px'; - selectionRectangle.style.width = '0px'; - selectionRectangle.style.height = '0px'; - visibleSelectionRectangle.style.left = '0px'; - visibleSelectionRectangle.style.top = '0px'; - visibleSelectionRectangle.style.width = '0px'; - visibleSelectionRectangle.style.height = '0px'; - // go through each .e item that was inside the selection rectangle, and mark it as selected - fileSystemExplorer.querySelectorAll('.e.selection-hover').forEach(item => { - item.classList.add('selected'); - item.classList.remove('selection-hover'); - }); - const selectedElements = document.querySelectorAll('.e.selected'); - btnFileSystemBrowserConfirm.disabled = selectedElements.length === 0; // disable Confirm button if no item is selected - if (selectedElements.length > 0) { - var selectedPaths = '"'; - selectedElements.forEach((element) => { - selectedPaths += element.dataset.path + '","'; - }); - selectedFileSystemElementsInput.value = selectedPaths.substring(0, selectedPaths.length - 2); - } - else - selectedFileSystemElementsInput.value = ''; -} - -/** - * Function for handling the file system browser dialog selection. - */ -function handleSelection() { - if (!isSelecting) // only relevant when we have a selection initialized - return; - // calculate dimensions of the selection rectangle - const currentX = currentMousePosition.x; - const currentY = currentMousePosition.y; - const width = currentX - (selectionStartPosition.x - fileSystemExplorer.scrollLeft); - const height = currentY - (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop); - - // update selection rectangle dimensions - visibleSelectionRectangle.style.width = Math.abs(width) + 'px'; - visibleSelectionRectangle.style.height = Math.abs(height) + 'px'; - selectionRectangle.style.width = Math.abs(width) + 'px'; - selectionRectangle.style.height = Math.abs(height) + 'px'; - - // adjust position based on selection direction - if (width < 0) { - selectionRectangle.style.left = currentX + 'px'; - visibleSelectionRectangle.style.left = currentX + 'px'; - } else { - selectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; - visibleSelectionRectangle.style.left = (selectionStartPosition.x - fileSystemExplorer.scrollLeft) + 'px'; - } - if (height < 0) { - selectionRectangle.style.top = currentY + 'px'; - visibleSelectionRectangle.style.top = currentY + 'px'; - } else { - selectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; - visibleSelectionRectangle.style.top = (selectionStartPosition.y - fileSystemExplorerContainer.scrollTop) + 'px'; + if (!response.ok) + throw new Error('Failed to fetch the thumbnail'); + // convert the response to a JSON object + const blob = await response.blob(); + const base64Data = await blobToBase64Async(blob); + const mimeType = response.headers.get('Content-Type'); + return { + base64Data: base64Data, + mimeType: mimeType + }; } - // do not let the selection rectangle go outside of explorer container, clip it if needed - const containerRect = fileSystemExplorerContainer.getBoundingClientRect(); - const left = parseFloat(visibleSelectionRectangle.style.left); - const top = parseFloat(visibleSelectionRectangle.style.top) + 1; - const right = left + parseFloat(visibleSelectionRectangle.style.width); - const bottom = top + parseFloat(visibleSelectionRectangle.style.height); - - if (left < containerRect.left) { - const difference = containerRect.left - left; - visibleSelectionRectangle.style.width = (parseFloat(visibleSelectionRectangle.style.width) - difference) + 'px'; - visibleSelectionRectangle.style.left = containerRect.left + 'px'; - } - if (right > containerRect.right) - visibleSelectionRectangle.style.width = (containerRect.right - left) + 'px'; - - if (top < containerRect.top - parseInt(window.getComputedStyle(menubar).height)) { - const difference = containerRect.top - top - parseInt(window.getComputedStyle(menubar).height); - visibleSelectionRectangle.style.height = (parseFloat(visibleSelectionRectangle.style.height) - difference) + 'px'; - visibleSelectionRectangle.style.top = (containerRect.top - parseInt(window.getComputedStyle(menubar).height)) + 'px'; - } - if (bottom > containerRect.bottom) - visibleSelectionRectangle.style.height = (containerRect.bottom - top) + 'px'; - - // change color of items that fall within selection rectangle - const selectionRect = selectionRectangle.getBoundingClientRect(); - // go through each .e item which has not had its thumbnail retrieved yet - fileSystemExplorer.querySelectorAll('.e').forEach(item => { - const itemRect = item.getBoundingClientRect(); - // check if the item is fully or partially visible horizontally and vertically - const isFullyVisibleHorizontally = itemRect.left >= selectionRect.left && itemRect.right <= selectionRect.right; - const isFullyVisibleVertically = itemRect.top >= selectionRect.top && itemRect.bottom <= selectionRect.bottom; - const isPartiallyVisibleHorizontally = itemRect.left < selectionRect.right && itemRect.right > selectionRect.left; - const isPartiallyVisibleVertically = itemRect.top < selectionRect.bottom && itemRect.bottom > selectionRect.top; - // if the item is fully or partially visible in both directions, add it to our list - if ((isFullyVisibleHorizontally || isPartiallyVisibleHorizontally) && (isFullyVisibleVertically || isPartiallyVisibleVertically)) - item.classList.add('selection-hover'); - else - item.classList.remove('selection-hover'); - }); -} - -/** - * Enables or disables the display of the file system tree view. - * @param {MouseEvent} e - The mouseup event object. - */ -function toggleFileSystemSelectionMode(e) { - isSelectionMode = !isSelectionMode; - e.preventDefault(); - e.stopPropagation(); - - svgSelectionMode.forEach(element => { - isSelectionMode ? element.classList.add('enabled') : element.classList.remove('enabled'); - }); -} - -/** - * Handler for the mouse up event of the file system browser dialog explorer - * @param {MouseEvent} e - The mouseup event object. - */ -function handleFileSystemExplorerMouseUp(e) { - const explorerScrollbars = hasScrollbars(fileSystemExplorer); - // check if clicked on the horizontal scrollbar - if (explorerScrollbars.horizontal && e.clientY > fileSystemExplorer.getBoundingClientRect().top + fileSystemExplorer.offsetHeight - scrollbarHeight) - return; - if (!e.ctrlKey && !e.shiftKey && !isSelectionMode) { - // deselect all file system elements when their explorer is clicked - fileSystemExplorer.querySelectorAll('.e.selected').forEach(item => { - item.classList.remove('selected'); - }); - // do not store information about what item was clicked first, in context of Shift-selection - fileSystemExplorer.removeAttribute('data-selection-start'); - btnFileSystemBrowserConfirm.disabled = document.querySelectorAll('.e.selected').length === 0; // disable Confirm button if no item is selected - } -} - -/** - * Handles the scroll event for the explorer or explorerContainer. - * Clears any previous timeout and creates a new one to fetch visible items. - */ -function handleFileSystemBrowserScrollEvent() { - // clear any previously set timeouts to debounce the getFileSystemVisibleItems call - if (scrollTimeout) clearTimeout(scrollTimeout); - // if there's an ongoing operation, abort it - if (abortController) { - abortController.abort(); - abortController = null; - } - // set a timeout to call getFileSystemVisibleItems once the user stops scrolling - scrollTimeout = setTimeout(() => { - if (showThumbnails) - getFileSystemVisibleItems(); - }, scrollThumbnailRetrievalTimeout); - hasScrolledAfterModeChange = true; -} - -/** - * Handles the window's resize event. - * Clears any previous timeout and creates a new one to fetch file system browser visible items. - */ -function handleFileSystemBrowserResizeEvent() { - // clear any previously set timeouts to debounce the getFileSystemVisibleItems call during resize - if (resizeTimeout) clearTimeout(resizeTimeout); - // if there's an ongoing operation, abort it - if (abortController) { - abortController.abort(); - abortController = null; - } - // set a timeout to call getFileSystemVisibleItems once the user stops resizing - resizeTimeout = setTimeout(() => { - if (showThumbnails) - getFileSystemVisibleItems(); - }, scrollThumbnailRetrievalTimeout); -} - -//+======================================================================================+ -//| Thumbnails | -//+======================================================================================+ - -/** - * Identifies items within the explorerContainer that are either fully or partially visible. - * Items with thumbnails already retrieved are excluded. - * Populates a list of such visible items and passes them for further processing. - */ -function getFileSystemVisibleItems() { - const containerRect = fileSystemExplorerContainer.getBoundingClientRect(); - const visibleItems = []; - // go through each .e item which has not had its thumbnail retrieved yet - const fileElements = Array.from(fileSystemExplorer.querySelectorAll('.e:not([data-thumbnail-retrieved])[data-type="File"]')); - // if the option for checking file header bytes is disabled, filter images by extension - const itemsToProcess = inspectFileForThumbnails ? fileElements : fileElements.filter(item => isImageFile(item.getAttribute('data-path'))); - itemsToProcess.forEach(item => { - const itemPath = item.getAttribute('data-path'); - const itemRect = item.getBoundingClientRect(); - // check if the item is fully or partially visible horizontally and vertically - const isFullyVisibleHorizontally = itemRect.left >= containerRect.left && itemRect.right <= containerRect.right; - const isFullyVisibleVertically = itemRect.top >= containerRect.top && itemRect.bottom <= containerRect.bottom; - const isPartiallyVisibleHorizontally = itemRect.left < containerRect.right && itemRect.right > containerRect.left; - const isPartiallyVisibleVertically = itemRect.top < containerRect.bottom && itemRect.bottom > containerRect.top; - // if the item is fully or partially visible in both directions, add it to our list - if ((isFullyVisibleHorizontally || isPartiallyVisibleHorizontally) && - (isFullyVisibleVertically || isPartiallyVisibleVertically)) { - const imgElement = item.querySelector('img'); - visibleItems.push({ - path: itemPath, - img: imgElement - }); - } - }); - // process the list of visible items - processVisibleItems(visibleItems); -} - -/** - * Processes a given item by retrieving its thumbnail from an API and updating the item's thumbnail image. - * If there are more items in the visibleItems list, it continues to process the next item. - * If an error occurs during the retrieval process (including an aborted fetch operation), it is handled gracefully. - * @param {Object} item - The item containing its path and corresponding image element. - * @param {Array} visibleItems - List of remaining visible items to process. - * @throws {AbortError} - Indicates the fetch operation was aborted. - * @throws {Error} - Catches and logs other errors that might occur during the thumbnail retrieval. - */ -async function processItem(item, visibleItems) { - try { - const result = await getThumbnailApiCall(item.path, imagePreviewsQuality); - // update the item's thumbnail using the retrieved data - if (typeof result.base64Data !== "undefined") - item.img.src = `data:${result.mimeType};base64,${result.base64Data}`; - item.img.closest('.e').setAttribute('data-thumbnail-retrieved', 'true'); - // continue with next item if there are more in the queue - if (visibleItems.length > 0) { - const nextItem = visibleItems.shift(); - processItem(nextItem, visibleItems); - } - } catch (error) { - if (error.name === 'AbortError') { - // console.log('Fetch operation was aborted.'); - } else { - // on error, revert the icons to the default ones - let itemType = item.img.closest('.e').getAttribute('data-type'); - if (itemType === 'directory') - item.img.src = clientBasePath + "images/icons/" + CURRENT_ICON_THEME + "/directory.svg"; - else if (itemType === 'file') - item.img.src = clientBasePath + "images/icons/" + CURRENT_ICON_THEME + "/file.svg"; - console.error('Error processing item:', error); + /** + * Initiates the processing of visible items. Processing is batched based on thumbnailsRetrievalBatchSize. * + * @param {Array} visibleItemsList - List of visible items to be processed. + */ + async function processVisibleItems(visibleItemsList) { + const visibleItems = [...visibleItemsList]; + abortController = new AbortController(); // create a new AbortController + // process items in batches determined by thumbnailsRetrievalBatchSize + for (let i = 0; i < Math.min(thumbnailsRetrievalBatchSize, visibleItems.length); i++) { + const item = visibleItems.shift(); + processItem(item, visibleItems); } } -} -/** - * Makes an API call to retrieve a thumbnail for the given item. - * @param {string} path - The path of the item for which the thumbnail needs to be fetched. - * @returns {Promise} - Returns a Promise resolving to an object containing base64Data and mimeType. - * @throws {Error} - Throws an error if the API call fails. - */ -async function getThumbnailApiCall(path, quality) { - // fetch the thumbnail for the given item from the server - const response = await fetch(`${serverBasePath}thumbnails/get-thumbnail?path=` + encodeURIComponent(path) + '&quality=' + quality, { - signal: abortController.signal // use the abort signal - }); - if (!response.ok) - throw new Error('Failed to fetch the thumbnail'); - // convert the response to a JSON object - const blob = await response.blob(); - const base64Data = await blobToBase64(blob); - const mimeType = response.headers.get('Content-Type'); - return { - base64Data: base64Data, - mimeType: mimeType - }; -} -/** - * Initiates the processing of visible items. Processing is batched based on thumbnailsRetrievalBatchSize. * - * @param {Array} visibleItemsList - List of visible items to be processed. - */ -async function processVisibleItems(visibleItemsList) { - const visibleItems = [...visibleItemsList]; - abortController = new AbortController(); // create a new AbortController - // process items in batches determined by thumbnailsRetrievalBatchSize - for (let i = 0; i < Math.min(thumbnailsRetrievalBatchSize, visibleItems.length); i++) { - const item = visibleItems.shift(); - processItem(item, visibleItems); + /** + * Returns the path to an SVG icon based on the file extension. + * @param {string} filename - The full name of the file including its extension. + * @returns {string} - The path to the appropriate SVG icon or a default one if not found. + */ + function getIconPathForFile(filename, type) { + // extract file extension from filename + const fileExtension = filename.split('.').pop().toLowerCase(); + // return the appropriate SVG image path or a default one if not found + return FILE_ICONS[fileExtension] || (type === "File" ? "file.svg" : "directory.svg"); } -} + + //+======================================================================================+ + //| Miscellaneous | + //+======================================================================================+ + + /** + * Enables or disables the display of the file system tree view. + * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. + */ + async function toggleFileSystemTreeViewAsync(isManualSet) { + if (isManualSet) + showFileSystemTreeView = !showFileSystemTreeView; + + showFileSystemTreeView ? fileSystemTreeViewContainer.classList.remove('collapsed') : fileSystemTreeViewContainer.classList.add('collapsed'); + svgTreeView.forEach(element => { + showFileSystemTreeView ? element.classList.add('enabled') : element.classList.remove('enabled'); + }); + showFileSystemTreeView ? fileSystemTreeViewContainer.classList.remove('collapsed') : fileSystemTreeViewContainer.classList.add('collapsed'); + // if file system treeview needs to be displayed, get its file system tree structure from the API + if (showFileSystemTreeView && isManualSet && addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + await navigateToPathAsync(addressBarInput.value, false, false); + } + } + + /** + * Enables or disables the display of hidden file system elements. + * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. + */ + async function toggleShowFileSystemHiddenElementsAsync(isManualSet) { + if (isManualSet) + showHiddenElements = !showHiddenElements; + + svgHiddenElements.forEach(element => { + showHiddenElements ? element.classList.add('enabled') : element.classList.remove('enabled'); + }); + if (isManualSet && addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + await navigateToPathAsync(addressBarInput.value, false, false); + } + } + + /** + * Enables or disables the display of file system elements thumbnails. + * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. + */ + async function toggleShowFileSystemElementsThumbnailsAsync(isManualSet) { + if (isManualSet) + showThumbnails = !showThumbnails; + + svgThumbnails.forEach(element => { + showThumbnails ? element.classList.add('enabled') : element.classList.remove('enabled'); + }); + if (isManualSet && addressBarInput.value !== null) { + if (!addressBarInput.value.endsWith(pathSeparator)) + addressBarInput.value += pathSeparator; + await navigateToPathAsync(addressBarInput.value, false, false); + } + } + + /** + * Gets the icon of the node, based on it type. + * @param {any} node The node for which to get the icon. + * @returns The icon on the node. + */ + function getNodeIcon(node) { + switch (node.itemType) { + case "Root": + return "💿"; + case "Directory": + return node.isExpanded ? "📂" : "📁"; + case "File": + return "📄"; + default: + return "❓"; + } + } + + //+======================================================================================+ + //| Event Handlers | + //+======================================================================================+ + + // event handlers for changing file system view modes + btnListView.addEventListener('click', () => switchViewMode('list', null, true)); + btnDetailsView.addEventListener('click', () => switchViewMode('details', null, true)); + btnSmallIconsView.addEventListener('click', () => switchViewMode('icons', 'small', true)); + btnMediumIconsView.addEventListener('click', () => switchViewMode('icons', 'medium', true)); + btnLargeIconsView.addEventListener('click', () => switchViewMode('icons', 'large', true)); + btnExtraLargeIconsView.addEventListener('click', () => switchViewMode('icons', 'extra-large', true)); + + btnNavigatorToggleTreeView.addEventListener('click', async () => await toggleFileSystemTreeViewAsync(true)); + btnNavigatorToggleThumbnails.addEventListener('click', async () => await toggleShowFileSystemElementsThumbnailsAsync(true)); + btnNavigatorToggleSelectionMode.addEventListener('click', toggleFileSystemSelectionMode); + btnNavigatorHiddenElements.addEventListener('click', async () => await toggleShowFileSystemHiddenElementsAsync(true)); + btnNavigatorNavigateUp.addEventListener('click', navigateUpAsync); + + fileSystemExplorer.addEventListener('mouseup', handleFileSystemExplorerMouseUp); + fileSystemExplorer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); + fileSystemExplorerContainer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); + + fileSystemExplorerContainer.addEventListener('mousedown', startSelection); + fileSystemExplorerContainer.addEventListener('mousemove', updateSelection); + fileSystemExplorerContainer.addEventListener('mouseup', endSelection); + fileSystemExplorerContainer.addEventListener('wheel', handleSelection, { passive: true }); + fileSystemExplorerContainer.addEventListener('scroll', handleSelection); -/** - * Returns the path to an SVG icon based on the file extension. - * @param {string} filename - The full name of the file including its extension. - * @returns {string} - The path to the appropriate SVG icon or a default one if not found. - */ -function getIconPathForFile(filename, type) { - // extract file extension from filename - const fileExtension = filename.split('.').pop().toLowerCase(); - // return the appropriate SVG image path or a default one if not found - return FILE_ICONS[fileExtension] || (type === "File" ? "file.svg" : "directory.svg"); -} - -//+======================================================================================+ -//| Miscellaneous | -//+======================================================================================+ - -/** - * Enables or disables the display of the file system tree view. - * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. - */ -async function toggleFileSystemTreeViewAsync(isManualSet) { - if (isManualSet) - showFileSystemTreeView = !showFileSystemTreeView; - - showFileSystemTreeView ? fileSystemTreeViewContainer.classList.remove('collapsed') : fileSystemTreeViewContainer.classList.add('collapsed'); - svgTreeView.forEach(element => { - showFileSystemTreeView ? element.classList.add('enabled') : element.classList.remove('enabled'); - }); - showFileSystemTreeView ? fileSystemTreeViewContainer.classList.remove('collapsed') : fileSystemTreeViewContainer.classList.add('collapsed'); - // if file system treeview needs to be displayed, get its file system tree structure from the API - if (showFileSystemTreeView && isManualSet && addressBarInput.value !== null) { - if (!addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; + /** + * Event handler for the address bar input navigate button Click event. + */ + btnFileSystemBrowserSubmitPath.addEventListener('click', async function () { await navigateToPathAsync(addressBarInput.value, false, false); - } -} - -/** - * Enables or disables the display of hidden file system elements. - * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. - */ -async function toggleShowFileSystemHiddenElementsAsync(isManualSet) { - if (isManualSet) - showHiddenElements = !showHiddenElements; - - svgHiddenElements.forEach(element => { - showHiddenElements ? element.classList.add('enabled') : element.classList.remove('enabled'); - }); - if (isManualSet && addressBarInput.value !== null) { - if (!addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; - await navigateToPathAsync(addressBarInput.value, false, false); - } -} - -/** - * Enables or disables the display of file system elements thumbnails. - * @param {boolean} isManualSet - Indicates whether the toggle is triggered manually (by clicking on the icon) or automatically. - */ -async function toggleShowFileSystemElementsThumbnailsAsync(isManualSet) { - if (isManualSet) - showThumbnails = !showThumbnails; - - svgThumbnails.forEach(element => { - showThumbnails ? element.classList.add('enabled') : element.classList.remove('enabled'); - }); - if (isManualSet && addressBarInput.value !== null) { - if (!addressBarInput.value.endsWith(pathSeparator)) - addressBarInput.value += pathSeparator; - await navigateToPathAsync(addressBarInput.value, false, false); - } -} - -/** - * Gets the icon of the node, based on it type. - * @param {any} node The node for which to get the icon. - * @returns The icon on the node. - */ -function getNodeIcon(node) { - switch (node.itemType) { - case "Root": - return "💿"; - case "Directory": - return node.isExpanded ? "📂" : "📁"; - case "File": - return "📄"; - default: - return "❓"; - } -} - -//+======================================================================================+ -//| Event Handlers | -//+======================================================================================+ - -// event handlers for changing file system view modes -btnListView.addEventListener('click', () => switchViewMode('list', null, true)); -btnDetailsView.addEventListener('click', () => switchViewMode('details', null, true)); -btnSmallIconsView.addEventListener('click', () => switchViewMode('icons', 'small', true)); -btnMediumIconsView.addEventListener('click', () => switchViewMode('icons', 'medium', true)); -btnLargeIconsView.addEventListener('click', () => switchViewMode('icons', 'large', true)); -btnExtraLargeIconsView.addEventListener('click', () => switchViewMode('icons', 'extra-large', true)); - -btnNavigatorToggleTreeView.addEventListener('click', async () => await toggleFileSystemTreeViewAsync(true)); -btnNavigatorToggleThumbnails.addEventListener('click', async () => await toggleShowFileSystemElementsThumbnailsAsync(true)); -btnNavigatorToggleSelectionMode.addEventListener('click', toggleFileSystemSelectionMode); -btnNavigatorHiddenElements.addEventListener('click', async () => await toggleShowFileSystemHiddenElementsAsync(true)); -btnNavigatorNavigateUp.addEventListener('click', navigateUpAsync); - -fileSystemExplorer.addEventListener('mouseup', handleFileSystemExplorerMouseUp); -fileSystemExplorer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); -fileSystemExplorerContainer.addEventListener('scroll', handleFileSystemBrowserScrollEvent); - -fileSystemExplorerContainer.addEventListener('mousedown', startSelection); -fileSystemExplorerContainer.addEventListener('mousemove', updateSelection); -fileSystemExplorerContainer.addEventListener('mouseup', endSelection); -fileSystemExplorerContainer.addEventListener('wheel', handleSelection, { passive: true }); -fileSystemExplorerContainer.addEventListener('scroll', handleSelection); - - -/** - * Event handler for the address bar input navigate button Click event. - */ -btnFileSystemBrowserSubmitPath.addEventListener('click', async function () { - await navigateToPathAsync(addressBarInput.value, false, false); - addressBarInput.style.display = 'none'; - addressBar.style.display = 'block'; -}); - -/** - * Event handler for the address bar input edit button Click event. - */ -btnFileSystemBrowserEditPath.addEventListener('click', function () { - addressBarInput.style.display = 'block'; - addressBarInput.focus(); - addressBar.style.display = 'none'; -}); - -/** - * Event handler for the navigator back button Click event. - */ -btnNavigatorNavigateBack.addEventListener('click', async function () { - if (addressBarInput.value !== null) - await navigateToPathAsync(addressBarInput.value, false, true); -}); - -/** - * Event handler for the navigator address bar input KeyDown event. - */ -addressBarInput.addEventListener('keydown', async function (e) { - if (e.key === 'Escape') { - e.preventDefault(); addressBarInput.style.display = 'none'; - addressBar.style.display = 'block'; - } else if (e.key === 'Enter') - await navigateToPathAsync(addressBarInput.value, false, false); -}); + addressBar.style.display = 'block'; + }); -/** - * Event handler for the addressbar Click event. - */ -addressBar.addEventListener('click', function (e) { - // if the clicked element is the ul itself or one of its direct children (but not deeper nested children) - if (e.target === e.currentTarget || e.target.parentElement === e.currentTarget) { - this.style.display = 'none'; // hide #addressBar - addressBarInput.style.display = 'block'; // show #addressBarInput - addressBarInput.focus(); // focus on the input - } -}); + /** + * Event handler for the address bar input edit button Click event. + */ + btnFileSystemBrowserEditPath.addEventListener('click', function () { + addressBarInput.style.display = 'block'; + addressBarInput.focus(); + addressBar.style.display = 'none'; + }); -/** - * Handles the window resize event. - */ -window.addEventListener('resize', function () { - handleFileSystemBrowserResizeEvent(); - // update all dropdowns' positions on resize - const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"]'); - if (dropdown) { - const pathSegmentId = dropdown.getAttribute('data-path-segment-id'); - if (pathSegmentId) - updateDropdownPosition(pathSegmentId, dropdown); - } -}); + /** + * Event handler for the navigator back button Click event. + */ + btnNavigatorNavigateBack.addEventListener('click', async function () { + if (addressBarInput.value !== null) + await navigateToPathAsync(addressBarInput.value, false, true); + }); + + /** + * Event handler for the navigator address bar input KeyDown event. + */ + addressBarInput.addEventListener('keydown', async function (e) { + if (e.key === 'Escape') { + e.preventDefault(); + addressBarInput.style.display = 'none'; + addressBar.style.display = 'block'; + } else if (e.key === 'Enter') + await navigateToPathAsync(addressBarInput.value, false, false); + }); + + /** + * Event handler for the addressbar Click event. + */ + addressBar.addEventListener('click', function (e) { + // if the clicked element is the ul itself or one of its direct children (but not deeper nested children) + if (e.target === e.currentTarget || e.target.parentElement === e.currentTarget) { + this.style.display = 'none'; // hide #addressBar + addressBarInput.style.display = 'block'; // show #addressBarInput + addressBarInput.focus(); // focus on the input + } + }); + + /** + * Handles the window resize event. + */ + window.addEventListener('resize', function () { + handleFileSystemBrowserResizeEvent(); + // update all dropdowns' positions on resize + const dropdown = document.querySelector('.navigator-dropdown[data-detached="true"]'); + if (dropdown) { + const pathSegmentId = dropdown.getAttribute('data-path-segment-id'); + if (pathSegmentId) + updateDropdownPosition(pathSegmentId, dropdown); + } + }); + + // expose the functions that need to be accessed globally + window.initFileSystemBrowser = initFileSystemBrowser; + window.showFileSystemBrowserDialogAsync = showFileSystemBrowserDialogAsync; +})(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 4a24c11b..9bb38ac5 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -219,7 +219,7 @@ function initializeNavigation() { bindNavigationLinks(); // handle browser back/forward - window.addEventListener('popstate', handlePopState); + window.addEventListener('popstate', handlePopStateAsync); } /** @@ -229,7 +229,7 @@ function bindNavigationLinks() { document.querySelectorAll('.nav-link').forEach(link => { // only bind if not already bound if (!link.dataset.boundNavigation) { - link.addEventListener('click', handleNavigation); + link.addEventListener('click', handleNavigationAsync); link.dataset.boundNavigation = 'true'; } }); @@ -239,17 +239,17 @@ function bindNavigationLinks() { * Handles link clicks to navigate dynamically without reloading the page. * @param {Event} e - The click event for a navigation link. */ -async function handleNavigation(e) { +async function handleNavigationAsync(e) { e.preventDefault(); const url = e.target.href; - await updateContent(url, true); + await updateContentAsync(url, true); } /** * Restores page content and title when navigating with browser back/forward buttons. * @param {PopStateEvent} e - The popstate event with previous state data. */ -async function handlePopState(e) { +async function handlePopStateAsync(e) { if (e.state) { // if we have cached content in state, use it immediately if (e.state.content) { @@ -257,7 +257,7 @@ async function handlePopState(e) { document.title = e.state.title; } // still fetch fresh content to ensure it's up to date - await updateContent(e.state.url, false); + await updateContentAsync(e.state.url, false); } } @@ -266,8 +266,18 @@ async function handlePopState(e) { * @param {string} url - URL to fetch new content from. * @param {boolean} addToHistory - Whether to add the new state to history. */ -async function updateContent(url, addToHistory) { +async function updateContentAsync(url, addToHistory) { try { + // first, run cleanup of current view's scripts (unsubscribes handlers in the currently displayed razor views' script section, so it can be properly unloaded) + if (window.viewCleanups) { + Object.values(window.viewCleanups).forEach(cleanup => { + if (typeof cleanup === 'function') + cleanup(); + }); + // reset cleanups object + window.viewCleanups = {}; + } + const response = await fetch(url); const html = await response.text(); @@ -277,81 +287,96 @@ async function updateContent(url, addToHistory) { const content = doc.querySelector('main').innerHTML; const title = doc.querySelector('title')?.textContent || document.title; - // find scripts section content - const scriptsSection = doc.querySelector('[data-section="scripts"]'); - - // update the page + // update the page content document.querySelector('main').innerHTML = content; document.title = title; - // handle Scripts section of the loaded view - if (scriptsSection) { - // get or create scripts container - let scriptsContainer = document.querySelector('[data-section="scripts"]'); - if (!scriptsContainer) { - scriptsContainer = document.createElement('div'); - scriptsContainer.setAttribute('data-section', 'scripts'); - document.body.appendChild(scriptsContainer); - } + // process all scripts in order: component scripts first, then view scripts + const componentScripts = doc.querySelectorAll('script[data-component-script]'); + for (const script of componentScripts) { + const newScript = document.createElement('script'); + // copy script attributes + Array.from(script.attributes).forEach(attr => { + newScript.setAttribute(attr.name, attr.value); + }); - // clear existing scripts in container - scriptsContainer.innerHTML = ''; - - // extract and execute scripts - const scriptElements = Array.from(scriptsSection.getElementsByTagName('script')); - - for (const script of scriptElements) { - const scriptId = script.getAttribute('data-form'); - - // remove existing script with same Id if it exists - const existingScript = document.querySelector(`script[data-form="${scriptId}"]`); - if (existingScript) - existingScript.remove(); - - const newScript = document.createElement('script'); - - // copy script attributes - Array.from(script.attributes).forEach(attr => { - newScript.setAttribute(attr.name, attr.value); + if (script.src) { + // wait for external script to fully load before continuing + await new Promise((resolve, reject) => { + newScript.onload = resolve; + newScript.onerror = reject; + document.body.appendChild(newScript); }); - - // handle both inline and external scripts - if (script.src) { - newScript.src = script.src; - // wait for external script to load - await new Promise((resolve, reject) => { - newScript.onload = resolve; - newScript.onerror = reject; - }); - } else { - // wrap inline scripts in a safety check - newScript.textContent = ` - (function() { - const safeGetElement = (id) => document.getElementById(id); - const safeAddEventListener = (element, e, handler) => { - if (element) - element.addEventListener(e, handler); - }; - ${script.textContent} - })(); - `; - } - - // add script to scripts container - scriptsContainer.appendChild(newScript); } } + // execute component initialization scripts + const componentInits = doc.querySelectorAll('script[data-component-init]'); + for (const script of componentInits) { + const newScript = document.createElement('script'); + // copy script attributes + Array.from(script.attributes).forEach(attr => { + newScript.setAttribute(attr.name, attr.value); + }); + newScript.textContent = script.textContent; + document.body.appendChild(newScript); + } + // process view scripts + const viewScripts = doc.querySelector('[data-section="scripts"]')?.getElementsByTagName('script') || []; + // get or create scripts container + let scriptsContainer = document.querySelector('[data-section="scripts"]'); + if (!scriptsContainer) { + scriptsContainer = document.createElement('div'); + scriptsContainer.setAttribute('data-section', 'scripts'); + document.body.appendChild(scriptsContainer); + } + // clear existing scripts in container + scriptsContainer.innerHTML = ''; + + // process view scripts + for (const script of viewScripts) { + const scriptId = script.getAttribute('data-form'); + // remove existing script with same Id if it exists + const existingScript = document.querySelector(`script[data-form="${scriptId}"]`); + if (existingScript) + existingScript.remove(); + + const newScript = document.createElement('script'); + // copy script attributes + Array.from(script.attributes).forEach(attr => { + newScript.setAttribute(attr.name, attr.value); + }); + + // handle both inline and external scripts + if (script.src) { + newScript.src = script.src; + // wait for external script to load + await new Promise((resolve, reject) => { + newScript.onload = resolve; + newScript.onerror = reject; + }); + } else { + // wrap inline scripts in a safety check + newScript.textContent = ` + (function() { + const safeGetElement = (id) => document.getElementById(id); + const safeAddEventListener = (element, e, handler) => { + if (element) + element.addEventListener(e, handler); + }; + ${script.textContent} + })(); + `; + } + // add script to scripts container + scriptsContainer.appendChild(newScript); + } // bind navigation links in the new content bindNavigationLinks(); // save to history if needed if (addToHistory) { - const state = { - url: url, - content: content, - title: title - }; + const state = { url, content, title }; history.pushState(state, title, url); } } catch (error) { @@ -360,26 +385,6 @@ async function updateContent(url, addToHistory) { } } -/** - * Dynamically loads and executes scripts within the content area once. - * @param {HTMLElement} container - The container to scan for scripts. - */ -function executeScriptsOnce(container) { - // Find all script tags inside the container - container.querySelectorAll('script').forEach(script => { - if (!script.dataset.executed) { - const newScript = document.createElement('script'); - newScript.textContent = script.textContent; // Inline scripts - if (script.src) newScript.src = script.src; // External scripts - newScript.async = script.async; - newScript.defer = script.defer; - - script.dataset.executed = 'true'; // Mark the script as executed - document.body.appendChild(newScript); - } - }); -} - //+======================================================================================+ //| Common Helper Functions | //+======================================================================================+ @@ -432,7 +437,7 @@ function updateOperationProgress(completed, total) { * @param {any} blob The blob to convert. * @returns The converted Base64 string. */ -async function blobToBase64(blob) { +async function blobToBase64Async(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result.split(',')[1]); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs index 97fdcbd8..63a31438 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -78,7 +78,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable Password = _hashService.HashString("TestPass123!"), Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index e43e95ce..e591fb13 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -120,7 +120,7 @@ public class CheckInitializationEndpointTests : IClassFixture, Password = _hashService.HashString("TestPass123!"), Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; @@ -269,7 +269,7 @@ public class LoginEndpointTests : IClassFixture, TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; @@ -292,7 +292,7 @@ public class LoginEndpointTests : IClassFixture, TempPasswordCreated = DateTime.UtcNow, Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; @@ -315,7 +315,7 @@ public class LoginEndpointTests : IClassFixture, TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old) Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index ea85b582..6d5707b4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -243,7 +243,7 @@ public class RecoverPasswordEndpointTests : IClassFixture(); UserEntity user = await dbContext.Users - .Include(user => user.UserRoles) + .Include(user => user.UserRole) .ThenInclude(userRole => userRole.Role) .Include(user => user.UserPermissions) .ThenInclude(userPermission => userPermission.Permission) @@ -93,7 +93,7 @@ public class GetAuthorizationEndpointTests : IClassFixture(); } - private static async Task AddRolesAndPermissionsToUser(UserEntity user, LuminaDbContext dbContext) + private static async Task AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext) { + // create and save role and permission first RoleEntity adminRole = new() { Id = Guid.NewGuid(), @@ -182,6 +183,11 @@ public class GetAuthorizationEndpointTests : IClassFixture /// Disposes API factory resources. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs index e8b392f8..504183d8 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs @@ -124,7 +124,7 @@ public class AuthChangePasswordTests : IClassFixture, IDisposa Username = _testUsername, Password = _hashService.HashString("TestPass123!"), Libraries = [], - UserRoles = [], + UserRole = null, UserPermissions = [], CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs index d2d80119..481aae8f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs @@ -268,7 +268,7 @@ public class AuthLoginTests : IClassFixture, IDisposable Password = _hashService.HashString("TestPass123!"), Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; @@ -291,7 +291,7 @@ public class AuthLoginTests : IClassFixture, IDisposable TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRegisterTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRegisterTests.cs index bda2a059..1a8b769c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRegisterTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRegisterTests.cs @@ -224,7 +224,7 @@ public class AuthRegisterTests : IClassFixture, IDisposable Password = _hashService.HashString("TestPass123!"), Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow }; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs index b18cf642..338cfc6c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs @@ -24,7 +24,7 @@ public class UserAuthorizationEntityMappingTests UserAuthorizationEntity entity = new() { UserId = Guid.NewGuid(), - Roles = new HashSet { "Admin" }, + Role = "Admin", Permissions = new HashSet { AuthorizationPermission.CanViewUsers } }; @@ -34,7 +34,7 @@ public class UserAuthorizationEntityMappingTests // Assert result.Should().NotBeNull(); result.UserId.Should().Be(entity.UserId); - result.Roles.Should().BeEquivalentTo(entity.Roles); + result.Role.Should().BeEquivalentTo(entity.Role); result.Permissions.Should().BeEquivalentTo(entity.Permissions); } @@ -45,7 +45,7 @@ public class UserAuthorizationEntityMappingTests UserAuthorizationEntity entity = new() { UserId = Guid.NewGuid(), - Roles = new HashSet(), + Role = string.Empty, Permissions = new HashSet() }; @@ -55,7 +55,7 @@ public class UserAuthorizationEntityMappingTests // Assert result.Should().NotBeNull(); result.UserId.Should().Be(entity.UserId); - result.Roles.Should().BeEmpty(); + result.Role.Should().BeEmpty(); result.Permissions.Should().BeEmpty(); } @@ -66,10 +66,7 @@ public class UserAuthorizationEntityMappingTests UserAuthorizationEntity entity = new() { UserId = Guid.NewGuid(), - Roles = new HashSet - { - "Admin" - }, + Role = "Admin", Permissions = new HashSet { AuthorizationPermission.CanViewUsers, @@ -84,7 +81,7 @@ public class UserAuthorizationEntityMappingTests // Assert result.Should().NotBeNull(); result.UserId.Should().Be(entity.UserId); - result.Roles.Should().BeEquivalentTo(entity.Roles); + result.Role.Should().BeEquivalentTo(entity.Role); result.Permissions.Should().BeEquivalentTo(entity.Permissions); } @@ -98,7 +95,7 @@ public class UserAuthorizationEntityMappingTests UserAuthorizationEntity entity = new() { UserId = Guid.Parse(userIdString), - Roles = new HashSet { "Admin" }, + Role = "Admin", Permissions = new HashSet { AuthorizationPermission.CanViewUsers } }; @@ -108,7 +105,7 @@ public class UserAuthorizationEntityMappingTests // Assert result.Should().NotBeNull(); result.UserId.Should().Be(entity.UserId); - result.Roles.Should().BeEquivalentTo(entity.Roles); + result.Role.Should().BeEquivalentTo(entity.Role); result.Permissions.Should().BeEquivalentTo(entity.Permissions); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs index ba625448..062e1c7e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs @@ -48,7 +48,7 @@ public class UserEntityFixture TotpSecret = default, Libraries = libraries, UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = userId }) .RuleFor(x => x.Username, f => f.Internet.UserName()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs index 52e43eaa..e9c75fb4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs @@ -38,7 +38,7 @@ public class UserMappingTests TotpSecret = "totpsecret", Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = null @@ -58,7 +58,7 @@ public class UserMappingTests result.TotpSecret.Should().Be(repositoryEntity.TotpSecret); result.Libraries.Should().BeSameAs(repositoryEntity.Libraries); result.UserPermissions.Should().BeSameAs(repositoryEntity.UserPermissions); - result.UserRoles.Should().BeSameAs(repositoryEntity.UserRoles); + result.UserRole.Should().BeSameAs(repositoryEntity.UserRole); result.CreatedOnUtc.Should().Be(repositoryEntity.CreatedOnUtc); result.CreatedBy.Should().Be(repositoryEntity.CreatedBy); result.UpdatedOnUtc.Should().Be(repositoryEntity.UpdatedOnUtc); @@ -85,7 +85,7 @@ public class UserMappingTests Password = "hashedpassword", Libraries = [], UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = null @@ -139,7 +139,7 @@ public class UserMappingTests Password = "hashedpassword", Libraries = libraries, UserPermissions = [], - UserRoles = [], + UserRole = null, CreatedBy = Guid.NewGuid(), CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = null diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/Fixtures/GetAuthorizationQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/Fixtures/GetAuthorizationQueryFixture.cs index f626119d..bd137d54 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/Fixtures/GetAuthorizationQueryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/Fixtures/GetAuthorizationQueryFixture.cs @@ -38,14 +38,12 @@ public class GetAuthorizationQueryFixture /// The created entity. public static UserAuthorizationEntity CreateUserAuthorizationEntity(Guid? userId = null, bool isAdmin = false) { - IReadOnlySet roles = isAdmin - ? ["Admin"] - : new HashSet(); + string role = isAdmin ? "Admin" : string.Empty; return new UserAuthorizationEntity { UserId = userId ?? Guid.NewGuid(), - Roles = roles, + Role = role, Permissions = new HashSet { AuthorizationPermission.CanViewUsers, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs index 23a37d47..407c5590 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs @@ -55,7 +55,7 @@ public class GetAuthorizationQueryHandlerTests // Assert result.IsError.Should().BeFalse(); result.Value.UserId.Should().Be(userId); - result.Value.Roles.Should().BeEquivalentTo(authEntity.Roles); + result.Value.Role.Should().BeEquivalentTo(authEntity.Role); result.Value.Permissions.Should().BeEquivalentTo(authEntity.Permissions); } @@ -81,7 +81,7 @@ public class GetAuthorizationQueryHandlerTests // Assert result.IsError.Should().BeFalse(); result.Value.UserId.Should().Be(targetUserId); - result.Value.Roles.Should().BeEquivalentTo(targetAuthEntity.Roles); + result.Value.Role.Should().BeEquivalentTo(targetAuthEntity.Role); result.Value.Permissions.Should().BeEquivalentTo(targetAuthEntity.Permissions); } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs index ef7d1cfd..9e3a52c4 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -155,7 +155,7 @@ public class UserRepositoryTests TempPassword = "TempPass456", TotpSecret = "NewSecret", Libraries = [], - UserRoles = [], + UserRole = null, UserPermissions = [], CreatedBy = existingUser.Id, CreatedOnUtc = existingUser.CreatedOnUtc, diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs index 2ce5f670..71251568 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs @@ -446,7 +446,7 @@ public class AuthorizationServiceTests // Assert result.IsError.Should().BeFalse(); result.Value.UserId.Should().Be(user.Id); - result.Value.Roles.Should().BeEmpty(); + result.Value.Role.Should().BeNull(); result.Value.Permissions.Should().BeEmpty(); await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); } @@ -471,7 +471,7 @@ public class AuthorizationServiceTests // Assert result.IsError.Should().BeFalse(); result.Value.UserId.Should().Be(user.Id); - result.Value.Roles.Should().BeEmpty(); + result.Value.Role.Should().BeNull(); result.Value.Permissions.Should().BeEquivalentTo( [ AuthorizationPermission.CanViewUsers, @@ -504,7 +504,7 @@ public class AuthorizationServiceTests // Assert result.IsError.Should().BeFalse(); result.Value.UserId.Should().Be(user.Id); - result.Value.Roles.Should().BeEquivalentTo(["Admin"]); + result.Value.Role.Should().BeEquivalentTo("Admin"); result.Value.Permissions.Should().BeEquivalentTo( [ AuthorizationPermission.CanViewUsers, @@ -538,7 +538,7 @@ public class AuthorizationServiceTests // Assert result.IsError.Should().BeFalse(); result.Value.UserId.Should().Be(user.Id); - result.Value.Roles.Should().BeEquivalentTo(["Admin"]); + result.Value.Role.Should().BeEquivalentTo("Admin"); result.Value.Permissions.Should().BeEquivalentTo( [ AuthorizationPermission.CanViewUsers, @@ -547,41 +547,4 @@ public class AuthorizationServiceTests ]); await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); } - - [Fact] - public async Task GetUserAuthorizationAsync_WhenUserHasMultipleRoles_ShouldReturnAllRolesAndPermissions() - { - // Arrange - Dictionary> rolePermissions = new() - { - { - "Admin", - new[] { AuthorizationPermission.CanViewUsers } - }, - { - "", - new[] { AuthorizationPermission.CanDeleteUsers } - } - }; - - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( - rolePermissions: rolePermissions); - - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) - .Returns(ErrorOrFactory.From(user)); - - // Act - ErrorOr result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.UserId.Should().Be(user.Id); - result.Value.Roles.Should().BeEquivalentTo(["Admin", ""]); - result.Value.Permissions.Should().BeEquivalentTo( - [ - AuthorizationPermission.CanViewUsers, - AuthorizationPermission.CanDeleteUsers - ]); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); - } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/AuthorizationServiceFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/AuthorizationServiceFixture.cs index 67729f2f..15dbe299 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/AuthorizationServiceFixture.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/AuthorizationServiceFixture.cs @@ -28,7 +28,58 @@ public class AuthorizationServiceFixture Guid userId = Guid.NewGuid(); DateTime utcNow = DateTime.UtcNow; List userPermissions = []; - List userRoles = []; + UserRoleEntity? userRole = null; + + // create role first if rolePermissions is provided + if (rolePermissions is not null) + { + foreach (KeyValuePair> rolePerm in rolePermissions) + { + Guid roleId = Guid.NewGuid(); + RoleEntity role = new() + { + Id = roleId, + RoleName = rolePerm.Key, + CreatedOnUtc = utcNow, + CreatedBy = userId, + RolePermissions = [] + }; + + foreach (AuthorizationPermission permission in rolePerm.Value) + { + Guid permissionId = Guid.NewGuid(); + PermissionEntity permissionEntity = new() + { + Id = permissionId, + PermissionName = permission, + CreatedOnUtc = utcNow, + CreatedBy = userId + }; + + role.RolePermissions.Add(new RolePermissionEntity + { + Id = Guid.NewGuid(), + RoleId = roleId, + Role = role, + PermissionId = permissionId, + Permission = permissionEntity, + CreatedOnUtc = utcNow, + CreatedBy = userId + }); + } + + userRole = new UserRoleEntity + { + Id = Guid.NewGuid(), + UserId = userId, + RoleId = roleId, + Role = role, + CreatedOnUtc = utcNow, + CreatedBy = userId, + User = null! + }; + } + } UserEntity user = new() { @@ -39,7 +90,7 @@ public class AuthorizationServiceFixture CreatedBy = userId, Libraries = [], UserPermissions = userPermissions, - UserRoles = userRoles + UserRole = userRole }; if (directPermissions is not null) @@ -105,7 +156,7 @@ public class AuthorizationServiceFixture }); } - userRoles.Add(new UserRoleEntity + userRole = new UserRoleEntity { Id = Guid.NewGuid(), UserId = userId, @@ -114,7 +165,7 @@ public class AuthorizationServiceFixture Role = role, CreatedOnUtc = utcNow, CreatedBy = userId - }); + }; } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs index 978b88f4..9dbeda79 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs @@ -48,7 +48,7 @@ public class GetAuthorizationEndpointTests CancellationToken cancellationToken = CancellationToken.None; AuthorizationResponse expectedResponse = new( request.UserId!.Value, - new HashSet { "Admin" }, + "Admin", new HashSet { AuthorizationPermission.CanViewUsers }); _mockSender.Send(Arg.Any(), Arg.Any()) @@ -99,7 +99,7 @@ public class GetAuthorizationEndpointTests _mockSender.Send(Arg.Any(), Arg.Any()) .Returns(ErrorOrFactory.From(new AuthorizationResponse( request.UserId!.Value, - new HashSet().ToHashSet(), + string.Empty, new HashSet().ToHashSet() ))); @@ -130,7 +130,7 @@ public class GetAuthorizationEndpointTests callInfo.Arg().ThrowIfCancellationRequested(); return ErrorOrFactory.From(new AuthorizationResponse( request.UserId!.Value, - new HashSet().ToHashSet(), + string.Empty, new HashSet().ToHashSet() )); }, callInfo.Arg())));