Merge pull request #85 from BinaryAlley/feature/add-authorization-role-admin-dashboard

Adds authorization roles administrator dashboard
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-12-18 13:27:45 +02:00
commit b2acd9653b
191 files changed
+6193 -810

No files matched your search

@@ -24,11 +24,6 @@ public class PermissionEntity : IStorageEntity, IAuditableEntity
/// </summary>
public required AuthorizationPermission PermissionName { get; init; }
/// <summary>
/// Gets the description of the permission.
/// </summary>
public string? PermissionDescription { get; set; }
/// <summary>
/// Gets or sets the collection of role permission associations that include this permission.
/// </summary>
@@ -42,12 +37,12 @@ public class PermissionEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
public Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
@@ -12,7 +12,7 @@ namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// Repository entity for a permission in the authorization system.
/// </summary>
[DebuggerDisplay("RoleName: {RoleName}")]
public class RoleEntity : IStorageEntity
public class RoleEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the role.
@@ -22,12 +22,7 @@ public class RoleEntity : IStorageEntity
/// <summary>
/// Gets the name of the role.
/// </summary>
public required AuthorizationRole RoleName { get; init; }
/// <summary>
/// Gets or sets the description of the role.
/// </summary>
public string? RoleDescription { get; set; }
public required string RoleName { get; init; }
/// <summary>
/// Gets or sets the collection of user roles associations that include this role.
@@ -42,12 +37,12 @@ public class RoleEntity : IStorageEntity
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
public Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
@@ -40,12 +40,12 @@ public class RolePermissionEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
public Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
@@ -8,7 +8,7 @@ using System.Diagnostics;
namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// <summary>
/// Data Transfer object containing all the authorization info of a user.
/// Data Transfer Object containing all the authorization info of a user.
/// </summary>
[DebuggerDisplay("UserId: {UserId}")]
public class UserAuthorizationEntity
@@ -21,7 +21,7 @@ public class UserAuthorizationEntity
/// <summary>
/// Gets the collection of roles associated to the user.
/// </summary>
public required IReadOnlySet<AuthorizationRole> Roles { get; init; }
public required IReadOnlySet<string> Roles { get; init; }
/// <summary>
/// Gets the collection of permissions associated to the user.
@@ -41,12 +41,12 @@ public class UserPermissionEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
public Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
@@ -41,12 +41,12 @@ public class UserRoleEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
public Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
@@ -63,12 +63,12 @@ public class UserEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
public Guid CreatedBy { get; set; }
/// <summary>
/// Gets the optional time and date when the entity was updated.
@@ -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<PermissionEntity>,
IInsertRepositoryAction<PermissionEntity>,
IGetAllRepositoryAction<PermissionEntity>
{
/// <summary>
/// Gets all permissions that have their Id match an Id in <paramref name="ids"/> from the storage medium.
/// </summary>
/// <param name="ids">The list of Ids of the permissions to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PermissionEntity"/>, or an error.</returns>
Task<ErrorOr<IEnumerable<PermissionEntity>>> GetByIdsAsync(IEnumerable<Guid> ids, CancellationToken cancellationToken);
}
@@ -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.
/// </summary>
public interface IRoleRepository : IRepository<RoleEntity>,
IGetByIdRepositoryAction<RoleEntity, Guid>,
IGetAllRepositoryAction<RoleEntity>,
IInsertRepositoryAction<RoleEntity>,
IGetAllRepositoryAction<RoleEntity>
IUpdateRepositoryAction<RoleEntity>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets a role identified by <paramref name="roleType"/> from the repository, if it exists.
@@ -23,5 +26,5 @@ public interface IRoleRepository : IRepository<RoleEntity>,
/// <param name="roleType">The type of role to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="RoleEntity"/> if found, or an error.</returns>
Task<ErrorOr<RoleEntity?>> GetByNameAsync(AuthorizationRole roleType, CancellationToken cancellationToken);
Task<ErrorOr<RoleEntity?>> GetByNameAsync(string roleType, CancellationToken cancellationToken);
}
@@ -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));
}
}
@@ -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));
}
}
@@ -31,7 +31,7 @@ public interface IAuthorizationService
/// <param name="role">The role to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the user is in the specified role, <see langword="false"/> otherwise.</returns>
Task<bool> IsInRoleAsync(Guid userId, AuthorizationRole role, CancellationToken cancellationToken);
Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken);
/// <summary>
/// Evaluates whether the specified user meets the conditions defined in the specified authorization policy.
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="AddRoleRequest"/>.
/// </summary>
public static class AddRoleRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="AddRoleCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static AddRoleCommand ToCommand(this AddRoleRequest request)
{
return new AddRoleCommand(
request.RoleName!,
request.Permissions!
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="UpdateRoleRequest"/>.
/// </summary>
public static class DeleteRoleRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="DeleteRoleCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static DeleteRoleCommand ToCommand(this DeleteRoleRequest request)
{
return new DeleteRoleCommand(
request.RoleId!.Value
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="GetRolePermissionsRequest"/>.
/// </summary>
public static class GetRolePermissionsRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetRolePermissionsQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetRolePermissionsQuery ToQuery(this GetRolePermissionsRequest request)
{
return new GetRolePermissionsQuery(
request.RoleId
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="PermissionEntity"/>.
/// </summary>
public static class PermissionEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="PermissionResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static PermissionResponse ToResponse(this PermissionEntity repositoryEntity)
{
return new PermissionResponse(
repositoryEntity.Id,
repositoryEntity.PermissionName
);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="PermissionResponse"/>.
/// </summary>
/// <param name="repositoryEntities">The repository entities to be converted.</param>
/// <returns>The converted responses.</returns>
public static IEnumerable<PermissionResponse> ToResponses(this IEnumerable<PermissionEntity> repositoryEntities)
{
return repositoryEntities.Select(permission => permission.ToResponse());
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="RoleEntity"/>.
/// </summary>
public static class RoleEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="RoleResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static RoleResponse ToResponse(this RoleEntity repositoryEntity)
{
return new RoleResponse(
repositoryEntity.Id,
repositoryEntity.RoleName
);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="RoleResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static RolePermissionsResponse ToRolePermissionsResponse(this RoleEntity repositoryEntity)
{
return new RolePermissionsResponse(
new RoleDto(repositoryEntity.Id, repositoryEntity.RoleName),
repositoryEntity.RolePermissions.Select(rolePermission => rolePermission.ToResponse()).ToArray()
);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="RoleResponse"/>.
/// </summary>
/// <param name="repositoryEntities">The repository entities to be converted.</param>
/// <returns>The converted responses.</returns>
public static IEnumerable<RoleResponse> ToResponses(this IEnumerable<RoleEntity> repositoryEntities)
{
return repositoryEntities.Select(role => role.ToResponse());
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="RolePermissionEntity"/>.
/// </summary>
public static class RolePermissionEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="RolePermissionsResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static PermissionDto ToResponse(this RolePermissionEntity repositoryEntity)
{
return new PermissionDto(
repositoryEntity.PermissionId,
repositoryEntity.Permission.PermissionName
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="UpdateRoleRequest"/>.
/// </summary>
public static class UpdateRoleRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="UpdateRoleCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static UpdateRoleCommand ToCommand(this UpdateRoleRequest request)
{
return new UpdateRoleCommand(
request.RoleId!.Value,
request.RoleName!,
request.Permissions!
);
}
}
@@ -11,16 +11,16 @@ namespace Lumina.Application.Common.Mapping.Authorization;
public static class UserAuthorizationEntityMapping
{
/// <summary>
/// Converts <paramref name="infrastructureEntity"/> to <see cref="GetAuthorizationResponse"/>.
/// Converts <paramref name="repositoryEntity"/> to <see cref="AuthorizationResponse"/>.
/// </summary>
/// <param name="infrastructureEntity">The infrastructure entity to be converted.</param>
/// <param name="repositoryEntity">The infrastructure entity to be converted.</param>
/// <returns>The converted response.</returns>
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
);
}
}
@@ -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;
/// <summary>
/// Query for retrieving the list of authorization permissions.
/// </summary>
public record GetPermissionsQuery : IRequest<ErrorOr<IEnumerable<PermissionResponse>>>;
@@ -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;
/// <summary>
/// Handler for the query to retrieve the list of authorization permissions.
/// </summary>
public class GetPermissionsQueryHandler : IRequestHandler<GetPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IPermissionRepository _permissionRepository;
/// <summary>
/// Initializes a new instance of the <see cref="GetPermissionsQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_permissionRepository = unitOfWork.GetRepository<IPermissionRepository>();
}
/// <summary>
/// Handles the query to retrieve the list of authorization permissions.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PermissionResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<PermissionResponse>>> 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<IEnumerable<PermissionEntity>> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getPermissionsResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors);
}
}
@@ -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;
/// <summary>
/// Command for adding an authorization role.
/// </summary>
/// <param name="RoleName">The name of the role.</param>
/// <param name="Permissions">The collection or permissions of the role.</param>
[DebuggerDisplay("RoleName: {RoleName}")]
public record AddRoleCommand(
string RoleName,
List<Guid> Permissions
) : IRequest<ErrorOr<RolePermissionsResponse>>;
@@ -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;
/// <summary>
/// Handler for the command to add an authorization role.
/// </summary>
public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ErrorOr<RolePermissionsResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
/// <summary>
/// Initializes a new instance of the <see cref="AddRoleCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
}
/// <summary>
/// Handles the command to add an authorization role.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RolePermissionsResponse>> 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<IRoleRepository>();
// 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<Created> 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<RoleEntity?> 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();
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="AddRoleCommand"/>.
/// </summary>
public class AddRoleCommandValidator : AbstractValidator<AddRoleCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddRoleCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Command for deleting an authorization role.
/// </summary>
/// <param name="RoleId">The Id of the role.</param>
[DebuggerDisplay("RoleId: {RoleId}")]
public record DeleteRoleCommand(
Guid RoleId
) : IRequest<ErrorOr<Deleted>>;
@@ -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;
/// <summary>
/// Handler for the command to delete an authorization role.
/// </summary>
public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, ErrorOr<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteRoleCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
}
/// <summary>
/// Handles the command to delete an authorization role.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully deleted <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<Deleted>> 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<IRoleRepository>();
ErrorOr<RoleEntity?> 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<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
if (deleteRoleResult.IsError)
return deleteRoleResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return deleteRoleResult.Value;
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteRoleCommand"/>.
/// </summary>
public class DeleteRoleCommandValidator : AbstractValidator<DeleteRoleCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteRoleCommandValidator"/> class.
/// </summary>
public DeleteRoleCommandValidator()
{
RuleFor(x => x.RoleId)
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
}
}
@@ -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;
/// <summary>
/// Command for updating an authorization role.
/// </summary>
/// <param name="RoleId">The Id of the role.</param>
/// <param name="RoleName">The name of the role.</param>
/// <param name="Permissions">The collection or permissions of the role.</param>
[DebuggerDisplay("RoleName: {RoleName}")]
public record UpdateRoleCommand(
Guid RoleId,
string RoleName,
List<Guid> Permissions
) : IRequest<ErrorOr<RolePermissionsResponse>>;
@@ -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;
/// <summary>
/// Handler for the command to update an authorization role.
/// </summary>
public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ErrorOr<RolePermissionsResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateRoleCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
}
/// <summary>
/// Handles the command to update an authorization role.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RolePermissionsResponse>> 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<IRoleRepository>();
// 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<Updated> 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<RoleEntity?> 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();
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateRoleCommand"/>.
/// </summary>
public class UpdateRoleCommandValidator : AbstractValidator<UpdateRoleCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateRoleCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Query for getting the authorization permissions of a role identified by <paramref name="RoleId"/>.
/// </summary>
/// <param name="RoleId">The Id of the authorization role for which to get the list of permissions.</param>
[DebuggerDisplay("RoleId: {RoleId}")]
public record GetRolePermissionsQuery(
Guid RoleId
) : IRequest<ErrorOr<RolePermissionsResponse>>;
@@ -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;
/// <summary>
/// Handler for the query to retrieve the list of authorization permissions for a role.
/// </summary>
public class GetRolePermissionsQueryHandler : IRequestHandler<GetRolePermissionsQuery, ErrorOr<RolePermissionsResponse>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IRoleRepository _roleRepository;
/// <summary>
/// Initializes a new instance of the <see cref="GetRolePermissionsQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
}
/// <summary>
/// Handles the query to retrieve the list of authorization permissions for a role.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RolePermissionsResponse>> 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<RoleEntity?> 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();
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="GetRolePermissionsQuery"/>.
/// </summary>
public class GetRolePermissionsQueryValidator : AbstractValidator<GetRolePermissionsQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetRolePermissionsQueryValidator"/> class.
/// </summary>
public GetRolePermissionsQueryValidator()
{
RuleFor(x => x.RoleId)
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
}
}
@@ -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;
/// <summary>
/// Query for retrieving the list of authorization roles.
/// </summary>
public record GetRolesQuery() : IRequest<ErrorOr<IEnumerable<RoleResponse>>>;
@@ -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;
/// <summary>
/// Handler for the query to retrieve the list of authorization roles.
/// </summary>
public class GetRolesQueryHandler : IRequestHandler<GetRolesQuery, ErrorOr<IEnumerable<RoleResponse>>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IRoleRepository _roleRepository;
/// <summary>
/// Initializes a new instance of the <see cref="GetRolesQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetRolesQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
}
/// <summary>
/// Handles the query to retrieve the list of authorization roles.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<RoleResponse>>> 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<IEnumerable<RoleEntity>> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getRolesResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors);
}
}
@@ -38,7 +38,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, E
/// </returns>
public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -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<GetDirectoryTreeQuer
/// </returns>
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> GetDrives()
{
ErrorOr<IEnumerable<FileSystemItem>> driveResult = _driveService.GetDrives();
if (driveResult.IsError)
return driveResult.Errors;
return ErrorOrFactory.From(driveResult.Value.ToTreeNodeResponses());
ErrorOr<IEnumerable<FileSystemItem>> getDrivesResult = _driveService.GetDrives();
if (getDrivesResult.IsError)
return getDrivesResult.Errors;
return ErrorOrFactory.From(getDrivesResult.Value.ToTreeNodeResponses());
}
/// <summary>
@@ -138,11 +138,11 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles, bool includeHiddenElements)
{
// get subdirectories under the current node's path
ErrorOr<IEnumerable<Directory>> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path, includeHiddenElements);
if (subDirectoriesResult.IsError)
return subDirectoriesResult.Errors;
ErrorOr<IEnumerable<Directory>> 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<GetDirectoryTreeQuer
if (includeFiles)
{
// get files under the current node's path
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(node.Path, includeHiddenElements);
if (filesResult.IsError)
return filesResult.Errors;
ErrorOr<IEnumerable<File>> 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()
{
@@ -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<GetTreeDirectories
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
}
}
@@ -38,7 +38,7 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemItem>> result = _driveService.GetDrives();
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors));
ErrorOr<IEnumerable<FileSystemItem>> getDrivesResult = _driveService.GetDrives();
return ValueTask.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors));
}
}
@@ -38,7 +38,7 @@ public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -38,7 +38,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, Error
/// </returns>
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
}
}
@@ -36,7 +36,7 @@ public class CombinePathCommandHandler : IRequestHandler<CombinePathCommand, Err
/// </returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(CombinePathCommand request, CancellationToken cancellationToken)
{
ErrorOr<string> result = _pathService.CombinePath(request.OriginalPath!, request.NewPath!);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors));
ErrorOr<string> combinePathResult = _pathService.CombinePath(request.OriginalPath!, request.NewPath!);
return ValueTask.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors));
}
}
@@ -38,7 +38,7 @@ public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr
/// </returns>
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegment>> result = _pathService.ParsePath(request.Path!);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
ErrorOr<IEnumerable<PathSegment>> parsePathResult = _pathService.ParsePath(request.Path!);
return ValueTask.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -38,7 +38,7 @@ public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, Err
/// </returns>
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(GetPathParentQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegment>> result = _pathService.GoUpOneLevel(request.Path!);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
ErrorOr<IEnumerable<PathSegment>> goUpOneLevelResult = _pathService.GoUpOneLevel(request.Path!);
return ValueTask.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
@@ -35,7 +35,7 @@ public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the root of the specified path, or an error.</returns>
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken)
{
ErrorOr<PathSegment> result = _pathService.GetPathRoot(request.Path!);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
ErrorOr<PathSegment> getPathRootResult = _pathService.GetPathRoot(request.Path!);
return ValueTask.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
}
}
@@ -35,7 +35,7 @@ public class GetThumbnailQueryHandler : IRequestHandler<GetThumbnailQuery, Error
/// <returns>An <see cref="ErrorOr{T}"/> containing either a thumbnail, or an error.</returns>
public async ValueTask<ErrorOr<ThumbnailResponse>> Handle(GetThumbnailQuery request, CancellationToken cancellationToken)
{
ErrorOr<Thumbnail> result = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken);
return await ValueTask.FromResult(result.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors));
ErrorOr<Thumbnail> getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken);
return await ValueTask.FromResult(getThumbnailResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors));
}
}
@@ -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<SetupApplicationCo
{
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<IEnumerable<UserEntity>> selectUserResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (selectUserResult.IsError)
return selectUserResult.Errors;
else if (selectUserResult.Value.Any())
ErrorOr<IEnumerable<UserEntity>> 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;
@@ -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<CheckInitializati
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
// if the repository reports an error, or there are no users, the application has not been initialized
ErrorOr<IEnumerable<UserEntity>> resultSelectUser = await userRepository.GetAllAsync(cancellationToken);
if (!resultSelectUser.IsError)
return new InitializationResponse(resultSelectUser.Value.Any());
ErrorOr<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken);
if (!selectUsersResult.IsError)
return new InitializationResponse(selectUsersResult.Value.Any());
return new InitializationResponse(false);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System;
@@ -62,11 +62,11 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
return insertLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// retrieve the newly saved media library from the persistence medium and return it
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (retrievedLibraryResult.IsError)
return retrievedLibraryResult.Errors;
if (retrievedLibraryResult.Value is null)
ErrorOr<LibraryEntity?> 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();
}
}
@@ -46,13 +46,13 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
{
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
if (resultGetLibrary.IsError)
return resultGetLibrary.Errors;
else if (resultGetLibrary.Value is null)
ErrorOr<LibraryEntity?> 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<UpdateLibraryCommand,
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// retrieve the updated media library from the persistence medium and return it
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (retrievedLibraryResult.IsError)
return retrievedLibraryResult.Errors;
if (retrievedLibraryResult.Value is null)
ErrorOr<LibraryEntity?> 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();
}
}
@@ -12,8 +12,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
/// Query for getting a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library to get.</param>
/// <param name="UserId">The Id os the user requesting the media library.</param>
[DebuggerDisplay("Path: {Path}")]
/// <param name="UserId">The Id of the user requesting the media library.</param>
[DebuggerDisplay("Id: {Id}")]
public record GetLibraryQuery(
Guid Id,
Guid UserId
@@ -42,14 +42,14 @@ public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<L
public async ValueTask<ErrorOr<LibraryResponse>> Handle(GetLibraryQuery request, CancellationToken cancellationToken)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
if (resultGetLibrary.IsError)
return resultGetLibrary.Errors;
else if (resultGetLibrary.Value is null)
ErrorOr<LibraryEntity?> 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();
}
}
@@ -46,22 +46,22 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
ErrorOr<UserEntity?> 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<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
ErrorOr<Updated> 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);
}
@@ -56,29 +56,29 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
ErrorOr<UserEntity?> 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<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
ErrorOr<Updated> 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);
}
@@ -65,10 +65,10 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
{
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is not null)
ErrorOr<UserEntity?> 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<RegisterUserCommand, E
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (resultInsertUser.IsError)
return resultInsertUser.Errors;
ErrorOr<Created> 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
@@ -65,29 +65,29 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
ErrorOr<UserEntity?> 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<LoginUserQuery, ErrorOr<Log
return Errors.Authentication.InvalidUsernameOrPassword;
}
// create the JWT token
string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username);
string token = _jwtTokenGenerator.GenerateToken(getUserResult.Value.Id.ToString(), getUserResult.Value.Username);
// check if the user uses TOTP
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
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;
return new LoginResponse(resultSelectUser.Value.Id, resultSelectUser.Value.Username, token, usesTotp);
return new LoginResponse(getUserResult.Value.Id, getUserResult.Value.Username, token, usesTotp);
}
}
@@ -15,4 +15,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho
[DebuggerDisplay("UserId: {UserId}")]
public record GetAuthorizationQuery(
Guid? UserId
) : IRequest<ErrorOr<GetAuthorizationResponse>>;
) : IRequest<ErrorOr<AuthorizationResponse>>;
@@ -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
/// <summary>
/// Handler for the query to retrieve the authorization roles and permissions of an account.
/// </summary>
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<GetAuthorizationResponse>>
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<AuthorizationResponse>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationService"/> class.
/// Initializes a new instance of the <see cref="GetAuthorizationQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
@@ -40,22 +39,22 @@ public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuer
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="GetAuthorizationResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="AuthorizationResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<GetAuthorizationResponse>> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken)
public async ValueTask<ErrorOr<AuthorizationResponse>> 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<UserAuthorizationEntity> resultGetCurrentUserPermission = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false);
if (resultGetCurrentUserPermission.IsError)
return resultGetCurrentUserPermission.Errors;
ErrorOr<UserAuthorizationEntity> 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<UserAuthorizationEntity> resultGetUserPermission = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
return resultGetUserPermission.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors);
ErrorOr<UserAuthorizationEntity> getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
return getUserPermissionResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors);
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.DTO.Authentication;
/// <summary>
/// Data transfer object for an authorization permission.
/// </summary>
/// <param name="Id">The Id of the permission.</param>
/// <param name="PermissionName">The name of the permission.</param>
[DebuggerDisplay("Id: {Id}, PermissionName: {PermissionName}")]
public record PermissionDto(
Guid Id,
AuthorizationPermission PermissionName
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.DTO.Authentication;
/// <summary>
/// Data transfer object for an authorization role.
/// </summary>
/// <param name="Id">The Id of the role.</param>
/// <param name="RoleName">The name of the role.</param>
[DebuggerDisplay("Id: {Id}, RoleName: {RoleName}")]
public record RoleDto(
Guid Id,
string RoleName
);
@@ -5,7 +5,7 @@ using System.Diagnostics;
namespace Lumina.Contracts.DTO.MediaContributors;
/// <summary>
/// Repository entity for a media contributor.
/// Data transfer object for a media contributor.
/// </summary>
/// <param name="Name">The name details of the media contributor, including display and legal names.</param>
/// <param name="Role">The role details of the media contributor, including the role name and category.</param>
@@ -5,7 +5,7 @@ using System.Diagnostics;
namespace Lumina.Contracts.DTO.MediaContributors;
/// <summary>
/// Repository entity for a media contributor name.
/// Data transfer object for a media contributor name.
/// </summary>
/// <param name="DisplayName">The display name of the media contributor.</param>
/// <param name="LegalName">The legal name of the media contributor.</param>
@@ -5,7 +5,7 @@ using System.Diagnostics;
namespace Lumina.Contracts.DTO.MediaContributors;
/// <summary>
/// Repository entity for a media contributor role.
/// Data transfer object for a media contributor role.
/// </summary>
/// <param name="Name">The name of the role assigned to the media contributor.</param>
/// <param name="Category">The category of the role.</param>
@@ -5,13 +5,9 @@ using System.Diagnostics;
namespace Lumina.Contracts.DTO.MediaLibrary.Management;
/// <summary>
/// Repository entity for a media library content location.
/// Data transfer object for a media library content location.
/// </summary>
[DebuggerDisplay("Path: {Path}")]
public class LibraryContentLocationDto
{
/// <summary>
/// Gets or sets the path of the media library content location.
/// </summary>
public required string Path { get; set; }
}
public record LibraryContentLocationDto(
string Path
);
@@ -6,7 +6,7 @@ using System.Diagnostics;
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Repository entity for ISBN information.
/// Data transfer object for ISBN information.
/// </summary>
/// <param name="Value">The ISBN value.</param>
/// <param name="Format">The format of the ISBN (e.g., ISBN-10 or ISBN-13).</param>
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authorization;
/// <summary>
/// Represents a request for adding an authorization role.
/// </summary>
/// <param name="RoleName">The name of the role. Required.</param>
/// <param name="Permissions">The collection or permissions of the role. Required.</param>
[DebuggerDisplay("RoleName: {RoleName}")]
public record AddRoleRequest(
string? RoleName,
List<Guid>? Permissions
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authorization;
/// <summary>
/// Represents a request for deleting an authorization role.
/// </summary>
/// <param name="RoleId">The Id of the role. Required.</param>
[DebuggerDisplay("RoleId: {RoleId}")]
public record DeleteRoleRequest(
Guid? RoleId
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authorization;
/// <summary>
/// Represents a request to get the authorization permissions of a role identified by <paramref name="RoleId"/>.
/// </summary>
/// <param name="RoleId">The Id of authorization role. Required.</param>
[DebuggerDisplay("RoleId: {RoleId}")]
public record GetRolePermissionsRequest(
Guid RoleId
);
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authorization;
/// <summary>
/// Represents a request for updating an existing authorization role.
/// </summary>
/// <param name="RoleId">The Id of the role. Required.</param>
/// <param name="RoleName">The name of the role. Required.</param>
/// <param name="Permissions">The collection or permissions of the role. Required.</param>
[DebuggerDisplay("RoleName: {RoleName}")]
public record UpdateRoleRequest(
Guid? RoleId,
string? RoleName,
List<Guid>? Permissions
);
@@ -14,8 +14,8 @@ namespace Lumina.Contracts.Responses.Authorization;
/// <param name="Roles">The collection of roles associated to the user.</param>
/// <param name="Permissions">The collection of permissions associated to the user.</param>
[DebuggerDisplay("UserId: {UserId}")]
public record GetAuthorizationResponse(
public record AuthorizationResponse(
Guid UserId,
IReadOnlySet<AuthorizationRole> Roles,
IReadOnlySet<string> Roles,
IReadOnlySet<AuthorizationPermission> Permissions
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.Authorization;
using System;
#endregion
namespace Lumina.Contracts.Responses.Authorization;
/// <summary>
/// Represents the response model for a request for an of authorization permission.
/// </summary>
/// <param name="Id">The Id of the requested authorization permission.</param>
/// <param name="PermissionName">The requested authorization permission.</param>
public record PermissionResponse(
Guid Id,
AuthorizationPermission PermissionName
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Authentication;
#endregion
namespace Lumina.Contracts.Responses.Authorization;
/// <summary>
/// Represents an authorizaton role permissions response.
/// </summary>
/// <param name="Role">The authorization role.</param>
/// <param name="Permissions">The permissions of the authorization role.</param>
public record RolePermissionsResponse(
RoleDto Role,
PermissionDto[] Permissions
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Contracts.Responses.Authorization;
/// <summary>
/// Represents the response model for a request for an authorization role.
/// </summary>
/// <param name="Id">The Id of the requested authorization role.</param>
/// <param name="RoleName">The requested authorization role.</param>
public record RoleResponse(
Guid Id,
string RoleName
);
@@ -29,11 +29,6 @@ public class PermissionConfiguration : IEntityTypeConfiguration<PermissionEntity
.HasMaxLength(100)
.HasColumnOrder(1);
builder.Property(permission => permission.PermissionDescription)
.HasMaxLength(255)
.HasDefaultValue(null)
.HasColumnOrder(2);
// audit
builder.Property(permission => permission.CreatedOnUtc)
.IsRequired()
@@ -25,15 +25,9 @@ public class RoleConfiguration : IEntityTypeConfiguration<RoleEntity>
builder.Property(role => role.RoleName)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(100)
.HasColumnOrder(1);
builder.Property(permission => permission.RoleDescription)
.HasMaxLength(255)
.HasDefaultValue(null)
.HasColumnOrder(2);
// audit
builder.Property(role => role.CreatedOnUtc)
.IsRequired()
@@ -0,0 +1,697 @@
// <auto-generated />
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
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
modelBuilder.Entity("BookGenres", b =>
{
b.Property<Guid>("BookId")
.HasColumnType("TEXT");
b.Property<string>("GenreId")
.HasColumnType("TEXT");
b.HasKey("BookId", "GenreId");
b.HasIndex("GenreId");
b.ToTable("BookGenres", (string)null);
});
modelBuilder.Entity("BookTags", b =>
{
b.Property<Guid>("BookId")
.HasColumnType("TEXT");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("PermissionName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime?>("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<Guid>("RoleId")
.HasColumnType("TEXT");
b.Property<Guid>("PermissionId")
.HasColumnType("TEXT");
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("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<Guid>("UserId")
.HasColumnType("TEXT");
b.Property<Guid>("PermissionId")
.HasColumnType("TEXT");
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("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<Guid>("UserId")
.HasColumnType("TEXT");
b.Property<Guid>("RoleId")
.HasColumnType("TEXT");
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("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<string>("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<string>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<DateTime>("Created")
.HasColumnType("TEXT");
b.Property<string>("LibraryType")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<DateTime?>("Updated")
.HasColumnType("TEXT");
b.Property<Guid>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<string>("ASIN")
.HasMaxLength(10)
.HasColumnType("TEXT")
.HasColumnOrder(21);
b.Property<string>("AppleBooksId")
.HasColumnType("TEXT")
.HasColumnOrder(29);
b.Property<string>("BarnesAndNobleId")
.HasMaxLength(10)
.HasColumnType("TEXT")
.HasColumnOrder(28);
b.Property<DateTime>("Created")
.HasColumnType("TEXT")
.HasColumnOrder(30);
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("Edition")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(19);
b.Property<string>("Format")
.HasColumnType("TEXT")
.HasColumnOrder(18);
b.Property<string>("GoodreadsId")
.HasColumnType("TEXT")
.HasColumnOrder(22);
b.Property<string>("GoogleBooksId")
.HasMaxLength(12)
.HasColumnType("TEXT")
.HasColumnOrder(27);
b.Property<string>("LCCN")
.HasColumnType("TEXT")
.HasColumnOrder(23);
b.Property<string>("LanguageCode")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<string>("LanguageName")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<string>("LanguageNativeName")
.HasColumnType("TEXT")
.HasColumnOrder(12);
b.Property<string>("LibraryThingId")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(26);
b.Property<string>("OCLCNumber")
.HasColumnType("TEXT")
.HasColumnOrder(24);
b.Property<string>("OpenLibraryId")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(25);
b.Property<string>("OriginalLanguageCode")
.HasColumnType("TEXT")
.HasColumnOrder(13);
b.Property<string>("OriginalLanguageName")
.HasColumnType("TEXT")
.HasColumnOrder(14);
b.Property<string>("OriginalLanguageNativeName")
.HasColumnType("TEXT")
.HasColumnOrder(15);
b.Property<DateOnly?>("OriginalReleaseDate")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<int?>("OriginalReleaseYear")
.HasColumnType("INTEGER")
.HasColumnOrder(5);
b.Property<string>("OriginalTitle")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<int?>("PageCount")
.HasColumnType("INTEGER")
.HasColumnOrder(17);
b.Property<string>("Publisher")
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(16);
b.Property<DateOnly?>("ReReleaseDate")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<int?>("ReReleaseYear")
.HasColumnType("INTEGER")
.HasColumnOrder(7);
b.Property<string>("ReleaseCountry")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("ReleaseVersion")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<DateTime?>("Updated")
.HasColumnType("TEXT")
.HasColumnOrder(31);
b.Property<int?>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("TempPassword")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<DateTime?>("TempPasswordCreated")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<string>("TotpSecret")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("LibraryId")
.HasColumnType("TEXT");
b1.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("BookId")
.HasColumnType("TEXT");
b1.Property<decimal>("MaxValue")
.HasColumnType("decimal(3,2)");
b1.Property<string>("Source")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b1.Property<decimal>("Value")
.HasColumnType("decimal(3,2)");
b1.Property<int?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b1.Property<Guid>("BookId")
.HasColumnType("TEXT");
b1.Property<string>("Format")
.IsRequired()
.HasMaxLength(6)
.HasColumnType("TEXT");
b1.Property<string>("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
}
}
}
@@ -0,0 +1,41 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations;
/// <inheritdoc />
public partial class ConvertsRoleFromEnumToString : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RoleDescription",
table: "Roles");
migrationBuilder.DropColumn(
name: "PermissionDescription",
table: "Permissions");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "RoleDescription",
table: "Roles",
type: "TEXT",
maxLength: 255,
nullable: true)
.Annotation("Relational:ColumnOrder", 2);
migrationBuilder.AddColumn<string>(
name: "PermissionDescription",
table: "Permissions",
type: "TEXT",
maxLength: 255,
nullable: true)
.Annotation("Relational:ColumnOrder", 2);
}
}
@@ -62,11 +62,6 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("PermissionDescription")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("PermissionName")
.IsRequired()
.HasMaxLength(100)
@@ -101,11 +96,6 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("RoleDescription")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(100)
@@ -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);
}
/// <summary>
/// Gets all permissions that have their Id match an Id in <paramref name="ids"/> from the storage medium.
/// </summary>
/// <param name="ids">The list of Ids of the permissions to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PermissionEntity"/>, or an error.</returns>
public async Task<ErrorOr<IEnumerable<PermissionEntity>>> GetByIdsAsync(IEnumerable<Guid> ids, CancellationToken cancellationToken)
{
return await _luminaDbContext.Permissions.Where(permission => ids.Contains(permission.Id)).ToListAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -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
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Created>> 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
/// <param name="roleType">The type of role to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="RoleEntity"/> if found, or an error.</returns>
public async Task<ErrorOr<RoleEntity?>> GetByNameAsync(AuthorizationRole roleType, CancellationToken cancellationToken)
public async Task<ErrorOr<RoleEntity?>> 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);
}
/// <summary>
/// Gets a <see cref="RoleEntity"/> identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the authorization role to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="RoleEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<ErrorOr<RoleEntity?>> 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);
}
/// <summary>
/// Updates a role.
/// </summary>
/// <param name="data">The role to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Updated>> 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;
}
/// <summary>
/// Deletes a role identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the role to be deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Deleted>> 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;
}
}
@@ -60,7 +60,7 @@ internal sealed class LibraryRepository : ILibraryRepository
/// <summary>
/// Updates a media library.
/// </summary>
/// <param name="data">Ther media library to update.</param>
/// <param name="data">The media library to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Updated>> UpdateAsync(LibraryEntity data, CancellationToken cancellationToken)
@@ -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<IPermissionRepository>();
// get the admin role
ErrorOr<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync(AuthorizationRole.Admin, cancellationToken).ConfigureAwait(false);
ErrorOr<RoleEntity?> 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<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync(AuthorizationRole.Admin, cancellationToken).ConfigureAwait(false);
ErrorOr<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
if (getAdminRoleResult.IsError)
return getAdminRoleResult.Errors;
@@ -1,10 +1,10 @@
namespace Lumina.Domain.Common.Enums.Authorization;
//namespace Lumina.Domain.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization roles.
/// </summary>
public enum AuthorizationRole
{
None = 0,
Admin = 1
}
///// <summary>
///// Enumeration for authorization roles.
///// </summary>
//public enum AuthorizationRole
//{
// None = 0,
// Admin = 1
//}
@@ -67,7 +67,7 @@ public class AuthorizationService : IAuthorizationService
/// <param name="role">The role to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the user is in the specified role, <see langword="false"/> otherwise.</returns>
public async Task<bool> IsInRoleAsync(Guid userId, AuthorizationRole role, CancellationToken cancellationToken)
public async Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken)
{
ErrorOr<UserEntity?> 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<AuthorizationRole> roles = getUserResult.Value.UserRoles
HashSet<string> roles = getUserResult.Value.UserRoles
.Select(userRole => userRole.Role.RoleName)
.ToHashSet();
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Permissions route.
/// </summary>
public static class Permissions
{
public const string GET_PERMISSIONS = "/permissions";
}
}
@@ -0,0 +1,19 @@
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Roles route.
/// </summary>
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}";
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/permissions</c> route.
/// </summary>
public class GetPermissionsEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetPermissionsEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetPermissionsEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Permissions.GET_PERMISSIONS);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the list of authorization permissions.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PermissionResponse>> result = await _sender.Send(new GetPermissionsQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPermissionsEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPermissionsEndpointSummary : Summary<GetPermissionsEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPermissionsEndpointSummary"/> class.
/// </summary>
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"
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/roles</c> route.
/// </summary>
public class AddRoleEndpoint : BaseEndpoint<AddRoleRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="AddRoleEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public AddRoleEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Roles.CREATE_ROLE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Creates a new authorization role.
/// </summary>
/// <param name="request">The request containing the authorization role to be created.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddRoleRequest request, CancellationToken cancellationToken)
{
ErrorOr<RolePermissionsResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddRoleEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddRoleEndpointSummary : Summary<AddRoleEndpoint, AddRoleRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddRoleEndpointSummary"/> class.
/// </summary>
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<RolePermissionsResponse>(r => r.Role, "The authorization role entity.");
ResponseParam<RolePermissionsResponse>(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<string, string[]>
{
{
"General.Validation", new[]
{
"RoleNameCannotBeNull",
"RoleNameCannotBeEmpty",
"PermissionsListCannotBeNull",
"PermissionsListCannotBeEmpty",
"PermissionIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/roles</c> route.
/// </summary>
public class DeleteRoleEndpoint : BaseEndpoint<DeleteRoleRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteRoleEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public DeleteRoleEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.DELETE);
Routes(ApiRoutes.Roles.DELETE_ROLE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Deletes an authorization role.
/// </summary>
/// <param name="request">The request containing the Id of the authorization role to be deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(DeleteRoleRequest request, CancellationToken cancellationToken)
{
ErrorOr<Deleted> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.NoContent(), Problem);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/roles/{roleId}/permissions</c> route.
/// </summary>
public class GetRolePermissionsEndpoint : BaseEndpoint<GetRolePermissionsRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetRolePermissionsEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetRolePermissionsEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Roles.GET_ROLE_PERMISSIONS_BY_ROLE_ID);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the list of authorization permissions of a role identified by Id.
/// </summary>
/// <param name="request">The request containing the id of the role for which to get the list of permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetRolePermissionsRequest request, CancellationToken cancellationToken)
{
ErrorOr<RolePermissionsResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetRolePermissionsEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolePermissionsEndpointSummary : Summary<GetRolePermissionsEndpoint, GetRolePermissionsRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetRolePermissionsEndpointSummary"/> class.
/// </summary>
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<string, string[]>
{
{
"General.Validation", new[]
{
"RoleIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/roles</c> route.
/// </summary>
public class GetRolesEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetRolesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetRolesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Roles.GET_ROLES);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the list of authorization roles.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<RoleResponse>> result = await _sender.Send(new GetRolesQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetRolesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPermissionsEndpointSummary : Summary<GetRolesEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPermissionsEndpointSummary"/> class.
/// </summary>
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"
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/roles</c> route.
/// </summary>
public class UpdateRoleEndpoint : BaseEndpoint<UpdateRoleRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateRoleEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public UpdateRoleEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.PUT);
Routes(ApiRoutes.Roles.UPDATE_ROLE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Updates an existing authorization role.
/// </summary>
/// <param name="request">The request containing the authorization role to be updated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UpdateRoleRequest request, CancellationToken cancellationToken)
{
ErrorOr<RolePermissionsResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="UpdateRoleEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateRoleEndpointSummary : Summary<UpdateRoleEndpoint, UpdateRoleRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateRoleEndpointSummary"/> class.
/// </summary>
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<RolePermissionsResponse>(r => r.Role, "The authorization role entity.");
ResponseParam<RolePermissionsResponse>(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<string, string[]>
{
{
"General.Validation", new[]
{
"RoleNameCannotBeNull",
"RoleNameCannotBeEmpty",
"PermissionsListCannotBeNull",
"PermissionsListCannotBeEmpty",
"PermissionIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -50,7 +50,7 @@ public class AddLibraryEndpoint : BaseEndpoint<AddLibraryRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<LibraryResponse> 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);
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more