diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/PermissionEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/PermissionEntity.cs index 656b7dbf..ba234131 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/PermissionEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/PermissionEntity.cs @@ -24,11 +24,6 @@ public class PermissionEntity : IStorageEntity, IAuditableEntity /// public required AuthorizationPermission PermissionName { get; init; } - /// - /// Gets the description of the permission. - /// - public string? PermissionDescription { get; set; } - /// /// Gets or sets the collection of role permission associations that include this permission. /// @@ -42,12 +37,12 @@ public class PermissionEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the time and date when the entity was added. /// - public required DateTime CreatedOnUtc { get; set; } + public DateTime CreatedOnUtc { get; set; } /// /// Gets or sets the Id of the user that created the entity. /// - public required Guid CreatedBy { get; set; } + public Guid CreatedBy { get; set; } /// /// Gets or sets the optional time and date when the entity was updated. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RoleEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RoleEntity.cs index 448a2ec7..2d20d9e5 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RoleEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RoleEntity.cs @@ -12,7 +12,7 @@ namespace Lumina.Application.Common.DataAccess.Entities.Authorization; /// Repository entity for a permission in the authorization system. /// [DebuggerDisplay("RoleName: {RoleName}")] -public class RoleEntity : IStorageEntity +public class RoleEntity : IStorageEntity, IAuditableEntity { /// /// Gets the Id of the role. @@ -22,12 +22,7 @@ public class RoleEntity : IStorageEntity /// /// Gets the name of the role. /// - public required AuthorizationRole RoleName { get; init; } - - /// - /// Gets or sets the description of the role. - /// - public string? RoleDescription { get; set; } + public required string RoleName { get; init; } /// /// Gets or sets the collection of user roles associations that include this role. @@ -42,12 +37,12 @@ public class RoleEntity : IStorageEntity /// /// Gets or sets the time and date when the entity was added. /// - public required DateTime CreatedOnUtc { get; set; } + public DateTime CreatedOnUtc { get; set; } /// /// Gets or sets the Id of the user that created the entity. /// - public required Guid CreatedBy { get; set; } + public Guid CreatedBy { get; set; } /// /// Gets or sets the optional time and date when the entity was updated. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RolePermissionEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RolePermissionEntity.cs index b0187d33..46c4fe4e 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RolePermissionEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/RolePermissionEntity.cs @@ -40,12 +40,12 @@ public class RolePermissionEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the time and date when the entity was added. /// - public required DateTime CreatedOnUtc { get; set; } + public DateTime CreatedOnUtc { get; set; } /// /// Gets or sets the Id of the user that created the entity. /// - public required Guid CreatedBy { get; set; } + public Guid CreatedBy { get; set; } /// /// Gets or sets the optional time and date when the entity was updated. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs index 7642fdba..66d67d7f 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserAuthorizationEntity.cs @@ -8,7 +8,7 @@ using System.Diagnostics; namespace Lumina.Application.Common.DataAccess.Entities.Authorization; /// -/// Data Transfer object containing all the authorization info of a user. +/// Data Transfer Object containing all the authorization info of a user. /// [DebuggerDisplay("UserId: {UserId}")] public class UserAuthorizationEntity @@ -21,7 +21,7 @@ public class UserAuthorizationEntity /// /// Gets the collection of roles associated to the user. /// - public required IReadOnlySet Roles { get; init; } + public required IReadOnlySet Roles { get; init; } /// /// Gets the collection of permissions associated to the user. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserPermissionEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserPermissionEntity.cs index 9c13373d..89d9534e 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserPermissionEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserPermissionEntity.cs @@ -41,12 +41,12 @@ public class UserPermissionEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the time and date when the entity was added. /// - public required DateTime CreatedOnUtc { get; set; } + public DateTime CreatedOnUtc { get; set; } /// /// Gets or sets the Id of the user that created the entity. /// - public required Guid CreatedBy { get; set; } + public Guid CreatedBy { get; set; } /// /// Gets or sets the optional time and date when the entity was updated. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserRoleEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserRoleEntity.cs index 3d8a1f3c..a856781c 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserRoleEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Authorization/UserRoleEntity.cs @@ -41,12 +41,12 @@ public class UserRoleEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the time and date when the entity was added. /// - public required DateTime CreatedOnUtc { get; set; } + public DateTime CreatedOnUtc { get; set; } /// /// Gets or sets the Id of the user that created the entity. /// - public required Guid CreatedBy { get; set; } + public Guid CreatedBy { get; set; } /// /// Gets or sets the optional time and date when the entity was updated. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs index 6c282a68..68885e30 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs @@ -63,12 +63,12 @@ public class UserEntity : IStorageEntity, IAuditableEntity /// /// Gets the time and date when the entity was added. /// - public required DateTime CreatedOnUtc { get; set; } + public DateTime CreatedOnUtc { get; set; } /// /// Gets or sets the Id of the user that created the entity. /// - public required Guid CreatedBy { get; set; } + public Guid CreatedBy { get; set; } /// /// Gets the optional time and date when the entity was updated. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs index c13278ff..c932d2f9 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IPermissionRepository.cs @@ -1,7 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; #endregion namespace Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -13,4 +18,11 @@ public interface IPermissionRepository : IRepository, IInsertRepositoryAction, IGetAllRepositoryAction { + /// + /// Gets all permissions that have their Id match an Id in from the storage medium. + /// + /// The list of Ids of the permissions to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByIdsAsync(IEnumerable ids, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs index 9442129f..22198c9c 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Authorization/IRoleRepository.cs @@ -3,7 +3,7 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; -using Lumina.Domain.Common.Enums.Authorization; +using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -14,8 +14,11 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Authorization; /// Interface for the repository for authorization roles. /// public interface IRoleRepository : IRepository, + IGetByIdRepositoryAction, + IGetAllRepositoryAction, IInsertRepositoryAction, - IGetAllRepositoryAction + IUpdateRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Gets a role identified by from the repository, if it exists. @@ -23,5 +26,5 @@ public interface IRoleRepository : IRepository, /// The type of role to get. /// Cancellation token that can be used to stop the execution. /// An containing either a if found, or an error. - Task> GetByNameAsync(AuthorizationRole roleType, CancellationToken cancellationToken); + Task> GetByNameAsync(string roleType, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs index 8867f328..88303d4c 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs @@ -12,10 +12,17 @@ public static partial class Errors public static class Authorization { public static Error NotAuthorized => Error.Unauthorized(description: nameof(NotAuthorized)); - public static Error AdminAccountAlreadyCreated => Error.Unauthorized(description: nameof(AdminAccountAlreadyCreated)); - public static Error AdminAccountNotFound => Error.Unauthorized(description: nameof(AdminAccountNotFound)); - public static Error AdminRoleNotFound => Error.Unauthorized(description: nameof(AdminRoleNotFound)); + public static Error AdminAccountAlreadyCreated => Error.Conflict(description: nameof(AdminAccountAlreadyCreated)); + public static Error AdminAccountNotFound => Error.NotFound(description: nameof(AdminAccountNotFound)); + public static Error AdminRoleNotFound => Error.NotFound(description: nameof(AdminRoleNotFound)); + public static Error RoleNotFound => Error.NotFound(description: nameof(RoleNotFound)); public static Error PermissionAlreadyExists => Error.Unauthorized(description: nameof(PermissionAlreadyExists)); - public static Error RoleAlreadyExists => Error.Unauthorized(description: nameof(RoleAlreadyExists)); + public static Error RoleAlreadyExists => Error.Conflict(description: nameof(RoleAlreadyExists)); + public static Error RoleIdCannotBeEmpty => Error.Validation(description: nameof(RoleIdCannotBeEmpty)); + public static Error PermissionsListCannotBeNull => Error.Validation(description: nameof(PermissionsListCannotBeNull)); + public static Error PermissionsListCannotBeEmpty => Error.Validation(description: nameof(PermissionsListCannotBeEmpty)); + 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)); } } diff --git a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs index f487eaa0..b6b21bfb 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs @@ -12,5 +12,6 @@ public static partial class Errors public static class Persistence { public static Error ErrorPersistingMediaLibrary => Error.Failure(description: nameof(ErrorPersistingMediaLibrary)); + public static Error ErrorPersistingAuthorizationRole => Error.Failure(description: nameof(ErrorPersistingAuthorizationRole)); } } diff --git a/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs b/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs index fcad85de..96f72470 100644 --- a/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Authorization/IAuthorizationService.cs @@ -31,7 +31,7 @@ public interface IAuthorizationService /// The role to check. /// Cancellation token that can be used to stop the execution. /// if the user is in the specified role, otherwise. - Task IsInRoleAsync(Guid userId, AuthorizationRole role, CancellationToken cancellationToken); + Task IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken); /// /// Evaluates whether the specified user meets the conditions defined in the specified authorization policy. diff --git a/src/Lumina.Application/Common/Mapping/Authorization/AddRoleRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/AddRoleRequestMapping.cs new file mode 100644 index 00000000..d4dc2072 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/AddRoleRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Contracts.Requests.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class AddRoleRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static AddRoleCommand ToCommand(this AddRoleRequest request) + { + return new AddRoleCommand( + request.RoleName!, + request.Permissions! + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/DeleteRoleRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/DeleteRoleRequestMapping.cs new file mode 100644 index 00000000..4df414da --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/DeleteRoleRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; +using Lumina.Contracts.Requests.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class DeleteRoleRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static DeleteRoleCommand ToCommand(this DeleteRoleRequest request) + { + return new DeleteRoleCommand( + request.RoleId!.Value + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/GetRolePermissionsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/GetRolePermissionsRequestMapping.cs new file mode 100644 index 00000000..fa2e0b3c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/GetRolePermissionsRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Contracts.Requests.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class GetRolePermissionsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetRolePermissionsQuery ToQuery(this GetRolePermissionsRequest request) + { + return new GetRolePermissionsQuery( + request.RoleId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/PermissionEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/PermissionEntityMapping.cs new file mode 100644 index 00000000..63115425 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/PermissionEntityMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Contracts.Responses.Authorization; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class PermissionEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static PermissionResponse ToResponse(this PermissionEntity repositoryEntity) + { + return new PermissionResponse( + repositoryEntity.Id, + repositoryEntity.PermissionName + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(permission => permission.ToResponse()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/RoleEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/RoleEntityMapping.cs new file mode 100644 index 00000000..5a513858 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/RoleEntityMapping.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Responses.Authorization; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class RoleEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static RoleResponse ToResponse(this RoleEntity repositoryEntity) + { + return new RoleResponse( + repositoryEntity.Id, + repositoryEntity.RoleName + ); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static RolePermissionsResponse ToRolePermissionsResponse(this RoleEntity repositoryEntity) + { + return new RolePermissionsResponse( + new RoleDto(repositoryEntity.Id, repositoryEntity.RoleName), + repositoryEntity.RolePermissions.Select(rolePermission => rolePermission.ToResponse()).ToArray() + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted responses. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(role => role.ToResponse()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/RolePermissionEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/RolePermissionEntityMapping.cs new file mode 100644 index 00000000..2a8c2b3c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/RolePermissionEntityMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Responses.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class RolePermissionEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static PermissionDto ToResponse(this RolePermissionEntity repositoryEntity) + { + return new PermissionDto( + repositoryEntity.PermissionId, + repositoryEntity.Permission.PermissionName + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/UpdateRoleRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/UpdateRoleRequestMapping.cs new file mode 100644 index 00000000..d9db1b26 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Authorization/UpdateRoleRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; +using Lumina.Contracts.Requests.Authorization; +#endregion + +namespace Lumina.Application.Common.Mapping.Authorization; + +/// +/// Extension methods for converting . +/// +public static class UpdateRoleRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdateRoleCommand ToCommand(this UpdateRoleRequest request) + { + return new UpdateRoleCommand( + request.RoleId!.Value, + request.RoleName!, + request.Permissions! + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs index f75ca292..c4d0eb8f 100644 --- a/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Authorization/UserAuthorizationEntityMapping.cs @@ -11,16 +11,16 @@ namespace Lumina.Application.Common.Mapping.Authorization; public static class UserAuthorizationEntityMapping { /// - /// Converts to . + /// Converts to . /// - /// The infrastructure entity to be converted. + /// The infrastructure entity to be converted. /// The converted response. - public static GetAuthorizationResponse ToResponse(this UserAuthorizationEntity infrastructureEntity) + public static AuthorizationResponse ToResponse(this UserAuthorizationEntity repositoryEntity) { - return new GetAuthorizationResponse( - infrastructureEntity.UserId, - infrastructureEntity.Roles, - infrastructureEntity.Permissions + return new AuthorizationResponse( + repositoryEntity.UserId, + repositoryEntity.Roles, + repositoryEntity.Permissions ); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs new file mode 100644 index 00000000..93184771 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; + +/// +/// Query for retrieving the list of authorization permissions. +/// +public record GetPermissionsQuery : IRequest>>; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs new file mode 100644 index 00000000..3b00e28f --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +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.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; + +/// +/// Handler for the query to retrieve the list of authorization permissions. +/// +public class GetPermissionsQueryHandler : IRequestHandler>> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IPermissionRepository _permissionRepository; + + /// + /// 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 GetPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _permissionRepository = unitOfWork.GetRepository(); + } + + /// + /// Handles the query to retrieve the list of authorization permissions. + /// + /// 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(GetPermissionsQuery 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; + ErrorOr> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getPermissionsResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs new file mode 100644 index 00000000..bdbd33aa --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs @@ -0,0 +1,21 @@ +#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.Admin.Authorization.Roles.Commands.AddRole; + +/// +/// Command for adding an authorization role. +/// +/// The name of the role. +/// The collection or permissions of the role. +[DebuggerDisplay("RoleName: {RoleName}")] +public record AddRoleCommand( + string RoleName, + List Permissions +) : IRequest>; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs new file mode 100644 index 00000000..74c13ceb --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +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.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; + +/// +/// Handler for the command to add an authorization role. +/// +public class AddRoleCommandHandler : 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 AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + } + + /// + /// Handles the command to add an authorization role. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async ValueTask> Handle(AddRoleCommand request, CancellationToken cancellationToken) + { + // only admins can create authorization roles + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return Errors.Authorization.NotAuthorized; + + IRoleRepository roleRepository = _unitOfWork.GetRepository(); + + // create the new role, with its permissions + RoleEntity newRole = new() + { + RoleName = request.RoleName, + RolePermissions = request.Permissions.Select(permissionId => new RolePermissionEntity() + { + PermissionId = permissionId, + Permission = null!, + Role = null!, + RoleId = default + }).ToList() + }; + // save the new role in the repository + ErrorOr insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); + if (insertRoleResult.IsError) + return insertRoleResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // retrieve the newly saved authorization role from the persistence medium and return it + ErrorOr getRoleResult = await roleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false); + if (getRoleResult.IsError) + return getRoleResult.Errors; + if (getRoleResult.Value is null) + return Errors.Persistence.ErrorPersistingAuthorizationRole; + return getRoleResult.Value.ToRolePermissionsResponse(); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs new file mode 100644 index 00000000..a2b2f01f --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; + +/// +/// Validates the needed validation rules for . +/// +public class AddRoleCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddRoleCommandValidator() + { + RuleFor(x => x.RoleName) + .NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description) + .NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + + RuleFor(x => x.Permissions) + .NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description) + .NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description); + RuleForEach(x => x.Permissions) + .NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs new file mode 100644 index 00000000..8773d8c1 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; + +/// +/// Command for deleting an authorization role. +/// +/// The Id of the role. +[DebuggerDisplay("RoleId: {RoleId}")] +public record DeleteRoleCommand( + Guid RoleId +) : IRequest>; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs new file mode 100644 index 00000000..940b88bc --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; + +/// +/// Handler for the command to delete an authorization role. +/// +public class DeleteRoleCommandHandler : 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 DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + } + + /// + /// Handles the command to delete an authorization role. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully deleted , or an error message. + /// + public async ValueTask> Handle(DeleteRoleCommand request, CancellationToken cancellationToken) + { + // only admins can delete authorization roles + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return Errors.Authorization.NotAuthorized; + + // check if a role with the requested Id exists + IRoleRepository roleRepository = _unitOfWork.GetRepository(); + ErrorOr getExistingRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + if (getExistingRoleResult.IsError) + return getExistingRoleResult.Errors; + else if (getExistingRoleResult.Value is null) + return Errors.Authorization.RoleNotFound; + + // delete the role and its permissions + ErrorOr deleteRoleResult = await roleRepository.DeleteByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + if (deleteRoleResult.IsError) + return deleteRoleResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return deleteRoleResult.Value; + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs new file mode 100644 index 00000000..a64205d5 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; + +/// +/// Validates the needed validation rules for . +/// +public class DeleteRoleCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteRoleCommandValidator() + { + RuleFor(x => x.RoleId) + .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + } +} 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 new file mode 100644 index 00000000..7d28f7c5 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs @@ -0,0 +1,23 @@ +#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.Admin.Authorization.Roles.Commands.UpdateRole; + +/// +/// Command for updating an authorization role. +/// +/// The Id of the role. +/// The name of the role. +/// The collection or permissions of the role. +[DebuggerDisplay("RoleName: {RoleName}")] +public record UpdateRoleCommand( + Guid RoleId, + string RoleName, + List Permissions +) : IRequest>; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs new file mode 100644 index 00000000..11ebe913 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +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.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; + +/// +/// Handler for the command to update an authorization role. +/// +public class UpdateRoleCommandHandler : 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 UpdateRoleCommandHandler(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(UpdateRoleCommand request, CancellationToken cancellationToken) + { + // only admins can update authorization roles + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return Errors.Authorization.NotAuthorized; + + IRoleRepository roleRepository = _unitOfWork.GetRepository(); + + // update the role and its permissions + RoleEntity newRole = new() + { + Id = request.RoleId, + RoleName = request.RoleName, + RolePermissions = request.Permissions.Select(permissionId => new RolePermissionEntity() + { + PermissionId = permissionId, + Permission = null!, + Role = null!, + RoleId = default + }).ToList() + }; + // save the updated role in the repository + ErrorOr updateRoleResult = await roleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false); + if (updateRoleResult.IsError) + return updateRoleResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // retrieve the updated authorization role from the persistence medium and return it + ErrorOr getRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + if (getRoleResult.IsError) + return getRoleResult.Errors; + if (getRoleResult.Value is null) + return Errors.Persistence.ErrorPersistingAuthorizationRole; + return getRoleResult.Value.ToRolePermissionsResponse(); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs new file mode 100644 index 00000000..4672ed03 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateRoleCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateRoleCommandValidator() + { + RuleFor(x => x.RoleId) + .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + + RuleFor(x => x.RoleName) + .NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description) + .NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description); + + RuleFor(x => x.Permissions) + .NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description) + .NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description); + RuleForEach(x => x.Permissions) + .NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs new file mode 100644 index 00000000..5413a926 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.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.Admin.Authorization.Roles.Queries.GetRolePermissions; + +/// +/// Query for getting the authorization permissions of a role identified by . +/// +/// The Id of the authorization role for which to get the list of permissions. +[DebuggerDisplay("RoleId: {RoleId}")] +public record GetRolePermissionsQuery( + Guid RoleId +) : IRequest>; 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 new file mode 100644 index 00000000..8c21ea93 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +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.Admin.Authorization.Roles.Queries.GetRolePermissions; + +/// +/// Handler for the query to retrieve the list of authorization permissions for a role. +/// +public class GetRolePermissionsQueryHandler : IRequestHandler> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IRoleRepository _roleRepository; + + /// + /// 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 GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _roleRepository = unitOfWork.GetRepository(); + } + + /// + /// Handles the query to retrieve the list of authorization permissions for a role. + /// + /// 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(GetRolePermissionsQuery request, CancellationToken cancellationToken) + { + // only admins can see the list of authorization roles + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return Errors.Authorization.NotAuthorized; + ErrorOr getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + if (getRoleResult.IsError) + return getRoleResult.Errors; + else if (getRoleResult.Value is null) + return Errors.Authorization.RoleNotFound; + return getRoleResult.Value.ToRolePermissionsResponse(); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs new file mode 100644 index 00000000..107b65d3 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Application.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; + +/// +/// Validates the needed validation rules for . +/// +public class GetRolePermissionsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetRolePermissionsQueryValidator() + { + RuleFor(x => x.RoleId) + .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs new file mode 100644 index 00000000..6a168b06 --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Authorization; +using Mediator; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; + +/// +/// Query for retrieving the list of authorization roles. +/// +public record GetRolesQuery() : IRequest>>; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs new file mode 100644 index 00000000..405086ac --- /dev/null +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +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.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; + +/// +/// Handler for the query to retrieve the list of authorization roles. +/// +public class GetRolesQueryHandler : IRequestHandler>> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IRoleRepository _roleRepository; + + /// + /// 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 GetRolesQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _roleRepository = unitOfWork.GetRepository(); + } + + /// + /// Handles the query to retrieve the list of authorization roles. + /// + /// 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(GetRolesQuery request, CancellationToken cancellationToken) + { + // only admins can see the list of authorization roles + bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false); + if (!isAdmin) + return Errors.Authorization.NotAuthorized; + ErrorOr> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getRolesResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index ea47bb58..bfda1160 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -38,7 +38,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs index ccc9782d..76052b5d 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; -using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -81,10 +81,10 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler private ErrorOr> GetDrives() { - ErrorOr> driveResult = _driveService.GetDrives(); - if (driveResult.IsError) - return driveResult.Errors; - return ErrorOrFactory.From(driveResult.Value.ToTreeNodeResponses()); + ErrorOr> getDrivesResult = _driveService.GetDrives(); + if (getDrivesResult.IsError) + return getDrivesResult.Errors; + return ErrorOrFactory.From(getDrivesResult.Value.ToTreeNodeResponses()); } /// @@ -138,11 +138,11 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles, bool includeHiddenElements) { // get subdirectories under the current node's path - ErrorOr> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path, includeHiddenElements); - if (subDirectoriesResult.IsError) - return subDirectoriesResult.Errors; + ErrorOr> getSubDirectoriesResult = _directoryService.GetSubdirectories(node.Path, includeHiddenElements); + if (getSubDirectoriesResult.IsError) + return getSubDirectoriesResult.Errors; // add each subdirectory as a child node of the current directory - foreach (Directory subDirectory in subDirectoriesResult.Value ?? []) + foreach (Directory subDirectory in getSubDirectoriesResult.Value ?? []) { FileSystemTreeNodeResponse subDirNode = new() { @@ -157,11 +157,11 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler> filesResult = _fileService.GetFiles(node.Path, includeHiddenElements); - if (filesResult.IsError) - return filesResult.Errors; + ErrorOr> getFilesResult = _fileService.GetFiles(node.Path, includeHiddenElements); + if (getFilesResult.IsError) + return getFilesResult.Errors; // add each file as a child node of the current directory - foreach (File file in filesResult.Value) + foreach (File file in getFilesResult.Value) { FileSystemTreeNodeResponse fileNode = new() { diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs index 1e46d6a3..5733c577 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs @@ -2,8 +2,8 @@ using ErrorOr; using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Mediator; using System.Collections.Generic; using System.Threading; @@ -38,7 +38,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); + ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs index 06591796..287c3762 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs @@ -38,7 +38,7 @@ public class GetDrivesQueryHandler : IRequestHandler public ValueTask>> Handle(GetDrivesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _driveService.GetDrives(); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors)); + ErrorOr> getDrivesResult = _driveService.GetDrives(); + return ValueTask.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs index 57e79a1b..2f37dfa6 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs @@ -38,7 +38,7 @@ public class GetFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetFilesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + ErrorOr> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index 6bbb0023..7bdd0799 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -38,7 +38,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler public ValueTask>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); + ErrorOr> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements); + return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs index 6a3444c5..00bd0d7c 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandler.cs @@ -36,7 +36,7 @@ public class CombinePathCommandHandler : IRequestHandler public ValueTask> Handle(CombinePathCommand request, CancellationToken cancellationToken) { - ErrorOr result = _pathService.CombinePath(request.OriginalPath!, request.NewPath!); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors)); + ErrorOr combinePathResult = _pathService.CombinePath(request.OriginalPath!, request.NewPath!); + return ValueTask.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs index ed8fd8c5..48f1675f 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs @@ -38,7 +38,7 @@ public class SplitPathCommandHandler : IRequestHandler public ValueTask>> Handle(SplitPathCommand request, CancellationToken cancellationToken) { - ErrorOr> result = _pathService.ParsePath(request.Path!); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + ErrorOr> parsePathResult = _pathService.ParsePath(request.Path!); + return ValueTask.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs index 2f11a756..f17ef062 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs @@ -38,7 +38,7 @@ public class GetPathParentQueryHandler : IRequestHandler public ValueTask>> Handle(GetPathParentQuery request, CancellationToken cancellationToken) { - ErrorOr> result = _pathService.GoUpOneLevel(request.Path!); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); + ErrorOr> goUpOneLevelResult = _pathService.GoUpOneLevel(request.Path!); + return ValueTask.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs index 4c32cfb3..98732e01 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs @@ -35,7 +35,7 @@ public class GetPathRootQueryHandler : IRequestHandlerAn containing either the root of the specified path, or an error. public ValueTask> Handle(GetPathRootQuery request, CancellationToken cancellationToken) { - ErrorOr result = _pathService.GetPathRoot(request.Path!); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors)); + ErrorOr getPathRootResult = _pathService.GetPathRoot(request.Path!); + return ValueTask.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs index 5475c23e..1c884438 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs @@ -35,7 +35,7 @@ public class GetThumbnailQueryHandler : IRequestHandlerAn containing either a thumbnail, or an error. public async ValueTask> Handle(GetThumbnailQuery request, CancellationToken cancellationToken) { - ErrorOr result = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken); - return await ValueTask.FromResult(result.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors)); + ErrorOr getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken); + return await ValueTask.FromResult(getThumbnailResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => 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 78e87bbd..17f2872b 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -1,8 +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.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; @@ -74,10 +72,10 @@ public class SetupApplicationCommandHandler : IRequestHandler(); - ErrorOr> selectUserResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - if (selectUserResult.IsError) - return selectUserResult.Errors; - else if (selectUserResult.Value.Any()) + ErrorOr> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (selectUsersResult.IsError) + return selectUsersResult.Errors; + else if (selectUsersResult.Value.Any()) return Errors.Authorization.AdminAccountAlreadyCreated; // no users are present, register the admin one string? totpSecret = null; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs index 690c99d8..4ef82f25 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs @@ -3,9 +3,7 @@ using ErrorOr; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Contracts.Responses.UsersManagement; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Mediator; using System.Collections.Generic; using System.Linq; @@ -42,9 +40,9 @@ public class CheckInitializationQueryHandler : IRequestHandler(); // if the repository reports an error, or there are no users, the application has not been initialized - ErrorOr> resultSelectUser = await userRepository.GetAllAsync(cancellationToken); - if (!resultSelectUser.IsError) - return new InitializationResponse(resultSelectUser.Value.Any()); + ErrorOr> selectUsersResult = await userRepository.GetAllAsync(cancellationToken); + if (!selectUsersResult.IsError) + return new InitializationResponse(selectUsersResult.Value.Any()); return new InitializationResponse(false); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index 62c2dc0c..3afa19d7 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; -using Lumina.Domain.Common.Enums.MediaLibrary; using Lumina.Contracts.Responses.MediaLibrary.Management; using Mediator; using System; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 8d5d925e..d6d8c7ff 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -62,11 +62,11 @@ public class AddLibraryCommandHandler : IRequestHandler retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); - if (retrievedLibraryResult.IsError) - return retrievedLibraryResult.Errors; - if (retrievedLibraryResult.Value is null) + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) return Errors.Persistence.ErrorPersistingMediaLibrary; - return retrievedLibraryResult.Value.ToResponse(); + return getLibraryResult.Value.ToResponse(); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 7a95de4c..eeea382b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -46,13 +46,13 @@ public class UpdateLibraryCommandHandler : IRequestHandler(); - ErrorOr resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); - if (resultGetLibrary.IsError) - return resultGetLibrary.Errors; - else if (resultGetLibrary.Value is null) + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError) + return getLibraryResult.Errors; + else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; // if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it - if (resultGetLibrary.Value.UserId != request.CurrentUserId) // TODO: after implementing the Admin role, add that permission check here too + if (getLibraryResult.Value.UserId != request.CurrentUserId) // TODO: after implementing the Admin role, add that permission check here too return ApplicationErrors.Authorization.NotAuthorized; // create a domain library object @@ -75,11 +75,11 @@ public class UpdateLibraryCommandHandler : IRequestHandler retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); - if (retrievedLibraryResult.IsError) - return retrievedLibraryResult.Errors; - if (retrievedLibraryResult.Value is null) + ErrorOr getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + if (getCreatedLibraryResult.IsError) + return getCreatedLibraryResult.Errors; + if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; - return retrievedLibraryResult.Value.ToResponse(); + return getCreatedLibraryResult.Value.ToResponse(); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQuery.cs index b90037ee..c734e7ad 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQuery.cs @@ -12,8 +12,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries; /// Query for getting a media library by its Id. /// /// The Id of the media library to get. -/// The Id os the user requesting the media library. -[DebuggerDisplay("Path: {Path}")] +/// The Id of the user requesting the media library. +[DebuggerDisplay("Id: {Id}")] public record GetLibraryQuery( Guid Id, Guid UserId diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryHandler.cs index 6d73b28d..91ee0193 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryQueryHandler.cs @@ -42,14 +42,14 @@ public class GetLibraryQueryHandler : IRequestHandler> Handle(GetLibraryQuery request, CancellationToken cancellationToken) { ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ErrorOr resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); - if (resultGetLibrary.IsError) - return resultGetLibrary.Errors; - else if (resultGetLibrary.Value is null) + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError) + return getLibraryResult.Errors; + else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; // if the user that requested the library is not an Admin or is not the owner of the library, they do not have the right to view it - if (resultGetLibrary.Value.UserId != request.UserId) // TODO: after implementing the Admin role, add that permission check here too + if (getLibraryResult.Value.UserId != request.UserId) // TODO: after implementing the Admin role, add that permission check here too return ApplicationErrors.Authorization.NotAuthorized; - return resultGetLibrary.Value.ToResponse(); + return getLibraryResult.Value.ToResponse(); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs index c821c0c2..ceda4423 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -46,22 +46,22 @@ public class ChangePasswordCommandHandler : IRequestHandler> Handle(ChangePasswordCommand request, CancellationToken cancellationToken) { IUserRepository userRepository = _unitOfWork.GetRepository(); - ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); - if (resultSelectUser.IsError) - return resultSelectUser.Errors; - else if (resultSelectUser.Value is null) + ErrorOr getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsError) + return getUserResult.Errors; + else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; // validate if the current password is correct - if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(resultSelectUser.Value.Password!))) + if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!))) return Errors.Authentication.InvalidCurrentPassword; - resultSelectUser.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!)); + getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!)); // if the password change was initiated via a password reset, remote the temporary password that was generated in the process - resultSelectUser.Value.TempPassword = null; - resultSelectUser.Value.TempPasswordCreated = null; + getUserResult.Value.TempPassword = null; + getUserResult.Value.TempPasswordCreated = null; // update the user - ErrorOr resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false); - if (resultUpdateUser.IsError) - return resultUpdateUser.Errors; + ErrorOr updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); + if (updateUserResult.IsError) + return updateUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return new ChangePasswordResponse(true); } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs index 93622228..35f02923 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -56,29 +56,29 @@ public class RecoverPasswordCommandHandler : IRequestHandler(); - ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); - if (resultSelectUser.IsError) - return resultSelectUser.Errors; - else if (resultSelectUser.Value is null) + ErrorOr getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsError) + return getUserResult.Errors; + else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; - else if (resultSelectUser.Value.TempPassword is not null) // if a temp password is present, a password request was already requested + else if (getUserResult.Value.TempPassword is not null) // if a temp password is present, a password request was already requested return Errors.Authentication.PasswordResetAlreadyRequested; // check if the user uses TOTP - bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret); + bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret); if (!usesTotp) return Errors.Authentication.InvalidTotpCode; if (usesTotp && string.IsNullOrEmpty(request.TotpCode)) return Errors.Authentication.InvalidTotpCode; else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it - if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode)) + if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), request.TotpCode)) return Errors.Authentication.InvalidTotpCode; // hash the new password and assign it to a temporary password that will be valid 15 minutes - resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator - resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow; + getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator + getUserResult.Value.TempPasswordCreated = DateTime.UtcNow; // update the user - ErrorOr resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false); - if (resultUpdateUser.IsError) - return resultUpdateUser.Errors; + ErrorOr updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); + if (updateUserResult.IsError) + return updateUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return new RecoverPasswordResponse(true); } 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 b87595c4..ce13b85c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -65,10 +65,10 @@ public class RegisterUserCommandHandler : IRequestHandler(); - ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); - if (resultSelectUser.IsError) - return resultSelectUser.Errors; - else if (resultSelectUser.Value is not null) + ErrorOr getUserRResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + if (getUserRResult.IsError) + return getUserRResult.Errors; + else if (getUserRResult.Value is not null) return Errors.Authentication.UsernameAlreadyExists; string? totpSecret = null; Guid id = Guid.NewGuid(); @@ -94,9 +94,9 @@ public class RegisterUserCommandHandler : IRequestHandler resultInsertUser = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); - if (resultInsertUser.IsError) - return resultInsertUser.Errors; + ErrorOr insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); + if (insertUserResult.IsError) + return insertUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // TODO: insert the default admin profile preferences when they are implemented // if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 3fd1e383..38242f44 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -65,29 +65,29 @@ public class LoginUserQueryHandler : IRequestHandler(); - ErrorOr resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); - if (resultSelectUser.IsError) - return resultSelectUser.Errors; - else if (resultSelectUser.Value is null) + ErrorOr getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false); + if (getUserResult.IsError) + return getUserResult.Errors; + else if (getUserResult.Value is null) return Errors.Authentication.InvalidUsernameOrPassword; // validate that the password is correct - if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!))) + if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!))) { // if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too - if (resultSelectUser.Value.TempPassword is not null) + if (getUserResult.Value.TempPassword is not null) { // the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error - if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow) + if (getUserResult.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow) { - resultSelectUser.Value.TempPassword = null; - resultSelectUser.Value.TempPasswordCreated = null; - await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken); + getUserResult.Value.TempPassword = null; + getUserResult.Value.TempPasswordCreated = null; + await userRepository.UpdateAsync(getUserResult.Value, cancellationToken); await _unitOfWork.SaveChangesAsync(cancellationToken); return Errors.Authentication.TempPasswordExpired; } else // temporary password is still valid, validate password against it { - if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.TempPassword!))) + if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!))) return Errors.Authentication.InvalidUsernameOrPassword; } } @@ -95,14 +95,14 @@ public class LoginUserQueryHandler : IRequestHandler>; +) : IRequest>; 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 91b52107..1e0b9be6 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandler.cs @@ -6,7 +6,6 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; -using Lumina.Domain.Common.Enums.Authorization; using Mediator; using System.Linq; using System.Threading; @@ -18,13 +17,13 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho /// /// Handler for the query to retrieve the authorization roles and permissions of an account. /// -public class GetAuthorizationQueryHandler : IRequestHandler> +public class GetAuthorizationQueryHandler : IRequestHandler> { private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. @@ -40,22 +39,22 @@ public class GetAuthorizationQueryHandler : IRequestHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a , or an error message. + /// An containing either a , or an error message. /// - public async ValueTask> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken) + public async ValueTask> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken) { // first, check if the Id of the user for whom to get the permission list is different from the Id currently making the request if (_currentUserService.UserId != request.UserId) { // if it is, get the role of the current user, and see if they are Admin - ErrorOr resultGetCurrentUserPermission = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false); - if (resultGetCurrentUserPermission.IsError) - return resultGetCurrentUserPermission.Errors; + ErrorOr getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false); + if (getCurrentUserPermissionResult.IsError) + return getCurrentUserPermissionResult.Errors; // if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request - if (!resultGetCurrentUserPermission.Value.Roles.Any(role => role == AuthorizationRole.Admin)) + if (!getCurrentUserPermissionResult.Value.Roles.Any(role => role == "Admin")) return Errors.Authorization.NotAuthorized; } - ErrorOr resultGetUserPermission = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); - return resultGetUserPermission.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors); + ErrorOr getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false); + return getUserPermissionResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors); } } diff --git a/src/Lumina.Contracts/DTO/Authentication/PermissionDto.cs b/src/Lumina.Contracts/DTO/Authentication/PermissionDto.cs new file mode 100644 index 00000000..c3d69af8 --- /dev/null +++ b/src/Lumina.Contracts/DTO/Authentication/PermissionDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.Authorization; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.Authentication; + +/// +/// Data transfer object for an authorization permission. +/// +/// The Id of the permission. +/// The name of the permission. +[DebuggerDisplay("Id: {Id}, PermissionName: {PermissionName}")] +public record PermissionDto( + Guid Id, + AuthorizationPermission PermissionName +); diff --git a/src/Lumina.Contracts/DTO/Authentication/RoleDto.cs b/src/Lumina.Contracts/DTO/Authentication/RoleDto.cs new file mode 100644 index 00000000..e59df0fa --- /dev/null +++ b/src/Lumina.Contracts/DTO/Authentication/RoleDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.Authentication; + +/// +/// Data transfer object for an authorization role. +/// +/// The Id of the role. +/// The name of the role. +[DebuggerDisplay("Id: {Id}, RoleName: {RoleName}")] +public record RoleDto( + Guid Id, + string RoleName +); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs index bd81f133..4ba7a284 100644 --- a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs @@ -5,7 +5,7 @@ using System.Diagnostics; namespace Lumina.Contracts.DTO.MediaContributors; /// -/// Repository entity for a media contributor. +/// Data transfer object for a media contributor. /// /// The name details of the media contributor, including display and legal names. /// The role details of the media contributor, including the role name and category. diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorNameDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorNameDto.cs index 674ae321..bda57019 100644 --- a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorNameDto.cs +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorNameDto.cs @@ -5,7 +5,7 @@ using System.Diagnostics; namespace Lumina.Contracts.DTO.MediaContributors; /// -/// Repository entity for a media contributor name. +/// Data transfer object for a media contributor name. /// /// The display name of the media contributor. /// The legal name of the media contributor. diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs index ddb48ef8..f659de93 100644 --- a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs @@ -5,7 +5,7 @@ using System.Diagnostics; namespace Lumina.Contracts.DTO.MediaContributors; /// -/// Repository entity for a media contributor role. +/// Data transfer object for a media contributor role. /// /// The name of the role assigned to the media contributor. /// The category of the role. diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/Management/LibraryContentLocationDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/Management/LibraryContentLocationDto.cs index 1a164e95..1caace4c 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/Management/LibraryContentLocationDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/Management/LibraryContentLocationDto.cs @@ -5,13 +5,9 @@ using System.Diagnostics; namespace Lumina.Contracts.DTO.MediaLibrary.Management; /// -/// Repository entity for a media library content location. +/// Data transfer object for a media library content location. /// [DebuggerDisplay("Path: {Path}")] -public class LibraryContentLocationDto -{ - /// - /// Gets or sets the path of the media library content location. - /// - public required string Path { get; set; } -} +public record LibraryContentLocationDto( + string Path +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDto.cs index da058c47..bc0481b7 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDto.cs @@ -6,7 +6,7 @@ using System.Diagnostics; namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; /// -/// Repository entity for ISBN information. +/// Data transfer object for ISBN information. /// /// The ISBN value. /// The format of the ISBN (e.g., ISBN-10 or ISBN-13). diff --git a/src/Lumina.Contracts/Requests/Authorization/AddRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/AddRoleRequest.cs new file mode 100644 index 00000000..b96e75f3 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authorization/AddRoleRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authorization; + +/// +/// Represents a request for adding an authorization role. +/// +/// The name of the role. Required. +/// The collection or permissions of the role. Required. +[DebuggerDisplay("RoleName: {RoleName}")] +public record AddRoleRequest( + string? RoleName, + List? Permissions +); diff --git a/src/Lumina.Contracts/Requests/Authorization/DeleteRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/DeleteRoleRequest.cs new file mode 100644 index 00000000..83b4bb7f --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authorization/DeleteRoleRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authorization; + +/// +/// Represents a request for deleting an authorization role. +/// +/// The Id of the role. Required. +[DebuggerDisplay("RoleId: {RoleId}")] +public record DeleteRoleRequest( + Guid? RoleId +); diff --git a/src/Lumina.Contracts/Requests/Authorization/GetRolePermissionsRequest.cs b/src/Lumina.Contracts/Requests/Authorization/GetRolePermissionsRequest.cs new file mode 100644 index 00000000..7a12ce63 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authorization/GetRolePermissionsRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Authorization; + +/// +/// Represents a request to get the authorization permissions of a role identified by . +/// +/// The Id of authorization role. Required. +[DebuggerDisplay("RoleId: {RoleId}")] +public record GetRolePermissionsRequest( + Guid RoleId +); diff --git a/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs b/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.cs new file mode 100644 index 00000000..bcd45fba --- /dev/null +++ b/src/Lumina.Contracts/Requests/Authorization/UpdateRoleRequest.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 an existing authorization role. +/// +/// The Id of the role. Required. +/// The name of the role. Required. +/// The collection or permissions of the role. Required. +[DebuggerDisplay("RoleName: {RoleName}")] +public record UpdateRoleRequest( + Guid? RoleId, + string? RoleName, + List? Permissions +); diff --git a/src/Lumina.Contracts/Responses/Authorization/GetAuthorizationResponse.cs b/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs similarity index 90% rename from src/Lumina.Contracts/Responses/Authorization/GetAuthorizationResponse.cs rename to src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs index fb4e3abf..68c4ce96 100644 --- a/src/Lumina.Contracts/Responses/Authorization/GetAuthorizationResponse.cs +++ b/src/Lumina.Contracts/Responses/Authorization/AuthorizationResponse.cs @@ -14,8 +14,8 @@ namespace Lumina.Contracts.Responses.Authorization; /// The collection of roles associated to the user. /// The collection of permissions associated to the user. [DebuggerDisplay("UserId: {UserId}")] -public record GetAuthorizationResponse( +public record AuthorizationResponse( Guid UserId, - IReadOnlySet Roles, + IReadOnlySet Roles, IReadOnlySet Permissions ); diff --git a/src/Lumina.Contracts/Responses/Authorization/PermissionResponse.cs b/src/Lumina.Contracts/Responses/Authorization/PermissionResponse.cs new file mode 100644 index 00000000..87eb2a11 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authorization/PermissionResponse.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.Authorization; +using System; +#endregion + +namespace Lumina.Contracts.Responses.Authorization; + +/// +/// Represents the response model for a request for an of authorization permission. +/// +/// The Id of the requested authorization permission. +/// The requested authorization permission. +public record PermissionResponse( + Guid Id, + AuthorizationPermission PermissionName +); diff --git a/src/Lumina.Contracts/Responses/Authorization/RolePermissionsResponse.cs b/src/Lumina.Contracts/Responses/Authorization/RolePermissionsResponse.cs new file mode 100644 index 00000000..b7260a08 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authorization/RolePermissionsResponse.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Authentication; +#endregion + +namespace Lumina.Contracts.Responses.Authorization; + +/// +/// Represents an authorizaton role permissions response. +/// +/// The authorization role. +/// The permissions of the authorization role. +public record RolePermissionsResponse( + RoleDto Role, + PermissionDto[] Permissions +); diff --git a/src/Lumina.Contracts/Responses/Authorization/RoleResponse.cs b/src/Lumina.Contracts/Responses/Authorization/RoleResponse.cs new file mode 100644 index 00000000..012986d8 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Authorization/RoleResponse.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.Authorization; + +/// +/// Represents the response model for a request for an authorization role. +/// +/// The Id of the requested authorization role. +/// The requested authorization role. +public record RoleResponse( + Guid Id, + string RoleName +); diff --git a/src/Lumina.DataAccess/Common/Configuration/PermissionConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/PermissionConfiguration.cs index 994b1e6c..231a3c56 100644 --- a/src/Lumina.DataAccess/Common/Configuration/PermissionConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/PermissionConfiguration.cs @@ -29,11 +29,6 @@ public class PermissionConfiguration : IEntityTypeConfiguration permission.PermissionDescription) - .HasMaxLength(255) - .HasDefaultValue(null) - .HasColumnOrder(2); - // audit builder.Property(permission => permission.CreatedOnUtc) .IsRequired() diff --git a/src/Lumina.DataAccess/Common/Configuration/RoleConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/RoleConfiguration.cs index 364737b9..b02bf925 100644 --- a/src/Lumina.DataAccess/Common/Configuration/RoleConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/RoleConfiguration.cs @@ -25,15 +25,9 @@ public class RoleConfiguration : IEntityTypeConfiguration builder.Property(role => role.RoleName) .IsRequired() - .HasConversion() .HasMaxLength(100) .HasColumnOrder(1); - builder.Property(permission => permission.RoleDescription) - .HasMaxLength(255) - .HasDefaultValue(null) - .HasColumnOrder(2); - // audit builder.Property(role => role.CreatedOnUtc) .IsRequired() diff --git a/src/Lumina.DataAccess/Common/Migrations/20241216112516_ConvertsRoleFromEnumToString.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20241216112516_ConvertsRoleFromEnumToString.Designer.cs new file mode 100644 index 00000000..f049b0af --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241216112516_ConvertsRoleFromEnumToString.Designer.cs @@ -0,0 +1,697 @@ +// +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("20241216112516_ConvertsRoleFromEnumToString")] + partial class ConvertsRoleFromEnumToString + { + /// + 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("RoleId") + .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", "RoleId"); + + 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") + .WithMany("UserRoles") + .HasForeignKey("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("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20241216112516_ConvertsRoleFromEnumToString.cs b/src/Lumina.DataAccess/Common/Migrations/20241216112516_ConvertsRoleFromEnumToString.cs new file mode 100644 index 00000000..978d3fac --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20241216112516_ConvertsRoleFromEnumToString.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class ConvertsRoleFromEnumToString : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "RoleDescription", + table: "Roles"); + + migrationBuilder.DropColumn( + name: "PermissionDescription", + table: "Permissions"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RoleDescription", + table: "Roles", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 2); + + migrationBuilder.AddColumn( + name: "PermissionDescription", + table: "Permissions", + type: "TEXT", + maxLength: 255, + nullable: true) + .Annotation("Relational:ColumnOrder", 2); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 4334da2a..d27adb31 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -62,11 +62,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(3); - b.Property("PermissionDescription") - .HasMaxLength(255) - .HasColumnType("TEXT") - .HasColumnOrder(2); - b.Property("PermissionName") .IsRequired() .HasMaxLength(100) @@ -101,11 +96,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(3); - b.Property("RoleDescription") - .HasMaxLength(255) - .HasColumnType("TEXT") - .HasColumnOrder(2); - b.Property("RoleName") .IsRequired() .HasMaxLength(100) diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs index 7e371bb6..6cf0db57 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs @@ -5,7 +5,9 @@ using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.Errors; using Lumina.DataAccess.Core.UoW; using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -53,4 +55,15 @@ internal sealed class PermissionRepository : IPermissionRepository { return await _luminaDbContext.Permissions.ToListAsync(cancellationToken).ConfigureAwait(false); } + + /// + /// Gets all permissions that have their Id match an Id in from the storage medium. + /// + /// The list of Ids of the permissions to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByIdsAsync(IEnumerable ids, CancellationToken cancellationToken) + { + return await _luminaDbContext.Permissions.Where(permission => ids.Contains(permission.Id)).ToListAsync(cancellationToken).ConfigureAwait(false); + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs index 46f9f64b..5c8961b2 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs @@ -4,8 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.Errors; using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.Common.Enums.Authorization; using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -37,7 +37,7 @@ internal sealed class RoleRepository : IRoleRepository /// An representing either a successfull operation, or an error. public async Task> InsertAsync(RoleEntity role, CancellationToken cancellationToken) { - bool roleExists = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id, cancellationToken).ConfigureAwait(false); + bool roleExists = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id || repositoryRole.RoleName == role.RoleName, cancellationToken).ConfigureAwait(false); if (roleExists) return Errors.Authorization.RoleAlreadyExists; @@ -61,7 +61,7 @@ internal sealed class RoleRepository : IRoleRepository /// The type of role to get. /// Cancellation token that can be used to stop the execution. /// An containing either a if found, or an error. - public async Task> GetByNameAsync(AuthorizationRole roleType, CancellationToken cancellationToken) + public async Task> GetByNameAsync(string roleType, CancellationToken cancellationToken) { return await _luminaDbContext.Roles .Include(role => role.RolePermissions) @@ -69,4 +69,61 @@ internal sealed class RoleRepository : IRoleRepository .FirstOrDefaultAsync(role => role.RoleName == roleType, cancellationToken) .ConfigureAwait(false); } + + /// + /// Gets a identified by from the storage medium. + /// + /// The id of the authorization role to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.Roles + .Include(role => role.RolePermissions) + .ThenInclude(rolePermission => rolePermission.Permission) + .FirstOrDefaultAsync(role => role.Id == id, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Updates a role. + /// + /// The role to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successfull operation, or an error. + public async Task> UpdateAsync(RoleEntity data, CancellationToken cancellationToken) + { + // check if a role with the requested Id exists, and retrieve it + RoleEntity? foundRole = await _luminaDbContext.Roles + .Include(role => role.RolePermissions) + .ThenInclude(rolePermission => rolePermission.Permission) + .FirstOrDefaultAsync(role => role.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (foundRole is null) + return Errors.Authorization.RoleNotFound; + // update scalar properties + _luminaDbContext.Entry(foundRole).CurrentValues.SetValues(data); + // update owned entities (their changes are not automatically tracked by EF) + foundRole.RolePermissions.Clear(); + foreach (RolePermissionEntity rolePermission in data.RolePermissions) + foundRole.RolePermissions.Add(rolePermission); + return Result.Updated; + } + + /// + /// Deletes a role identified by from the storage medium. + /// + /// The id of the role to be deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successfull operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + // check if a role with the requested Id exists, and retrieve it + RoleEntity? foundRole = await _luminaDbContext.Roles + .FirstOrDefaultAsync(role => role.Id == id, cancellationToken).ConfigureAwait(false); + if (foundRole is null) + return Errors.Authorization.RoleNotFound; + // then, remove it + _luminaDbContext.Remove(foundRole); + return Result.Deleted; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs index e060a9f4..3ef5d3b6 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -60,7 +60,7 @@ internal sealed class LibraryRepository : ILibraryRepository /// /// Updates a media library. /// - /// Ther media library to update. + /// The media library to update. /// Cancellation token that can be used to stop the execution. /// An representing either a successfull operation, or an error. public async Task> UpdateAsync(LibraryEntity data, CancellationToken cancellationToken) diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index f236ab24..17a87a92 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -48,9 +48,9 @@ public class DataSeedService : IDataSeedService // create the default authorization permissions and add them to the repository. PermissionEntity[] defaultPermissions = [ - new() { PermissionName = AuthorizationPermission.CanViewUsers, PermissionDescription = "Can view users", CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, - new() { PermissionName = AuthorizationPermission.CanDeleteUsers, PermissionDescription = "Can delete users", CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, - new() { PermissionName = AuthorizationPermission.CanRegisterUsers, PermissionDescription = "Can register users", CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow } + new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, + new() { PermissionName = AuthorizationPermission.CanDeleteUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, + new() { PermissionName = AuthorizationPermission.CanRegisterUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow } ]; foreach (PermissionEntity permission in defaultPermissions) { @@ -75,7 +75,7 @@ public class DataSeedService : IDataSeedService // create the default authorization roles and add them to the repository RoleEntity[] defaultRoles = [ - new() { RoleName = AuthorizationRole.Admin, RoleDescription = "Administrator role", CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow } + new() { RoleName = "Admin", CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow } ]; foreach (RoleEntity role in defaultRoles) { @@ -100,7 +100,7 @@ public class DataSeedService : IDataSeedService IPermissionRepository permissionRepository = _unitOfWork.GetRepository(); // get the admin role - ErrorOr getAdminRoleResult = await roleRepository.GetByNameAsync(AuthorizationRole.Admin, cancellationToken).ConfigureAwait(false); + ErrorOr getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsError) return getAdminRoleResult.Errors; @@ -146,7 +146,7 @@ public class DataSeedService : IDataSeedService // get the admin role - ErrorOr getAdminRoleResult = await roleRepository.GetByNameAsync(AuthorizationRole.Admin, cancellationToken).ConfigureAwait(false); + ErrorOr getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsError) return getAdminRoleResult.Errors; diff --git a/src/Lumina.Domain/Common/Enums/Authorization/AuthorizationRole.cs b/src/Lumina.Domain/Common/Enums/Authorization/AuthorizationRole.cs index c5af2cbf..76f9f8b1 100644 --- a/src/Lumina.Domain/Common/Enums/Authorization/AuthorizationRole.cs +++ b/src/Lumina.Domain/Common/Enums/Authorization/AuthorizationRole.cs @@ -1,10 +1,10 @@ -namespace Lumina.Domain.Common.Enums.Authorization; +//namespace Lumina.Domain.Common.Enums.Authorization; -/// -/// Enumeration for authorization roles. -/// -public enum AuthorizationRole -{ - None = 0, - Admin = 1 -} +///// +///// Enumeration for authorization roles. +///// +//public enum AuthorizationRole +//{ +// None = 0, +// Admin = 1 +//} diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index f926b554..36594360 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -67,7 +67,7 @@ public class AuthorizationService : IAuthorizationService /// The role to check. /// Cancellation token that can be used to stop the execution. /// if the user is in the specified role, otherwise. - public async Task IsInRoleAsync(Guid userId, AuthorizationRole role, CancellationToken cancellationToken) + public async Task IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken) { ErrorOr getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsError || getUserResult.Value is null) @@ -106,7 +106,7 @@ public class AuthorizationService : IAuthorizationService return Errors.Users.UserDoesNotExist; // get all roles - HashSet roles = getUserResult.Value.UserRoles + HashSet roles = getUserResult.Value.UserRoles .Select(userRole => userRole.Role.RoleName) .ToHashSet(); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Admin/ApiRoutes.Permissions.cs b/src/Lumina.Presentation.Api/Common/Routes/Admin/ApiRoutes.Permissions.cs new file mode 100644 index 00000000..4b92116f --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Admin/ApiRoutes.Permissions.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Api.Common.Routes.UsersManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Permissions route. + /// + public static class Permissions + { + public const string GET_PERMISSIONS = "/permissions"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Admin/ApiRoutes.Roles.cs b/src/Lumina.Presentation.Api/Common/Routes/Admin/ApiRoutes.Roles.cs new file mode 100644 index 00000000..0d49d5d2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Admin/ApiRoutes.Roles.cs @@ -0,0 +1,19 @@ +namespace Lumina.Presentation.Api.Common.Routes.UsersManagement; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Roles route. + /// + public static class Roles + { + public const string GET_ROLE_PERMISSIONS_BY_ROLE_ID = "/roles/{roleId}/permissions"; + public const string GET_ROLES = "/roles"; + public const string CREATE_ROLE = "/roles"; + public const string UPDATE_ROLE = "/roles"; + public const string DELETE_ROLE = "/roles/{roleId}"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs new file mode 100644 index 00000000..69b7a4fb --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; +using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; +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.Admin.Authorization.Permissions.GetPermissions; + +/// +/// API endpoint for the /permissions route. +/// +public class GetPermissionsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetPermissionsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Permissions.GET_PERMISSIONS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of authorization permissions. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(new GetPermissionsQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointSummary.cs new file mode 100644 index 00000000..a0acb120 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointSummary.cs @@ -0,0 +1,76 @@ +#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.Admin.Authorization.Permissions.GetPermissions; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPermissionsEndpointSummary() + { + Summary = "Gets the collection of authorization permissions."; + Description = "Gets the entire list of authorization permissions."; + + Response(200, "The authorization permissions 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 = "/api/v1/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/permissions" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/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 = "/api/v1/permissions", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs new file mode 100644 index 00000000..c7e15a07 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.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.Admin.Authorization.Roles.AddRole; + +/// +/// API endpoint for the /roles route. +/// +public class AddRoleEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public AddRoleEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Roles.CREATE_ROLE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Creates a new authorization role. + /// + /// The request containing the authorization role to be created. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddRoleRequest 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/Admin/Authorization/Roles/AddRole/AddRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointSummary.cs new file mode 100644 index 00000000..7536c519 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointSummary.cs @@ -0,0 +1,128 @@ +#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.Admin.Authorization.Roles.AddRole; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddRoleEndpointSummary() + { + Summary = "Adds a new authorization role."; + Description = "Creates a new authorization role and returns its details."; + + ExampleRequest = new AddRoleRequest( + RoleName: "Editor", + Permissions: [ + Guid.NewGuid(), + Guid.NewGuid(), + ] + ); + + RequestParam(r => r.RoleName, "The name of the role. Required."); + RequestParam(r => r.Permissions, "The collection or 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."); + + + Response(200, "The authorization role was successfully created.", example: + new RolePermissionsResponse( + Role: new RoleDto(Id: Guid.NewGuid(), "Editor"), + Permissions: [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers), new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] + )); + + 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/roles" + }, + 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/roles" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/roles" + } + } + ); + + 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/roles", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed due to a conflict, role already exists.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "RoleAlreadyExists", + instance = "/api/v1/roles", + traceId = "00-f8784de7cb2d70b81b2529893068bee7-4779e0404fe5f554-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/roles", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "RoleNameCannotBeNull", + "RoleNameCannotBeEmpty", + "PermissionsListCannotBeNull", + "PermissionsListCannotBeEmpty", + "PermissionIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs new file mode 100644 index 00000000..7accd7e2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Contracts.Requests.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.Admin.Authorization.Roles.DeleteRole; + +/// +/// API endpoint for the /roles route. +/// +public class DeleteRoleEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public DeleteRoleEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.DELETE); + Routes(ApiRoutes.Roles.DELETE_ROLE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes an authorization role. + /// + /// The request containing the Id of the authorization role to be deleted. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteRoleRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.NoContent(), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs new file mode 100644 index 00000000..4281c0ac --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.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.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// API endpoint for the /roles/{roleId}/permissions route. +/// +public class GetRolePermissionsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetRolePermissionsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Roles.GET_ROLE_PERMISSIONS_BY_ROLE_ID); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of authorization permissions of a role identified by Id. + /// + /// The request containing the id of the role for which to get the list of permissions. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetRolePermissionsRequest 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/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs new file mode 100644 index 00000000..4613a09b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.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.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetRolePermissionsEndpointSummary() + { + Summary = "Gets the collection of authorization permissions of a role."; + Description = "Gets the entire list of authorization permissions of a role."; + + ExampleRequest = new GetRolePermissionsRequest( + RoleId: Guid.NewGuid() + ); + + RequestParam(r => r.RoleId, "The Id of authorization role. Required."); + + Response(200, "The authorization permissions 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 = "/api/v1/roles/{roleId}/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/roles/{roleId}/permissions" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/roles/{roleId}/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 = "/api/v1/roles/{roleId}/permissions", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested authorization role 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 = "RoleNotFound", + instance = "/api/v1/roles/{roleId}/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/roles/{roleId}/permissions", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "RoleIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs new file mode 100644 index 00000000..48f5e47c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; +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.Admin.Authorization.Roles.GetRoles; + +/// +/// API endpoint for the /roles route. +/// +public class GetRolesEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetRolesEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Roles.GET_ROLES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of authorization roles. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(new GetRolesQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs new file mode 100644 index 00000000..1418737e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointSummary.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRoles; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPermissionsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPermissionsEndpointSummary() + { + Summary = "Gets the collection of authorization roles."; + Description = "Gets the entire list of authorization roles."; + + Response(200, "The authorization roles are returned.", + example: new[] { + new RoleResponse(Id: Guid.NewGuid(), "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/roles" + }, + 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/roles" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/roles" + } + } + ); + + 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/roles", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.cs new file mode 100644 index 00000000..a9c13ee7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpoint.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.Admin.Authorization.Roles.UpdateRole; + +/// +/// API endpoint for the /roles route. +/// +public class UpdateRoleEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public UpdateRoleEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.PUT); + Routes(ApiRoutes.Roles.UPDATE_ROLE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates an existing authorization role. + /// + /// The request containing the authorization role to be updated. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateRoleRequest 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/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs new file mode 100644 index 00000000..c089a068 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.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.Admin.Authorization.Roles.UpdateRole; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateRoleEndpointSummary() + { + Summary = "Updates an existing authorization role."; + Description = "Updates an existing authorization role and returns its details."; + + ExampleRequest = new UpdateRoleRequest( + RoleId: Guid.NewGuid(), + RoleName: "Editor", + Permissions: [ + Guid.NewGuid(), + Guid.NewGuid(), + ] + ); + + RequestParam(r => 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."); + + ResponseParam(r => r.Role, "The authorization role entity."); + ResponseParam(r => r.Permissions, "The list of permissions of the role entity."); + + + Response(200, "The authorization role was successfully updated.", example: + new RolePermissionsResponse( + Role: new RoleDto(Id: Guid.NewGuid(), "Editor"), + Permissions: [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers), new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] + )); + + 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/roles" + }, + 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/roles" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/roles" + } + } + ); + + 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/roles", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the provided role 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 = "RoleNotFound", + instance = "/api/v1/roles", + 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/roles", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "RoleNameCannotBeNull", + "RoleNameCannotBeEmpty", + "PermissionsListCannotBeNull", + "PermissionsListCannotBeEmpty", + "PermissionIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs index 3c2be24b..a46b1aba 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs @@ -50,7 +50,7 @@ public class AddLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddLibraryRequest request, CancellationToken cancellationToken) { - // retrieve the currently authenticated user, and send it with the request + // retrieve the currently authenticated user, and send it with the request // TODO: replace with current user service string? user = User.FindFirstValue(ClaimTypes.NameIdentifier); ErrorOr result = await _sender.Send(request.ToCommand(Guid.Parse(user!)), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Libraries.ADD_LIBRARY}/{result.Value.Id}", result.Value), Problem); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs similarity index 98% rename from src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs rename to src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs index 1bec1041..e22f8375 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/GetBook/GetBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs @@ -9,7 +9,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.GetBook; +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; /// /// API endpoint for the /books/{id} route. diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs index ae858294..ee084521 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpoint.cs @@ -43,13 +43,13 @@ public class GetAuthorizationEndpoint : BaseEndpoint - /// Gets the authentication roles and permissions of an account. + /// Gets the authorization roles and permissions of an account. /// - /// The request containing the account for which to get the authentication roles and permissions. + /// The request containing the account for which to get the authorization roles and permissions. /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetAuthorizationRequest request, CancellationToken cancellationToken) { - ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + 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/GetAuthorization/GetAuthorizationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs index 0742d875..f5daca88 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 @@ -31,9 +31,9 @@ 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.", - example: new GetAuthorizationResponse( + example: new AuthorizationResponse( UserId: Guid.NewGuid(), - Roles: new HashSet() { AuthorizationRole.Admin }, + Roles: new HashSet() { "Admin" }, Permissions: new HashSet() { AuthorizationPermission.CanRegisterUsers, AuthorizationPermission.CanDeleteUsers } )); diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index 2805fd39..cfb60cc9 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -125,19 +125,31 @@ public class ApiHttpClient : IApiHttpClient } /// - /// Sends a DELETE request to the specified as an asynchronous operation and returns the result. + /// Sends a DELETE request to the specified as an asynchronous operation. /// - /// The expected type of the response content. /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. - /// The deserialized response containing the result of the DELETE request. - public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) + public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) { using HttpRequestMessage request = new(HttpMethod.Delete, endpoint); AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); if (authenticationHeader is not null) request.Headers.Authorization = authenticationHeader; - return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + //return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + // send the HTTP request and read the response + HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + ProblemDetailsModel? problemDetails = null; + string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + // attempt to deserialize the response content to ProblemDetailsModel if the request fails + try + { + problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + } + catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + throw new ApiException(problemDetails, response.StatusCode); + } } /// diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index a5d8f3c7..86a1e71d 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -39,13 +39,11 @@ public interface IApiHttpClient Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default); /// - /// Sends a DELETE request to the specified as an asynchronous operation and returns the result. + /// Sends a DELETE request to the specified as an asynchronous operation. /// - /// The expected type of the response content. /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. - /// The deserialized response containing the result of the DELETE request. - Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default); + Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default); /// /// Sends a PUT request to the specified as an asynchronous operation and returns the result. diff --git a/src/Lumina.Presentation.Web/Common/Attributes/RequireRoleAttribute.cs b/src/Lumina.Presentation.Web/Common/Attributes/RequireRoleAttribute.cs index aa4190e1..8221d78d 100644 --- a/src/Lumina.Presentation.Web/Common/Attributes/RequireRoleAttribute.cs +++ b/src/Lumina.Presentation.Web/Common/Attributes/RequireRoleAttribute.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Common.Filters.TypeFilters; using Lumina.Presentation.Web.Common.Models.Authorization; #endregion @@ -18,7 +17,7 @@ public class RequireRoleAttribute : ApiAuthorizationAttribute /// Initializes a new instance of the class. /// /// One or more roles that are allowed to access the endpoint. - public RequireRoleAttribute(params AuthorizationRole[] roles) : base() + public RequireRoleAttribute(params string[] roles) : base() { Arguments = [new AuthorizationRequirementModel { Roles = roles }]; } diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs similarity index 96% rename from src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationService.cs rename to src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs index 1ecc0a7f..614a3425 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationService.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Models.Authorization; using Microsoft.AspNetCore.Http; using System; using System.Linq; @@ -10,7 +10,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Web.Common.Models.Authorization; +namespace Lumina.Presentation.Web.Common.Authorization; /// /// Implements authorization logic for API endpoints by validating user roles, permissions, and policies. @@ -49,7 +49,7 @@ public class AuthorizationService : IAuthorizationService /// The role to check. /// Cancellation token that can be used to stop the execution. /// if the currently logged in user is in the specified role, otherwise. - public async Task IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken) + public async Task IsInRoleAsync(string role, CancellationToken cancellationToken) { GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(cancellationToken).ConfigureAwait(false); return authorization.Roles.Contains(role); diff --git a/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs index 651bb67b..7a0481be 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs @@ -26,7 +26,7 @@ public interface IAuthorizationService /// The role to check. /// Cancellation token that can be used to stop the execution. /// if the currently logged in user is in the specified role, otherwise. - Task IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken); + Task IsInRoleAsync(string role, CancellationToken cancellationToken); /// /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy. diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index c607976d..05197e4c 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters; -using Lumina.Presentation.Web.Common.Filters.ExceptionFilters; using Lumina.Presentation.Web.Common.MiddlewareFilters; using Lumina.Presentation.Web.Common.Models.Authorization; using Lumina.Presentation.Web.Common.Security; @@ -49,7 +48,7 @@ public static class PresentationWebLayerServices { services.AddControllersWithViews(mvcOptions => { - mvcOptions.Filters.Add(); + //mvcOptions.Filters.Add(); mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter }) .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) @@ -216,7 +215,6 @@ public static class PresentationWebLayerServices // enable access to the current HTTP context in non-controller classes services.AddHttpContextAccessor(); - services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddSingleton(); diff --git a/src/Lumina.Presentation.Web/Common/Enums/Authorization/AuthorizationRole.cs b/src/Lumina.Presentation.Web/Common/Enums/Authorization/AuthorizationRole.cs index e4b8d5f7..8a5daf09 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/Authorization/AuthorizationRole.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/Authorization/AuthorizationRole.cs @@ -1,10 +1,10 @@ -namespace Lumina.Presentation.Web.Common.Enums.Authorization; +//namespace Lumina.Presentation.Web.Common.Enums.Authorization; -/// -/// Enumeration for authorization roles. -/// -public enum AuthorizationRole -{ - None = 0, - Admin = 1 -} +///// +///// Enumeration for authorization roles. +///// +//public enum AuthorizationRole +//{ +// None = 0, +// Admin = 1 +//} diff --git a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs index cb2c1db9..c6bf492a 100644 --- a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs +++ b/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs @@ -1,6 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Models.Authorization; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System.Threading.Tasks; @@ -33,7 +36,18 @@ public class ApiAuthorizationFilter : IAsyncAuthorizationFilter /// The authorization filter context. public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement)) - context.Result = new ForbidResult(); + try + { + if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement)) + context.Result = new ForbidResult(); + } + catch (ApiException ex) + { + if (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized) + { + await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + context.HttpContext.Response.Cookies.Delete("Token"); + } + } } } diff --git a/src/Lumina.Presentation.Web/Common/Filters/ExceptionFilters/ApiExceptionFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/ExceptionFilters/ApiExceptionFilter.cs deleted file mode 100644 index 65c91f33..00000000 --- a/src/Lumina.Presentation.Web/Common/Filters/ExceptionFilters/ApiExceptionFilter.cs +++ /dev/null @@ -1,122 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Exceptions; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Localization; -using Microsoft.Extensions.Logging; -using System.Linq; -using System.Net; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Common.Filters.ExceptionFilters; - -/// -/// Filters API exceptions and provides centralized handling for API-related errors. -/// -public class ApiExceptionFilter : IExceptionFilter -{ - private readonly IStringLocalizer _stringLocalizer; - private readonly ILogger _logger; - - /// - /// Initializes a new instance of the class with the specified localizer and logger. - /// - /// Injected service used for providing localized strings. - /// Injected service used for logging. - public ApiExceptionFilter(IStringLocalizer stringLocalizer, ILogger logger) - { - _stringLocalizer = stringLocalizer; - _logger = logger; - } - - /// - /// Called after an action has thrown an Exception. - /// - /// The . - public void OnException(ExceptionContext context) - { - // check if the exception is an ApiException - if (context.Exception is ApiException apiException) - { - // log all available details for debugging/monitoring - _logger.LogError( - apiException, - "API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}", - apiException.HttpStatusCode, - apiException.ProblemDetails?.Title, - apiException.ProblemDetails?.Detail, - apiException.ProblemDetails?.Extensions); - // handle unauthorized errors by prompting the user to re-login - if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in) - { - SignOutSynchronously(context.HttpContext); - string currentUrl = context.HttpContext.Request.GetDisplayUrl(); - _logger.LogInformation("Redirecting unauthorized user to {Url}", currentUrl); - context.HttpContext.Response.Redirect(currentUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too - } - else - { - StringBuilder errorMessage = new(); - if (apiException.ProblemDetails is not null) - { - // only show the meaningful error message to the user - if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail)) - errorMessage.AppendLine($"{_stringLocalizer[apiException.ProblemDetails.Detail]}
"); - else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title)) - errorMessage.AppendLine($"{_stringLocalizer[apiException.ProblemDetails.Title]}
"); - - if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true) - if (errorsObj.ValueKind == JsonValueKind.Object) - foreach (JsonProperty error in errorsObj.EnumerateObject()) - { - _logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString())); - if (error.Value.ValueKind == JsonValueKind.Array) - foreach (JsonElement errorValue in error.Value.EnumerateArray()) - errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}
"); - } - } - else - { - _logger.LogError(apiException, "Generic API error occurred"); - errorMessage.AppendLine($"{apiException.Message}
"); - } - // return a JSON result with the error details - context.Result = new JsonResult(new - { - success = false, - errorMessage = errorMessage.ToString() - }); - } - } - else - { - _logger.LogError(context.Exception, "Unexpected exception occurred: {Message}", context.Exception.Message); - // return a JSON result with the error details - context.Result = new JsonResult(new - { - success = false, - errorMessage = context.Exception.Message.ToString() - }); - } - // mark the exception as handled to prevent propagation - context.ExceptionHandled = true; - } - - /// - /// Signs out the user synchronously by deleting the authentication cookie and token. - /// - /// The HttpContext for the current request. - private static void SignOutSynchronously(HttpContext httpContext) - { - Task task = httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); - task.Wait(); // run the task synchronously - httpContext.Response.Cookies.Delete("Token"); - } -} diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs new file mode 100644 index 00000000..11bc559a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -0,0 +1,172 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using System; +using System.Linq; +using System.Net; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Middlewares; + +/// +/// Middleware to handle exceptions thrown when the remote API returns a problem details. +/// +public class ExceptionHandlingMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + private readonly IStringLocalizer _stringLocalizer; + + /// + /// Initializes a new instance of the class. + /// + /// The next middleware in the request pipeline. + /// Injected service used for logging. + /// Injected service used for providing localized strings. + public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger, IStringLocalizer stringLocalizer) + { + _next = next; + _logger = logger; + _stringLocalizer = stringLocalizer; + } + + /// + /// Handles incoming requests and handles any exceptions thrown. + /// + /// The for the current request. + public async Task InvokeAsync(HttpContext context) + { + try + { + await _next(context); + } + catch (ApiException apiException) // threat API exceptions differently - they contain Problem Details properties + { + await HandleApiExceptionAsync(context, apiException); + } + catch (Exception ex) // other cases - + { + _logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message); + // return a JSON result with the error details + await WriteJsonResponseAsync(context, new + { + success = false, + errorMessage = ex.Message + }); + } + } + + /// + /// Handles exceptions specific to the API, including problem details. + /// + private async Task HandleApiExceptionAsync(HttpContext context, ApiException apiException) + { + // log all available details for debugging/monitoring + _logger.LogError( + apiException, + "API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}", + apiException.HttpStatusCode, + apiException.ProblemDetails?.Title, + apiException.ProblemDetails?.Detail, + apiException.ProblemDetails?.Extensions); + + // handle unauthorized errors by prompting the user to re-login + if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in) + await HandleUnauthorizedAsync(context); + else + { + string errorMessage = BuildErrorMessage(apiException); + await WriteJsonResponseAsync(context, new + { + success = false, + errorMessage + }); + } + } + + /// + /// Handles unauthorized exceptions. + /// + private async Task HandleUnauthorizedAsync(HttpContext context) + { + // when API JWT tokens expire, the client app is still logged in, so, sign out the user and delete the authentication cookie and token + await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + context.Response.Cookies.Delete("Token"); + + if (IsApiRequest(context)) + { + context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; + await WriteJsonResponseAsync(context, new + { + success = false, + errorMessage = "Unauthorized" + }); + } + else + { + string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us"; + string returnUrl = $"{context.Request.Path}{context.Request.QueryString}"; + string loginUrl = $"/{culture}/auth/login?returnUrl={Uri.EscapeDataString(returnUrl)}"; + _logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl); + context.Response.Redirect(loginUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too + } + } + + /// + /// Builds a detailed error message from an . + /// + private string BuildErrorMessage(ApiException apiException) + { + StringBuilder errorMessage = new(); + + if (apiException.ProblemDetails is not null) + { + // only show the meaningful error message to the user + if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail)) + errorMessage.AppendLine($"{_stringLocalizer[apiException.ProblemDetails.Detail]}
"); + else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title)) + errorMessage.AppendLine($"{_stringLocalizer[apiException.ProblemDetails.Title]}
"); + + if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true) + if (errorsObj.ValueKind == JsonValueKind.Object) + foreach (JsonProperty error in errorsObj.EnumerateObject()) + { + _logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString())); + if (error.Value.ValueKind == JsonValueKind.Array) + foreach (JsonElement errorValue in error.Value.EnumerateArray()) + errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}
"); + } + } + else + { + _logger.LogError(apiException, "Generic API error occurred"); + errorMessage.AppendLine($"{apiException.Message}
"); + errorMessage.AppendLine($"{_stringLocalizer[apiException.HttpStatusCode.ToString()]}"); + } + return errorMessage.ToString(); + } + + /// + /// Checks if the current request is an API request. + /// + private static bool IsApiRequest(HttpContext context) + { + return context.Request.Headers.Accept.Any(x => x?.Contains("application/json") == true) || context.Request.Headers.XRequestedWith == "XMLHttpRequest"; + } + + /// + /// Writes a JSON response to the client. + /// + private static async Task WriteJsonResponseAsync(HttpContext context, object response) + { + context.Response.ContentType = "application/json"; + await context.Response.WriteAsJsonAsync(response); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/AddRoleRequestModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/AddRoleRequestModel.cs new file mode 100644 index 00000000..76b9c855 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/AddRoleRequestModel.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Authorization; + +/// +/// Represents the request model for adding an authorization role. +/// +/// The name of the role. +/// The collection or permissions of the role. +public record AddRoleRequestModel( + string? RoleName, + List? Permissions +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationRequirementModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationRequirementModel.cs index 33ad42f4..139981e2 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationRequirementModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationRequirementModel.cs @@ -13,7 +13,7 @@ public class AuthorizationRequirementModel /// /// The collection of roles required for accessing the resource. /// - public AuthorizationRole[]? Roles { get; set; } + public string[]? Roles { get; set; } /// /// The collection of permissions required for accessing the resource. diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs index 5e09bca3..d59c761d 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/GetAuthorizationResponseModel.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Enums.Authorization; using System; -using System.Collections.Generic; using System.Diagnostics; #endregion @@ -16,6 +15,6 @@ namespace Lumina.Presentation.Web.Common.Models.Authorization; [DebuggerDisplay("UserId: {UserId}")] public record GetAuthorizationResponse( Guid UserId, - AuthorizationRole[] Roles, + string[] Roles, AuthorizationPermission[] Permissions ); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs new file mode 100644 index 00000000..14de666f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/PermissionModel.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Authorization; +using System; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Authorization; + +/// +/// Represents a model for an authorization permission. +/// +/// The Id of the authorization permission. +/// The authorization permission. +public record PermissionModel( + Guid Id, + AuthorizationPermission PermissionName +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs new file mode 100644 index 00000000..aa41a538 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/RoleModel.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Authorization; + +/// +/// Represents a model for an authorization role. +/// +/// The Id of the authorization role. +/// The authorization role. +public record RoleModel( + Guid Id, + string RoleName +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs new file mode 100644 index 00000000..115e18a0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/RolePermissionsModel.cs @@ -0,0 +1,16 @@ +#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. +/// +/// The Id of the authorization role. +/// 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 new file mode 100644 index 00000000..c2cc74fe --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/UpdateRoleRequestModel.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 an existing authorization role. +/// +/// The Id of the role. +/// The name of the role. +/// The collection or permissions of the role. +public record UpdateRoleRequestModel( + Guid RoleId, + string? RoleName, + List? Permissions +); diff --git a/src/Lumina.Presentation.Web/Common/Models/Common/CachedResponseModel.cs b/src/Lumina.Presentation.Web/Common/Models/Common/CachedResponseModel.cs new file mode 100644 index 00000000..3c02aabe --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Common/CachedResponseModel.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Common; + +/// +/// Represents a cached HTTP response, including its content and status code. +/// +[DebuggerDisplay("StatusCode: {StatusCode}")] +public class CachedResponseModel +{ + /// + /// Gets or sets the content of the cached HTTP response. + /// + public string Content { get; set; } = string.Empty; + + /// + /// Gets or sets the HTTP status code of the cached response. + /// + public HttpStatusCode StatusCode { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs b/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs index d1fd275e..0d118442 100644 --- a/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedAuthorizationHandler.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.Common; using Microsoft.Extensions.Caching.Hybrid; using Microsoft.Extensions.Caching.Memory; using System; @@ -42,13 +43,19 @@ public class CachedAuthorizationHandler : DelegatingHandler if (!requestPath.EndsWith(AUTHORIZATION_ENDPOINT, StringComparison.OrdinalIgnoreCase)) return await base.SendAsync(request, cancellationToken); // otherwise, check the hybrid cache to see if there is a cached authorization - string response = await _hybridCache.GetOrCreateAsync( + CachedResponseModel response = await _hybridCache.GetOrCreateAsync( AUTHORIZATION_ENDPOINT, async (cancellationToken) => { // perform the actual API call if cache is empty or expired HttpResponseMessage result = await base.SendAsync(request, cancellationToken); - return await result.Content.ReadAsStringAsync(cancellationToken); + string content = await result.Content.ReadAsStringAsync(cancellationToken); + // cache both status code and content + return new CachedResponseModel + { + Content = content, + StatusCode = result.StatusCode + }; }, new HybridCacheEntryOptions() { @@ -56,9 +63,9 @@ public class CachedAuthorizationHandler : DelegatingHandler }, cancellationToken: cancellationToken ); - return new HttpResponseMessage(HttpStatusCode.OK) + return new HttpResponseMessage(response.StatusCode) { - Content = new StringContent(response) + Content = new StringContent(response.Content) }; } } diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs index 7b5e47b0..7542a8dd 100644 --- a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -10,6 +10,7 @@ public interface IUrlService /// /// The action name within the controller. /// The controller name. + /// Optional additional route values, like query parameters. /// An absolute URL to the specified action. - string? GetAbsoluteUrl(string action, string controller); + string? GetAbsoluteUrl(string action, string controller, object? additionalRouteValues = null); } diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs index b90d989d..00ef414e 100644 --- a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; using System; using System.Linq; +using System.Reflection; #endregion namespace Lumina.Presentation.Web.Common.Services; @@ -36,8 +37,9 @@ public class UrlService : IUrlService ///
/// The action name within the controller. /// The controller name. + /// Optional additional route values, like query parameters. /// An absolute URL to the specified action. - public string? GetAbsoluteUrl(string action, string controller) + public string? GetAbsoluteUrl(string action, string controller, object? additionalRouteValues = null) { HttpContext? httpContext = _httpContextAccessor.HttpContext; if (httpContext is null) @@ -48,16 +50,24 @@ public class UrlService : IUrlService ControllerActionDescriptor? controllerActionDescriptor = _actionDescriptorCollectionProvider .ActionDescriptors.Items .OfType() - .FirstOrDefault(ad => - ad.ControllerName.Equals(controller, StringComparison.OrdinalIgnoreCase) && - ad.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase)); + .FirstOrDefault(controllerActionDescription => + controllerActionDescription.ControllerName.Equals(controller, StringComparison.OrdinalIgnoreCase) && + controllerActionDescription.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase)); if (controllerActionDescriptor is null) return null; // check if the route template contains {culture} string? routeTemplate = controllerActionDescriptor.AttributeRouteInfo?.Template; bool needsCulture = routeTemplate?.Contains("{culture}") == true; + // merge culture and additional values + RouteValueDictionary routeValues = []; + if (needsCulture) + routeValues.Add("culture", culture); + if (additionalRouteValues is not null) + foreach (PropertyInfo prop in additionalRouteValues.GetType().GetProperties()) + routeValues.Add(prop.Name, prop.GetValue(additionalRouteValues)); + // create route values based on whether the controller is localized object values = needsCulture ? new { culture, action } : new { action }; - return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: values, scheme: scheme); + return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: routeValues, scheme: scheme); } } diff --git a/src/Lumina.Presentation.Web/Common/Utilities/ApiExceptionHandlingMiddlewareUtilities.cs b/src/Lumina.Presentation.Web/Common/Utilities/ApiExceptionHandlingMiddlewareUtilities.cs new file mode 100644 index 00000000..80bfe993 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Utilities/ApiExceptionHandlingMiddlewareUtilities.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Middlewares; +using Microsoft.AspNetCore.Builder; +#endregion + +namespace Lumina.Presentation.Web.Common.Utilities; + +/// +/// Extension methods for making it easier for to be added the middleware. +/// +public static class ApiExceptionHandlingMiddlewareUtilities +{ + /// + /// Adds the to the application's request pipeline. + /// Handles exception raised when the server API returns a problem details. + /// + /// The used to configure the application's request pipeline. + /// The for further configuration. + public static IApplicationBuilder UseApiExceptionHandling(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareExtensions.cs b/src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareUtilities.cs similarity index 90% rename from src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareExtensions.cs rename to src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareUtilities.cs index 107a1d45..5c2f636b 100644 --- a/src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareExtensions.cs +++ b/src/Lumina.Presentation.Web/Common/Utilities/CultureRedirectMiddlewareUtilities.cs @@ -8,8 +8,7 @@ namespace Lumina.Presentation.Web.Common.Utilities; /// /// Extension methods for making it easier for to be added the middleware. /// -// Extension method to make it easier to add the middleware -public static class CultureRedirectMiddlewareExtensions +public static class CultureRedirectMiddlewareUtilities { /// /// Adds the to the application's request pipeline. diff --git a/src/Lumina.Presentation.Web/Controllers/AdminController.cs b/src/Lumina.Presentation.Web/Controllers/AdminController.cs new file mode 100644 index 00000000..14c4c3b0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Controllers/AdminController.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Attributes; +using Lumina.Presentation.Web.Common.Models.Authorization; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Controllers; + +/// +/// Controller for administrator related operations. +/// +[Authorize] +[RequireRole("Admin")] +[Route("{culture}/admin")] +public class AdminController : Controller +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AdminController(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Displays the view for managing authorization roles. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("manage-roles")] + public async Task ManageRoles(CancellationToken cancellationToken) + { + // get the list of roles and permissions from the API + ViewData["roles"] = await _apiHttpClient.GetAsync($"roles/", cancellationToken).ConfigureAwait(false); + ViewData["rolePermissions"] = await _apiHttpClient.GetAsync($"permissions/", cancellationToken).ConfigureAwait(false); + return View(); + } + + /// + /// Displays the view for managing authorization permissions. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("manage-permissions")] + public async Task ManagePermissions(CancellationToken cancellationToken) + { + ViewData["Roles"] = await _apiHttpClient.GetAsync($"roles/", cancellationToken).ConfigureAwait(false); + return View(); + } + + /// + /// Gets the authorization permissions of a role identified by . + /// + /// The Id of the role for which to get the list of permissions. + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-permissions-by-role-id/{roleId}")] + public async Task GetPermissionsByRoleId(Guid roleId, CancellationToken cancellationToken) + { + RolePermissionsModel response = await _apiHttpClient.GetAsync($"roles/{roleId}/permissions", cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + + /// + /// Gets the collection of authorization roles. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("get-roles")] + public async Task GetRoles(CancellationToken cancellationToken) + { + RoleModel[] response = await _apiHttpClient.GetAsync($"roles/", cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + + /// + /// Creates an authorization role with the specified name and associated permissions. + /// + /// The model containing the data of the role to be created. + /// Cancellation token that can be used to stop the execution. + [HttpPost("create-role")] + public async Task CreateRole([FromBody] AddRoleRequestModel model, CancellationToken cancellationToken) + { + RolePermissionsModel response = await _apiHttpClient.PostAsync($"roles/", model, cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + + /// + /// Updates an authorization role with the specified name and associated permissions. + /// + /// The model containing the data of the role to be updated. + /// Cancellation token that can be used to stop the execution. + [HttpPost("update-role")] + public async Task UpdateRole([FromBody] UpdateRoleRequestModel model, CancellationToken cancellationToken) + { + RolePermissionsModel response = await _apiHttpClient.PutAsync($"roles/", model, cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + + /// + /// Deletes an authorization role. + /// + /// The Id of the role to be deleted. + /// Cancellation token that can be used to stop the execution. + [HttpDelete("delete-role/{roleId}")] + public async Task DeleteRole(Guid roleId, CancellationToken cancellationToken) + { + await _apiHttpClient.DeleteAsync($"roles/{roleId}", cancellationToken).ConfigureAwait(false); + return Json(new { success = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index db8b47ee..4ade8b1b 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -63,31 +63,31 @@ - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index bd7b38e9..1ce067a1 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -89,6 +89,7 @@ public class Program ServeUnknownFileTypes = true }); app.UseCultureRedirect(); // if the user attempts to go to a localized route without providing a culture, redirect to default culture + app.UseApiExceptionHandling(); // handle any problem details returned by the API app.UseRouting(); app.UseSession(); app.UseAuthentication(); diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.de-DE.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index ab237ad9..ba2e4042 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -192,6 +192,9 @@ Verschlüsselungsschlüssel muss eine Base64-Zeichenkette sein! + + Fehler beim Speichern der Autorisierungsrolle! + Fehler beim Speichern der Medienbibliothek! @@ -345,6 +348,9 @@ Sie sind nicht berechtigt, diesen Vorgang auszuführen! + + Die angegebene Ressource wurde nicht gefunden! + Kein Vorschaubild! @@ -390,6 +396,12 @@ Pfadliste darf nicht null sein! + + Die Berechtigungsliste darf nicht leer sein! + + + Die Berechtigungsliste darf nicht null sein! + Verlag darf maximal 100 Zeichen lang sein! @@ -426,18 +438,27 @@ Wiederveröffentlichungsjahr muss zwischen 1 und 9999 liegen! + + Rolle existiert bereits! + Rollenkategorie darf nicht leer sein! Rollenkategorie darf maximal 50 Zeichen lang sein! + + Rollen-ID darf nicht leer sein! + Rollenname darf nicht leer sein! Rollenname darf maximal 50 Zeichen lang sein! + + Rolle nicht gefunden + Stream-ID darf nicht leer sein! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.en-US.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 902c2169..97680230 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -192,6 +192,9 @@ Encryption secret key must be a Base64 string! + + Error persisting authorization role! + Error persisting media library! @@ -345,6 +348,9 @@ You are not authorized to perform this operation! + + Specified resource was not found! + No thumbnail! @@ -390,6 +396,12 @@ Paths list cannot be null! + + Permissions list cannot be empty! + + + Permissions list cannot be null! + Publisher must be maximum 100 characters long! @@ -426,18 +438,27 @@ Re-release year must be between 1 and 9999! + + Role already exists! + Role category cannot be empty! Role category must be maximum 50 characters long! + + Role Id cannot be empty! + Role name cannot be empty! Role name must be maximum 50 characters long! + + Role not found + Stream Id cannot be empty! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.es-ES.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index 680804b4..4fcd97b5 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -192,6 +192,9 @@ ¡La clave secreta de cifrado debe ser una cadena Base64! + + ¡Error al persistir el rol de autorización! + ¡Error al guardar la biblioteca multimedia! @@ -345,6 +348,9 @@ ¡No está autorizado para realizar esta operación! + + ¡El recurso especificado no fue encontrado! + ¡Sin miniatura! @@ -390,6 +396,12 @@ ¡La lista de rutas no puede ser nula! + + ¡La lista de permisos no puede estar vacía! + + + ¡La lista de permisos no puede ser nula! + ¡El nombre de la editorial debe tener máximo 100 caracteres! @@ -426,18 +438,27 @@ ¡El año de relanzamiento debe estar entre 1 y 9999! + + ¡El rol ya existe! + ¡La categoría del rol no puede estar vacía! ¡La categoría del rol debe tener máximo 50 caracteres! + + ¡El ID del rol no puede estar vacío! + ¡El nombre del rol no puede estar vacío! ¡El nombre del rol debe tener máximo 50 caracteres! + + Rol no encontrado + ¡El ID del flujo no puede estar vacío! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.fr-FR.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index f641dfc4..1105a663 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -192,6 +192,9 @@ La clé secrète de chiffrement doit être une chaîne Base64! + + Erreur lors de la persistance du rôle d'autorisation ! + Erreur lors de l'enregistrement de la bibliothèque multimédia! @@ -345,6 +348,9 @@ Vous n'êtes pas autorisé à effectuer cette opération! + + La ressource spécifiée n'a pas été trouvée ! + Pas de vignette ! @@ -390,6 +396,12 @@ La liste des chemins ne peut pas être nulle ! + + La liste des permissions ne peut pas être vide ! + + + La liste des permissions ne peut pas être nulle ! + Le nom de l'éditeur ne doit pas dépasser 100 caractères ! @@ -426,18 +438,27 @@ L'année de réédition doit être comprise entre 1 et 9999 ! + + Le rôle existe déjà ! + La catégorie du rôle ne peut pas être vide ! La catégorie du rôle ne doit pas dépasser 50 caractères ! + + L'ID du rôle ne peut pas être vide ! + Le nom du rôle ne peut pas être vide ! Le nom du rôle ne doit pas dépasser 50 caractères ! + + Rôle non trouvé + L'identifiant du flux ne peut pas être vide ! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.it-IT.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 78a68832..b84db79c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -192,6 +192,9 @@ La chiave segreta di crittografia deve essere una stringa Base64! + + Errore nel salvare il ruolo di autorizzazione! + Errore durante il salvataggio della libreria multimediale! @@ -345,6 +348,9 @@ Non sei autorizzato a eseguire questa operazione! + + La risorsa specificata non è stata trovata! + Nessuna miniatura! @@ -390,6 +396,12 @@ La lista dei percorsi non può essere nulla! + + L'elenco dei permessi non può essere vuoto! + + + L'elenco dei permessi non può essere nullo! + Il nome dell'editore deve essere lungo al massimo 100 caratteri! @@ -426,18 +438,27 @@ L'anno di ripubblicazione deve essere compreso tra 1 e 9999! + + Il ruolo esiste già! + La categoria del ruolo non può essere vuota! La categoria del ruolo deve essere lunga al massimo 50 caratteri! + + L'ID del ruolo non può essere vuoto! + Il nome del ruolo non può essere vuoto! Il nome del ruolo deve essere lungo al massimo 50 caratteri! + + Ruolo non trovato + L'ID del flusso non può essere vuoto! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ja-JP.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 693ae9c1..dfcdd212 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -192,6 +192,9 @@ 暗号化シークレットキーはBase64形式の文字列である必要があります! + + 認可ロールの保存中にエラーが発生しました! + メディアライブラリの保存に失敗しました! @@ -345,6 +348,9 @@ この操作を実行する権限がありません! + + 指定されたリソースが見つかりませんでした! + サムネイルがありません! @@ -390,6 +396,12 @@ パスリストをnullにすることはできません! + + 権限リストは空にできません! + + + 権限リストはnullにできません! + 出版社名は最大100文字までです! @@ -426,18 +438,27 @@ 再公開年は1から9999の間でなければなりません! + + ロールはすでに存在します! + 役割カテゴリを空にすることはできません! 役割カテゴリは最大50文字までです! + + ロールIDは空にできません! + 役割名を空にすることはできません! 役割名は最大50文字までです! + + ロールが見つかりません + ストリームIDを空にすることはできません! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 1b976a8f..fc587539 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -192,6 +192,9 @@ Encryption secret key must be a Base64 string! + + Error persisting authorization role! + Error persisting media library! @@ -345,6 +348,9 @@ You are not authorized to perform this operation! + + Specified resource was not found! + No thumbnail! @@ -390,6 +396,12 @@ Paths list cannot be null! + + Permissions list cannot be empty! + + + Permissions list cannot be null! + Publisher must be maximum 100 characters long! @@ -426,18 +438,27 @@ Re-release year must be between 1 and 9999! + + Role already exists! + Role category cannot be empty! Role category must be maximum 50 characters long! + + Role Id cannot be empty! + Role name cannot be empty! Role name must be maximum 50 characters long! + + Role not found + Stream Id cannot be empty! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ro-RO.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index 5af38c93..40a8e244 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -192,6 +192,9 @@ Cheia secretă de criptare trebuie să fie un șir Base64! + + Eroare la salvarea rolului de autorizare! + Eroare la salvarea bibliotecii media! @@ -345,6 +348,9 @@ Nu sunteți autorizat să efectuați această operațiune! + + Resursa specificată nu a fost găsită! + Fără pictograma! @@ -390,6 +396,12 @@ Lista de căi nu poate fi nulă! + + Lista de permisiuni nu poate fi goală! + + + Lista de permisiuni nu poate fi nulă! + Editura trebuie să aibă maximum 100 caractere! @@ -426,18 +438,27 @@ Anul relansării trebuie să fie între 1 și 9999! + + Rolul există deja! + Categoria rolului nu poate fi goală! Categoria rolului trebuie să aibă maximum 50 caractere! + + ID-ul rolului nu poate fi gol! + Numele rolului nu poate fi gol! Numele rolului trebuie să aibă maximum 50 caractere! + + Rolul nu a fost găsit + ID-ul fluxului nu poate fi gol! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ru-RU.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index 6b95aa36..0cbd1c0c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -192,6 +192,9 @@ Секретный ключ шифрования должен быть строкой в формате Base64! + + Ошибка при сохранении роли авторизации! + Ошибка при сохранении медиатеки! @@ -345,6 +348,9 @@ У вас нет прав для выполнения этой операции! + + Указанный ресурс не найден! + Нет миниатюры! @@ -390,6 +396,12 @@ Список путей не может быть пустым! + + Список разрешений не может быть пустым! + + + Список разрешений не может быть пустым! + Название издательства не должно превышать 100 символов! @@ -426,18 +438,27 @@ Год переиздания должен быть между 1 и 9999! + + Роль уже существует! + Категория роли не может быть пустой! Категория роли не должна превышать 50 символов! + + Идентификатор роли не может быть пустым! + Название роли не может быть пустым! Название роли не должно превышать 50 символов! + + Роль не найдена + Идентификатор потока не может быть пустым! diff --git a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx similarity index 96% rename from src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.zh-CN.resx rename to src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index ed73a9f9..9332a998 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Filters/ApiExceptionFilter.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -192,6 +192,9 @@ 加密密钥必须是Base64字符串! + + 持久化授权角色时出错! + 保存媒体库时出错! @@ -345,6 +348,9 @@ 您无权执行此操作! + + 指定的资源未找到! + 没有缩略图! @@ -390,6 +396,12 @@ 路径列表不能为空! + + 权限列表不能为空! + + + 权限列表不能为空! + 出版社名称最多只能有100个字符! @@ -432,12 +444,18 @@ 角色类别最多只能有50个字符! + + 角色ID不能为空! + 角色名称不能为空! 角色名称最多只能有50个字符! + + 角色未找到 + 流ID不能为空! diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.de-DE.resx new file mode 100644 index 00000000..000d1929 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.de-DE.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Rolle erstellen + + + Rolle löschen + + + Die Rolle wurde erstellt! + + + Die Rolle wurde gelöscht! + + + Rollenname + + + Rollen + + + Die Rolle wurde aktualisiert! + + + Wählen Sie eine Rolle + + + Rolle aktualisieren + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.en-US.resx new file mode 100644 index 00000000..deb2f415 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.en-US.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Create role + + + Delete role + + + The role has been created! + + + The role has been deleted! + + + Role name + + + Roles + + + The role has been updated! + + + Select a role + + + Update role + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.es-ES.resx new file mode 100644 index 00000000..7f9ce17f --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.es-ES.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Crear un rol + + + Eliminar rol + + + ¡El rol ha sido creado! + + + ¡El rol ha sido eliminado! + + + Nombre del rol + + + Roles + + + ¡El rol ha sido actualizado! + + + Selecciona un rol + + + Actualizar rol + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.fr-FR.resx new file mode 100644 index 00000000..1df32972 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.fr-FR.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Créer un rôle + + + Supprimer le rôle + + + Le rôle a été créé ! + + + Le rôle a été supprimé ! + + + Nom du rôle + + + Rôles + + + Le rôle a été mis à jour ! + + + Sélectionnez un rôle + + + Mettre à jour le rôle + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.it-IT.resx new file mode 100644 index 00000000..9ce689f0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.it-IT.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Creare un ruolo + + + Elimina ruolo + + + Il ruolo è stato creato! + + + Il ruolo è stato eliminato! + + + Nome del ruolo + + + Ruoli + + + Il ruolo è stato aggiornato! + + + Seleziona un ruolo + + + Aggiorna ruolo + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ja-JP.resx new file mode 100644 index 00000000..11e06e6f --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ja-JP.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/ManageRoles.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.resx new file mode 100644 index 00000000..deb2f415 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Create role + + + Delete role + + + The role has been created! + + + The role has been deleted! + + + Role name + + + Roles + + + The role has been updated! + + + Select a role + + + Update role + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ro-RO.resx new file mode 100644 index 00000000..147df845 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ro-RO.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Creare rol + + + Ștergere rol + + + Rolul a fost creat! + + + Rolul a fost șters! + + + Numele rolului + + + Roluri + + + Rolul a fost actualizat! + + + Selectare rol + + + Actualizare rol + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ru-RU.resx new file mode 100644 index 00000000..94eb9c57 --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.ru-RU.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/ManageRoles.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.zh-CN.resx new file mode 100644 index 00000000..64d5a85a --- /dev/null +++ b/src/Lumina.Presentation.Web/Resources/Views/Admin/ManageRoles.zh-CN.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Shared/_Layout.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.de-DE.resx index e5104bb3..08ab2b5c 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.de-DE.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Navigation fehlgeschlagen! + Vollhöhe Umschalten diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.en-US.resx index 640d4380..81fc5d9b 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.en-US.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Navigation failed! + Toggle Full Height diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.es-ES.resx index b20fef89..9cab8f6e 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.es-ES.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + ¡Navegación fallida! + Alternar Altura Completa diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.fr-FR.resx index 371b4408..ea280d95 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.fr-FR.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Navigation échouée ! + Basculer Hauteur Complète diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.it-IT.resx index 0b15c1cb..f0352b09 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.it-IT.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Navigazione fallita! + Attiva/Disattiva Altezza Piena diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ja-JP.resx index d6386d2b..b0acd12c 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ja-JP.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + ナビゲーションに失敗しました! + 全高表示切替 diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.resx index 640d4380..81fc5d9b 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Navigation failed! + Toggle Full Height diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ro-RO.resx index 3046887c..e9909c0d 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ro-RO.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Navigarea a eșuat! + Comutare Înălțime Completă diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ru-RU.resx index b3ab644d..acd3b566 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_Layout.ru-RU.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Навигация не удалась! + Переключить Полную Высоту diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx index 53ea41fc..b2360164 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.de-DE.resx @@ -189,6 +189,9 @@ Registrieren + + Berechtigungen verwalten + Werkzeuge @@ -201,4 +204,7 @@ Schriftliche Inhalte - \ No newline at end of file + + Rollen verwalten + + diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx index 058fbb75..ac280756 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.en-US.resx @@ -189,6 +189,9 @@ Register + + Manage permissions + Tools @@ -201,4 +204,7 @@ Written Content + + Manage roles + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx index ebeae0e4..0f8f73b5 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.es-ES.resx @@ -189,6 +189,9 @@ Registrarse + + Administrar permisos + Herramientas @@ -201,4 +204,7 @@ Contenido Escrito + + Administrar roles + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx index dab109ab..4f5902a6 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.fr-FR.resx @@ -189,6 +189,9 @@ S'inscrire + + Gérer les permissions + Outils @@ -201,4 +204,7 @@ Contenu Écrit + + Gérer les rôles + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx index 090f8ab6..aadc0942 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.it-IT.resx @@ -189,6 +189,9 @@ Registrati + + Gestire i permessi + Strumenti @@ -201,4 +204,7 @@ Contenuto Scritto + + Gestire i ruoli + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx index 8b85d5b4..fa4558e1 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ja-JP.resx @@ -189,6 +189,9 @@ 登録 + + 権限を管理する + ツール @@ -201,4 +204,7 @@ 文字コンテンツ + + ロールを管理する + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx index 058fbb75..ac280756 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.resx @@ -189,6 +189,9 @@ Register + + Manage permissions + Tools @@ -201,4 +204,7 @@ Written Content + + Manage roles + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx index b72e7ec2..599c16fc 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ro-RO.resx @@ -189,6 +189,9 @@ Înregistrare + + Gestionare permisiuni + Unelte @@ -201,4 +204,7 @@ Conținut Scris + + Gestionare roluri + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx index f155e0d0..cac9ba6d 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.ru-RU.resx @@ -189,6 +189,9 @@ Регистрация + + Управление разрешениями + Инструменты @@ -201,4 +204,7 @@ Письменный Контент + + Управление ролями + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx index 06f759a8..10340b91 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Shared/_NavMenu.zh-CN.resx @@ -189,6 +189,9 @@ 注册 + + 管理权限 + 工具 @@ -201,4 +204,7 @@ 文字内容 + + 管理角色 + \ 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 new file mode 100644 index 00000000..b8c43d98 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml @@ -0,0 +1,101 @@ +@* +/admin/manage-permissions/ +*@ + +@using Lumina.Presentation.Web.Common.Models.Authorization +@using Microsoft.AspNetCore.Mvc.Localization + +@{ + var roles = ViewData["roles"] as RoleModel[]; + var rolePermissions = ViewData["rolePermissions"] as PermissionModel[]; +} + +@inject IViewLocalizer _localizer + +
+ + +
+ + +
+
+ + +
+
+
@_localizer["SelectARole"]
+ @if (roles is not null) + { + @for (int i = 0; i < roles.Length; i++) + { +
@roles[i].RoleName
+ } + } +
+
+
+ + +
+ + +
+ + +
+
+
+ @if (rolePermissions is not null) + { + @foreach (var rolePermission in rolePermissions) + { +
+ +
+ } + } +
+
+
+ + +
+ + +
+
+ +@*
+
+
+ @Html.AntiForgeryToken() + @{ +
+
+
+ + +
+
+
@_localizer["None"]
+ @foreach (var item in aa!) + { +
@_localizer[item.ToString()]
+ } +
+
+
+ } +

a

+ +
+
*@ diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css b/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css new file mode 100644 index 00000000..5f282702 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Admin/ManagePermissions.cshtml.css @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml b/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml new file mode 100644 index 00000000..083ba10e --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml @@ -0,0 +1,237 @@ +@* +/admin/manage-roles/ +*@ + +@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[]; + // 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++) + { +
@roles[i].RoleName
+ } + } +
+
+
+ + +
+ + +
+ + +
+
+
+
+ @if (rolePermissions is not null) + { + @foreach (var rolePermission in rolePermissions) + { +
+ +
+ } + } +
+
+
+
+ + +
+ + +
+
+
+ +@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml.css b/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml.css new file mode 100644 index 00000000..8703767a --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Admin/ManageRoles.cshtml.css @@ -0,0 +1,46 @@ +#authorization-roles-container { + display: flex; + margin: auto; + width: 100%; + height: 100%; + flex-direction: column; + flex-wrap: nowrap; +} + +#authorization-roles-permissions-container { + flex-grow: 1; + min-width: 135px; + min-height: 0px; +} + +#authorization-roles-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-roles-permissions-scroll { + background-color: #232323; + margin: auto; + width: 100%; + height: 100%; +} + +#authorization-roles-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/Auth/AccessDenied.cshtml b/src/Lumina.Presentation.Web/Views/Auth/AccessDenied.cshtml index 3c9904ed..07ff0ba5 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/AccessDenied.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/AccessDenied.cshtml @@ -6,9 +6,12 @@ @inject IViewLocalizer _localizer -
-
-
-

@_localizer["NotAllowedToAccessResource"]

+
+
+
+
+
+

@_localizer["NotAllowedToAccessResource"]

+
diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml index c5970e10..390e4047 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml @@ -16,68 +16,71 @@ @model ChangePasswordRequestModel -
-
-
- @Html.AntiForgeryToken() - -
- -
-
- - *: +
+
+
+
+ + @Html.AntiForgeryToken() + +
+ +
+
+ + *: +
+
+ +
+ @_localizer["DescriptionCurrentPassword"]
-
- + +
+
+ + *: +
+
+ +
+ @_localizer["DescriptionNewPassword"]
- @_localizer["DescriptionCurrentPassword"] -
- -
-
- - *: + +
+
+ + *: +
+
+ +
+ @_localizer["DescriptionNewPasswordConfirm"] +
+
+
-
- -
- @_localizer["DescriptionNewPassword"] -
- -
-
- - *: -
-
- -
- @_localizer["DescriptionNewPasswordConfirm"] -
-
-
+ + +
+
- - -
-
@section Scripts {
diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml index 9183fa2e..9cd043c8 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -1,8 +1,12 @@ +@using Lumina.Presentation.Web.Common.Authorization +@using Lumina.Presentation.Web.Common.Enums.Authorization @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization +@using System.Threading @inject IUrlService _urlService @inject IViewLocalizer _localizer +@inject IAuthorizationService _auth