Merge pull request #83 from BinaryAlley/feature/implement-authorization-caching-and-check-in-web-client

Implements authorization caching and check in the web client
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-12-06 18:51:37 +02:00
commit b11b7fc82b
108 files changed
+5931 -73

No files matched your search

@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -21,17 +22,22 @@ public class PermissionEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets the name of the permission.
/// </summary>
public required string PermissionName { get; init; }
public required AuthorizationPermission PermissionName { get; init; }
/// <summary>
/// Gets the collection of role permission associations that include this permission.
/// Gets the description of the permission.
/// </summary>
public required ICollection<RolePermissionEntity> RolePermissions { get; init; } = [];
public string? PermissionDescription { get; set; }
/// <summary>
/// Gets the collection of user permission associations that include this permission.
/// Gets or sets the collection of role permission associations that include this permission.
/// </summary>
public required ICollection<UserPermissionEntity> UserPermissions { get; init; } = [];
public ICollection<RolePermissionEntity> RolePermissions { get; set; } = [];
/// <summary>
/// Gets or sets the collection of user permission associations that include this permission.
/// </summary>
public ICollection<UserPermissionEntity> UserPermissions { get; set; } = [];
/// <summary>
/// Gets or sets the time and date when the entity was added.
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -21,17 +22,22 @@ public class RoleEntity : IStorageEntity
/// <summary>
/// Gets the name of the role.
/// </summary>
public required string RoleName { get; init; }
public required AuthorizationRole RoleName { get; init; }
/// <summary>
/// Gets the collection of user roles associations that include this role.
/// Gets or sets the description of the role.
/// </summary>
public required ICollection<UserRoleEntity> UserRoles { get; init; } = [];
public string? RoleDescription { get; set; }
/// <summary>
/// Gets the collection of role permission associations that include this role.
/// Gets or sets the collection of user roles associations that include this role.
/// </summary>
public required ICollection<RolePermissionEntity> RolePermissions { get; init; } = [];
public ICollection<UserRoleEntity> UserRoles { get; set; } = [];
/// <summary>
/// Gets or sets the collection of role permission associations that include this role.
/// </summary>
public ICollection<RolePermissionEntity> RolePermissions { get; set; } = [];
/// <summary>
/// Gets or sets the time and date when the entity was added.
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// <summary>
/// Data Transfer object containing all the authorization info of a user.
/// </summary>
[DebuggerDisplay("UserId: {UserId}")]
public class UserAuthorizationEntity
{
/// <summary>
/// Gets the Id of the user.
/// </summary>
public required Guid UserId { get; init; }
/// <summary>
/// Gets the collection of roles associated to the user.
/// </summary>
public required IReadOnlySet<AuthorizationRole> Roles { get; init; }
/// <summary>
/// Gets the collection of permissions associated to the user.
/// </summary>
public required IReadOnlySet<AuthorizationPermission> Permissions { get; init; }
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Authorization;
/// <summary>
/// Interface for the repository for authorization permissions.
/// </summary>
public interface IPermissionRepository : IRepository<PermissionEntity>,
IInsertRepositoryAction<PermissionEntity>,
IGetAllRepositoryAction<PermissionEntity>
{
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Authorization;
/// <summary>
/// Interface for the repository for authorization role permissions.
/// </summary>
public interface IRolePermissionRepository : IRepository<RolePermissionEntity>,
IInsertRepositoryAction<RolePermissionEntity>
{
}
@@ -0,0 +1,27 @@
#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 Lumina.Domain.Common.Enums.Authorization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Authorization;
/// <summary>
/// Interface for the repository for authorization roles.
/// </summary>
public interface IRoleRepository : IRepository<RoleEntity>,
IInsertRepositoryAction<RoleEntity>,
IGetAllRepositoryAction<RoleEntity>
{
/// <summary>
/// Gets a role identified by <paramref name="roleType"/> from the repository, if it exists.
/// </summary>
/// <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);
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Authorization;
/// <summary>
/// Interface for the repository for authorization user roles.
/// </summary>
public interface IUserRoleRepository : IRepository<UserRoleEntity>,
IInsertRepositoryAction<UserRoleEntity>
{
}
@@ -20,7 +20,7 @@ public interface IUserRepository : IRepository<UserEntity>,
IUpdateRepositoryAction<UserEntity>
{
/// <summary>
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
/// Gets a user identified by <paramref name="username"/> from the repository, if it exists.
/// </summary>
/// <param name="username">The username of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Seed;
/// <summary>
/// Interface for the service for seeding initial data in the persistence medium.
/// </summary>
public interface IDataSeedService
{
/// <summary>
/// Sets up default authorization permissions in the system.
/// </summary>
/// <param name="adminId">The Id of the admin admin user who will own these permissions.</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>
Task<ErrorOr<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken);
/// <summary>
/// Sets up default authorization roles in the system.
/// </summary>
/// <param name="userId">The Id of the admin user for whom roles will be set.</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>
Task<ErrorOr<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Assigns admin role permissions to the admin user.
/// </summary>
/// <param name="userId">The Id of the admin user to receive admin role permissions.</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>
Task<ErrorOr<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Assigns admin role to the admin user.
/// </summary>
/// <param name="userId">The Id of the admin user to receive the admin role.</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>
Task<ErrorOr<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken);
}
@@ -13,5 +13,9 @@ public static partial class Errors
{
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 PermissionAlreadyExists => Error.Unauthorized(description: nameof(PermissionAlreadyExists));
public static Error RoleAlreadyExists => Error.Unauthorized(description: nameof(RoleAlreadyExists));
}
}
@@ -1,5 +1,8 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -16,19 +19,19 @@ public interface IAuthorizationService
/// Determines whether the specified user has a specific permission.
/// </summary>
/// <param name="userId">The Id of the user for whom to check the permission.</param>
/// <param name="permission">The name of the permission to check.</param>
/// <param name="permission">The permission to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the user has the specified permission, <see langword="false"/> otherwise.</returns>
Task<bool> HasPermissionAsync(Guid userId, string permission, CancellationToken cancellationToken);
Task<bool> HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken);
/// <summary>
/// Determines whether the specified user belongs to a specific role.
/// </summary>
/// <param name="userId">The Id of the user for whom to check the role.</param>
/// <param name="role">The name of the role to check.</param>
/// <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, string role, CancellationToken cancellationToken);
Task<bool> IsInRoleAsync(Guid userId, AuthorizationRole role, CancellationToken cancellationToken);
/// <summary>
/// Evaluates whether the specified user meets the conditions defined in the specified authorization policy.
@@ -38,4 +41,12 @@ public interface IAuthorizationService
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the user satisfies the policy, <see langword="false"/> otherwise.</returns>
Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(Guid userId, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy;
/// <summary>
/// Retrieves all authorization roles and permissions of a user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The id of the user for whom to retrieve the authorization roles and permissions.</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="UserAuthorizationEntity"/>, or an error.</returns>
Task<ErrorOr<UserAuthorizationEntity>> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken);
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Contracts.Requests.Authorization;
#endregion
namespace Lumina.Application.Common.Mapping.Authorization;
/// <summary>
/// Extension methods for converting <see cref="GetAuthorizationRequest"/>.
/// </summary>
public static class GetAuthorizationRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetAuthorizationQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetAuthorizationQuery ToQuery(this GetAuthorizationRequest request)
{
return new GetAuthorizationQuery(
request.UserId
);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Contracts.Responses.Authorization;
#endregion
namespace Lumina.Application.Common.Mapping.Authorization;
/// <summary>
/// Extension methods for converting <see cref="UserAuthorizationEntity"/>.
/// </summary>
public static class UserAuthorizationEntityMapping
{
/// <summary>
/// Converts <paramref name="infrastructureEntity"/> to <see cref="GetAuthorizationResponse"/>.
/// </summary>
/// <param name="infrastructureEntity">The infrastructure entity to be converted.</param>
/// <returns>The converted response.</returns>
public static GetAuthorizationResponse ToResponse(this UserAuthorizationEntity infrastructureEntity)
{
return new GetAuthorizationResponse(
infrastructureEntity.UserId,
infrastructureEntity.Roles,
infrastructureEntity.Permissions
);
}
}
@@ -32,7 +32,7 @@ public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr
/// </summary>
/// <param name="request">The query containing the requested path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The root of the specified path.</returns>
/// <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!);
@@ -1,7 +1,10 @@
#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;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -29,6 +32,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IDataSeedService _dataSeedService;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationCommandHandler"/> class.
@@ -39,13 +43,15 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="dataSeedService">Injected service for the initial persistence medium data seed.</param>
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider)
IDateTimeProvider dateTimeProvider,
IDataSeedService dataSeedService)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
@@ -53,6 +59,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
_totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
_dataSeedService = dataSeedService;
}
/// <summary>
@@ -67,10 +74,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>> resultSelectUser = await userRepository.GetAllAsync(cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value.Any())
ErrorOr<IEnumerable<UserEntity>> selectUserResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (selectUserResult.IsError)
return selectUserResult.Errors;
else if (selectUserResult.Value.Any())
return Errors.Authorization.AdminAccountAlreadyCreated;
// no users are present, register the admin one
string? totpSecret = null;
@@ -82,7 +89,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
CreatedOnUtc = _dateTimeProvider.UtcNow,
Libraries = [],
UserPermissions = [], // TODO: implement default roles and permissions
UserPermissions = [],
UserRoles = [],
CreatedBy = id
};
@@ -97,10 +104,28 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken);
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);
// set the default permissions, roles, roles permissions
ErrorOr<Created> setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false);
if (setPermissionsResult.IsError)
return setPermissionsResult.Errors;
ErrorOr<Created> setRoleResult = await _dataSeedService.SetDefaultAuthorizationRolesAsync(id, cancellationToken).ConfigureAwait(false);
if (setRoleResult.IsError)
return setRoleResult.Errors;
ErrorOr<Created> setRolePermissionResult = await _dataSeedService.SetAdminRolePermissionsAsync(id, cancellationToken).ConfigureAwait(false);
if (setRolePermissionResult.IsError)
return setRolePermissionResult.Errors;
ErrorOr<Created> setRoleToAdminResult = await _dataSeedService.SetAdminRoleToAdministratorAccount(id, cancellationToken).ConfigureAwait(false);
if (setRoleToAdminResult.IsError)
return setRoleToAdminResult.Errors;
// 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
return new RegistrationResponse(user.Id, user.Username, totpSecret);
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authorization;
using Mediator;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
/// <summary>
/// Query for retrieving the authorization roles and permissions of an account.
/// </summary>
/// <param name="UserId">The Id of the user for whom to get the authorization.</param>
[DebuggerDisplay("UserId: {UserId}")]
public record GetAuthorizationQuery(
Guid? UserId
) : IRequest<ErrorOr<GetAuthorizationResponse>>;
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
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 Lumina.Domain.Common.Enums.Authorization;
using Mediator;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
/// <summary>
/// Handler for the query to retrieve the authorization roles and permissions of an account.
/// </summary>
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<GetAuthorizationResponse>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationService"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
public GetAuthorizationQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
}
/// <summary>
/// Handles the query to retrieve the authorization roles and permissions of an account.
/// </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 <see cref="GetAuthorizationResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<GetAuthorizationResponse>> 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;
// 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))
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);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
/// <summary>
/// Validates the needed validation rules for <see cref="GetAuthorizationQuery"/>.
/// </summary>
public class GetAuthorizationQueryValidator : AbstractValidator<GetAuthorizationQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationQueryValidator"/> class.
/// </summary>
public GetAuthorizationQueryValidator()
{
RuleFor(x => x.UserId)
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Contracts.Requests.Authorization;
/// <summary>
/// Represents the request model for retrieving account authorization information.
/// </summary>
/// <param name="UserId">The Id of the user for whom to get the authorization. Required.</param>
public record GetAuthorizationRequest(
Guid? UserId
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Authorization;
/// <summary>
/// Represents the response model for an account authorization request.
/// </summary>
/// <param name="UserId">The Id of the user for whom the authorization is retrieved.</param>
/// <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(
Guid UserId,
IReadOnlySet<AuthorizationRole> Roles,
IReadOnlySet<AuthorizationPermission> Permissions
);
@@ -25,24 +25,30 @@ public class PermissionConfiguration : IEntityTypeConfiguration<PermissionEntity
builder.Property(permission => permission.PermissionName)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(100)
.HasColumnOrder(1);
builder.Property(permission => permission.PermissionDescription)
.HasMaxLength(255)
.HasDefaultValue(null)
.HasColumnOrder(2);
// audit
builder.Property(permission => permission.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(2);
.HasColumnOrder(3);
builder.Property(permission => permission.CreatedBy)
.IsRequired()
.HasColumnOrder(3);
.HasColumnOrder(4);
builder.Property(permission => permission.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(4);
.HasColumnOrder(5);
builder.Property(permission => permission.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(5);
.HasColumnOrder(6);
}
}
@@ -25,24 +25,30 @@ 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()
.HasColumnOrder(2);
.HasColumnOrder(3);
builder.Property(role => role.CreatedBy)
.IsRequired()
.HasColumnOrder(3);
.HasColumnOrder(4);
builder.Property(role => role.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(4);
.HasColumnOrder(5);
builder.Property(role => role.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(5);
.HasColumnOrder(6);
}
}
@@ -21,6 +21,8 @@ public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermissi
// composite primary key
builder.HasKey(rolePermission => new { rolePermission.RoleId, rolePermission.PermissionId });
builder.Ignore(rolePermission => rolePermission.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id
// foreign key: Role
builder.HasOne(rolePermission => rolePermission.Role)
@@ -22,6 +22,8 @@ public class UserPermissionConfiguration : IEntityTypeConfiguration<UserPermissi
// composite primary key
builder.HasKey(userPermission => new { userPermission.UserId, userPermission.PermissionId });
builder.Ignore(userPermission => userPermission.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id
// foreign key: User
builder.HasOne(userPermission => userPermission.User)
.WithMany(user => user.UserPermissions)
@@ -21,7 +21,9 @@ public class UserRoleConfiguration : IEntityTypeConfiguration<UserRoleEntity>
// composite primary key
builder.HasKey(userRole => new { userRole.UserId, userRole.RoleId });
builder.Ignore(userRole => userRole.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id
// foreign key: User
builder.HasOne(userRole => userRole.User)
.WithMany(user => user.UserRoles)
@@ -1,8 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.Seed;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.Repositories.Common.Factory;
using Lumina.DataAccess.Core.Seed;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
@@ -60,5 +62,7 @@ public static class DataAccessLayerServices
.Any(type => type.GetGenericTypeDefinition() == genericRepositoryType))
.First(), type);
}
services.AddScoped<IDataSeedService, DataSeedService>();
}
}
@@ -0,0 +1,707 @@
// <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("20241123185828_AddsDescriptionColumnToRolesAndPermissions")]
partial class AddsDescriptionColumnToRolesAndPermissions
{
/// <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>("PermissionDescription")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
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>("RoleDescription")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
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,243 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations;
/// <inheritdoc />
public partial class AddsDescriptionColumnToRolesAndPermissions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Id",
table: "UserRoles");
migrationBuilder.DropColumn(
name: "Id",
table: "UserPermissions");
migrationBuilder.DropColumn(
name: "Id",
table: "RolePermissions");
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "Roles",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 4);
migrationBuilder.AlterColumn<Guid>(
name: "UpdatedBy",
table: "Roles",
type: "TEXT",
nullable: true,
oldClrType: typeof(Guid),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 6)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<DateTime>(
name: "CreatedOnUtc",
table: "Roles",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 3)
.OldAnnotation("Relational:ColumnOrder", 2);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "Roles",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 4)
.OldAnnotation("Relational:ColumnOrder", 3);
migrationBuilder.AddColumn<string>(
name: "RoleDescription",
table: "Roles",
type: "TEXT",
maxLength: 255,
nullable: true)
.Annotation("Relational:ColumnOrder", 2);
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "Permissions",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 4);
migrationBuilder.AlterColumn<Guid>(
name: "UpdatedBy",
table: "Permissions",
type: "TEXT",
nullable: true,
oldClrType: typeof(Guid),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 6)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<DateTime>(
name: "CreatedOnUtc",
table: "Permissions",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 3)
.OldAnnotation("Relational:ColumnOrder", 2);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "Permissions",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 4)
.OldAnnotation("Relational:ColumnOrder", 3);
migrationBuilder.AddColumn<string>(
name: "PermissionDescription",
table: "Permissions",
type: "TEXT",
maxLength: 255,
nullable: true)
.Annotation("Relational:ColumnOrder", 2);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RoleDescription",
table: "Roles");
migrationBuilder.DropColumn(
name: "PermissionDescription",
table: "Permissions");
migrationBuilder.AddColumn<Guid>(
name: "Id",
table: "UserRoles",
type: "TEXT",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.AddColumn<Guid>(
name: "Id",
table: "UserPermissions",
type: "TEXT",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "Roles",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 4)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<Guid>(
name: "UpdatedBy",
table: "Roles",
type: "TEXT",
nullable: true,
oldClrType: typeof(Guid),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AlterColumn<DateTime>(
name: "CreatedOnUtc",
table: "Roles",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 2)
.OldAnnotation("Relational:ColumnOrder", 3);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "Roles",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 3)
.OldAnnotation("Relational:ColumnOrder", 4);
migrationBuilder.AddColumn<Guid>(
name: "Id",
table: "RolePermissions",
type: "TEXT",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "Permissions",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 4)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<Guid>(
name: "UpdatedBy",
table: "Permissions",
type: "TEXT",
nullable: true,
oldClrType: typeof(Guid),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AlterColumn<DateTime>(
name: "CreatedOnUtc",
table: "Permissions",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 2)
.OldAnnotation("Relational:ColumnOrder", 3);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "Permissions",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 3)
.OldAnnotation("Relational:ColumnOrder", 4);
}
}
@@ -56,9 +56,14 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(3);
.HasColumnOrder(4);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("PermissionDescription")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
@@ -70,11 +75,11 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
.HasColumnOrder(6);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
.HasColumnOrder(5);
b.HasKey("Id");
@@ -90,9 +95,14 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(3);
.HasColumnOrder(4);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("RoleDescription")
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
@@ -104,11 +114,11 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
.HasColumnOrder(6);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
.HasColumnOrder(5);
b.HasKey("Id");
@@ -131,9 +141,6 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
@@ -168,9 +175,6 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
@@ -205,9 +209,6 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(4);
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
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 Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Authorization;
/// <summary>
/// Repository for authorization permissions.
/// </summary>
internal sealed class PermissionRepository : IPermissionRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="PermissionRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public PermissionRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new authorization permission.
/// </summary>
/// <param name="permission">The authorization permission to add.</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<Created>> InsertAsync(PermissionEntity permission, CancellationToken cancellationToken)
{
bool permissionExists = await _luminaDbContext.Permissions.AnyAsync(repositoryPermission => repositoryPermission.Id == permission.Id, cancellationToken).ConfigureAwait(false);
if (permissionExists)
return Errors.Authorization.PermissionAlreadyExists;
_luminaDbContext.Permissions.Add(permission);
return Result.Created;
}
/// <summary>
/// Gets all autorization permissions.
/// </summary>
/// <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>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Permissions.ToListAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.DataAccess.Core.UoW;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Authorization;
/// <summary>
/// Repository for authorization role permissions.
/// </summary>
internal sealed class RolePermissionRepository : IRolePermissionRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="RolePermissionRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public RolePermissionRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new authorization role permission.
/// </summary>
/// <param name="rolePermission">The authorization role permission to add.</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<Created>> InsertAsync(RolePermissionEntity rolePermission, CancellationToken cancellationToken)
{
_luminaDbContext.RolePermissions.Add(rolePermission);
return await Task.FromResult(Result.Created);
}
}
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
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.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Authorization;
/// <summary>
/// Repository for authorization roles.
/// </summary>
internal sealed class RoleRepository : IRoleRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="RoleRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public RoleRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new authorization role.
/// </summary>
/// <param name="role">The authorization role to add.</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<Created>> InsertAsync(RoleEntity role, CancellationToken cancellationToken)
{
bool roleExists = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id, cancellationToken).ConfigureAwait(false);
if (roleExists)
return Errors.Authorization.RoleAlreadyExists;
_luminaDbContext.Roles.Add(role);
return Result.Created;
}
/// <summary>
/// Gets all autorization roles.
/// </summary>
/// <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="RoleEntity"/>, or an error.</returns>
public async Task<ErrorOr<IEnumerable<RoleEntity>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Roles.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a role identified by <paramref name="roleType"/> from the repository, if it exists.
/// </summary>
/// <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)
{
return await _luminaDbContext.Roles
.Include(role => role.RolePermissions)
.ThenInclude(library => library.Permission)
.FirstOrDefaultAsync(role => role.RoleName == roleType, cancellationToken)
.ConfigureAwait(false);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.DataAccess.Core.UoW;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Authorization;
/// <summary>
/// Repository for authorization user roles.
/// </summary>
internal sealed class UserRoleRepository : IUserRoleRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="UserRoleRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public UserRoleRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new authorization user role.
/// </summary>
/// <param name="userRole">The authorization user role to add.</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<Created>> InsertAsync(UserRoleEntity userRole, CancellationToken cancellationToken)
{
_luminaDbContext.UserRoles.Add(userRole);
return await Task.FromResult(Result.Created);
}
}
@@ -56,7 +56,7 @@ internal sealed class UserRepository : IUserRepository
}
/// <summary>
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
/// Gets a user identified by <paramref name="username"/> from the repository, if it exists.
/// </summary>
/// <param name="username">The username of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -0,0 +1,181 @@
#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;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Seed;
/// <summary>
/// Service for seeding initial data in the persistence medium.
/// </summary>
public class DataSeedService : IDataSeedService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="DataSeedService"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
public DataSeedService(IUnitOfWork unitOfWork, IDateTimeProvider dateTimeProvider)
{
_unitOfWork = unitOfWork;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
/// Sets up default authorization permissions in the system.
/// </summary>
/// <param name="adminId">The Id of the admin admin user who will own these permissions.</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<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken)
{
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
// 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 }
];
foreach (PermissionEntity permission in defaultPermissions)
{
ErrorOr<Created> insertPermissionResult = await permissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false);
if (insertPermissionResult.IsError)
return insertPermissionResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Created;
}
/// <summary>
/// Sets up default authorization roles in the system.
/// </summary>
/// <param name="userId">The Id of the admin user for whom roles will be set.</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<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken)
{
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
// 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 }
];
foreach (RoleEntity role in defaultRoles)
{
ErrorOr<Created> insertRoleResult = await roleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false);
if (insertRoleResult.IsError)
return insertRoleResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Created;
}
/// <summary>
/// Assigns admin role permissions to the admin user.
/// </summary>
/// <param name="userId">The Id of the admin user to receive admin role permissions.</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<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
{
IRolePermissionRepository rolePermissionRepository = _unitOfWork.GetRepository<IRolePermissionRepository>();
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
// get the admin role
ErrorOr<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync(AuthorizationRole.Admin, cancellationToken).ConfigureAwait(false);
if (getAdminRoleResult.IsError)
return getAdminRoleResult.Errors;
if (getAdminRoleResult.Value is null)
return Errors.Authorization.AdminAccountNotFound;
// get all permissions
ErrorOr<IEnumerable<PermissionEntity>> getPermissionsResult = await permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getPermissionsResult.IsError)
return getPermissionsResult.Errors;
// add each permission to the admin role
foreach (PermissionEntity permission in getPermissionsResult.Value)
{
RolePermissionEntity rolePermissionEntity = new()
{
Permission = permission,
PermissionId = permission.Id,
Role = getAdminRoleResult.Value,
RoleId = getAdminRoleResult.Value.Id,
CreatedBy = userId,
CreatedOnUtc = _dateTimeProvider.UtcNow
};
ErrorOr<Created> insertRolePermissionResult = await rolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false);
if (insertRolePermissionResult.IsError)
return insertRolePermissionResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Created;
}
/// <summary>
/// Assigns admin role to the admin user.
/// </summary>
/// <param name="userId">The Id of the admin user to receive the admin role.</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<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken)
{
IUserRoleRepository userRoleRepository = _unitOfWork.GetRepository<IUserRoleRepository>();
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
// get the admin role
ErrorOr<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync(AuthorizationRole.Admin, cancellationToken).ConfigureAwait(false);
if (getAdminRoleResult.IsError)
return getAdminRoleResult.Errors;
if (getAdminRoleResult.Value is null)
return Errors.Authorization.AdminRoleNotFound;
// get admin user
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
if (getUserResult.Value is null)
return Errors.Authorization.AdminAccountNotFound;
// add the admin role to the admin user
UserRoleEntity userRole = new()
{
CreatedBy = userId,
CreatedOnUtc = _dateTimeProvider.UtcNow,
Role = getAdminRoleResult.Value,
RoleId = getAdminRoleResult.Value.Id,
User = getUserResult.Value,
UserId = getUserResult.Value.Id
};
ErrorOr<Created> insertUserRoleResult = await userRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false);
if (insertUserRoleResult.IsError)
return insertUserRoleResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Created;
}
}
@@ -0,0 +1,12 @@
namespace Lumina.Domain.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization permissions.
/// </summary>
public enum AuthorizationPermission
{
None = 0,
CanViewUsers = 1,
CanDeleteUsers = 2,
CanRegisterUsers = 3
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization roles.
/// </summary>
public enum AuthorizationRole
{
None = 0,
Admin = 1
}
@@ -12,6 +12,7 @@ public static partial class Errors
public static class Users
{
public static Error UserAlreadyExists => Error.Conflict(description: nameof(UserAlreadyExists));
public static Error UserDoesNotExist => Error.Conflict(description: nameof(UserDoesNotExist));
public static Error UserDoesNotExist => Error.NotFound(description: nameof(UserDoesNotExist));
public static Error UserIdCannotBeEmpty => Error.Validation(description: nameof(UserIdCannotBeEmpty));
}
}
@@ -1,10 +1,12 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.Core.Authorization;
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
using Lumina.Infrastructure.Core.Security;
@@ -43,7 +45,7 @@ public static class InfrastructureLayerServices
// authorization
services.AddScoped<IOver18Policy, Over18Policy>();
services.AddScoped<IAuthorizationPolicyFactory, AuthorizationPolicyFactory>();
services.AddScoped<IAuthorizationService, AuthorizationService>();
return services;
}
}
@@ -1,12 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.Common.Errors;
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -37,10 +41,10 @@ public class AuthorizationService : IAuthorizationService
/// Determines whether the specified user has a specific permission.
/// </summary>
/// <param name="userId">The Id of the user for whom to check the permission.</param>
/// <param name="permission">The name of the permission to check.</param>
/// <param name="permission">The permission to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the user has the specified permission, <see langword="false"/> otherwise.</returns>
public async Task<bool> HasPermissionAsync(Guid userId, string permission, CancellationToken cancellationToken)
public async Task<bool> HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken)
{
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError || getUserResult.Value is null)
@@ -60,10 +64,10 @@ public class AuthorizationService : IAuthorizationService
/// Determines whether the specified user belongs to a specific role.
/// </summary>
/// <param name="userId">The Id of the user for whom to check the role.</param>
/// <param name="role">The name of the role to check.</param>
/// <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, string role, CancellationToken cancellationToken)
public async Task<bool> IsInRoleAsync(Guid userId, AuthorizationRole role, CancellationToken cancellationToken)
{
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError || getUserResult.Value is null)
@@ -84,4 +88,49 @@ public class AuthorizationService : IAuthorizationService
IAuthorizationPolicy policy = _authorizationPolicyFactory.CreatePolicy<TAuthorizationPolicy>();
return await policy.EvaluateAsync(userId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves all authorization roles and permissions of a user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The id of the user for whom to retrieve the authorization roles and permissions.</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="UserAuthorizationEntity"/>, or an error.</returns>
public async Task<ErrorOr<UserAuthorizationEntity>> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken)
{
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsError)
return getUserResult.Errors;
if (getUserResult.Value is null)
return Errors.Users.UserDoesNotExist;
// get all roles
HashSet<AuthorizationRole> roles = getUserResult.Value.UserRoles
.Select(userRole => userRole.Role.RoleName)
.ToHashSet();
// get direct user permissions
HashSet<AuthorizationPermission> directPermissions = getUserResult.Value.UserPermissions
.Select(userPermission => userPermission.Permission.PermissionName)
.ToHashSet();
// get permissions from roles
HashSet<AuthorizationPermission> rolePermissions = getUserResult.Value.UserRoles
.SelectMany(userRole => userRole.Role.RolePermissions)
.Select(rolePermission => rolePermission.Permission.PermissionName)
.ToHashSet();
// combine all permissions
HashSet<AuthorizationPermission> allPermissions = directPermissions
.Union(rolePermissions)
.ToHashSet();
return new UserAuthorizationEntity
{
UserId = userId,
Roles = roles,
Permissions = allPermissions
};
}
}
@@ -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 Authorization route.
/// </summary>
public static class Authorization
{
public const string GET_AUTHORIZATION = "/auth/get-authorization";
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetAuthorization;
/// <summary>
/// API endpoint for the <c>/auth/get-authorization</c> route.
/// </summary>
public class GetAuthorizationEndpoint : BaseEndpoint<GetAuthorizationRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetAuthorizationEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Authorization.GET_AUTHORIZATION);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the authentication roles and permissions of an account.
/// </summary>
/// <param name="request">The request containing the account for which to get the authentication roles and permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetAuthorizationRequest request, CancellationToken cancellationToken)
{
ErrorOr<GetAuthorizationResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetAuthorization;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetAuthorizationEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationEndpointSummary : Summary<GetAuthorizationEndpoint, GetAuthorizationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationEndpointSummary"/> class.
/// </summary>
public GetAuthorizationEndpointSummary()
{
Summary = "Gets the authorization details of an account.";
Description = "Gets the authorization roles and permissions of an account.";
ExampleRequest = new GetAuthorizationRequest(
UserId: Guid.NewGuid()
);
RequestParam(r => r.UserId, "The Id of the user for whom to get the authorization. Required.");
Response(200, "The authorization roles and permissions of the account are returned.",
example: new GetAuthorizationResponse(
UserId: Guid.NewGuid(),
Roles: new HashSet<AuthorizationRole>() { AuthorizationRole.Admin },
Permissions: new HashSet<AuthorizationPermission>() { AuthorizationPermission.CanRegisterUsers, AuthorizationPermission.CanDeleteUsers }
));
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/auth/get-authorization"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/auth/get-authorization"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/auth/get-authorization"
}
}
);
Response(403, "The request failed because either the current user is not an Admin, or the requested roles and permissions do not belong to the current user making the request.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/auth/get-authorization",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/auth/get-authorization",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"UserIdCannotBeEmpty"
}
}
},
traceId = "00-839f81e411d7eb91ed5aa91e56b00bbb-7c8bd5dfabdaf2dc-00"
}
);
}
}
+1 -1
View File
@@ -85,7 +85,7 @@ public class Program
}
catch (Exception ex)
{
Microsoft.Extensions.Logging.ILogger logger = services.GetRequiredService<Microsoft.Extensions.Logging.ILogger>();
ILogger<Program> logger = services.GetRequiredService<ILogger<Program>>();
logger.LogCritical(ex, "Failed to run database migrations");
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Filters.TypeFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
#endregion
namespace Lumina.Presentation.Web.Common.Attributes;
/// <summary>
/// Attribute that restricts endpoint access to users with specified permissions.
/// </summary>
/// <remarks>
/// Can be applied to controllers or individual actions. Multiple permissions create an OR condition.
/// </remarks>
public class RequirePermissionAttribute : ApiAuthorizationAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequirePermissionAttribute"/> class.
/// </summary>
/// <param name="permissions">One or more permissions that are allowed to access the endpoint.</param>
public RequirePermissionAttribute(params AuthorizationPermission[] permissions) : base()
{
Arguments = [new AuthorizationRequirementModel { Permissions = permissions }];
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Filters.TypeFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Attributes;
/// <summary>
/// Attribute that restricts endpoint access based on a custom authorization policy.
/// </summary>
/// <remarks>
/// Can be applied to controllers or individual actions.
/// </remarks>
public class RequirePolicyAttribute : ApiAuthorizationAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequirePolicyAttribute"/> class.
/// </summary>
/// <param name="policyType">The type of the authorization policy to apply.</param>
public RequirePolicyAttribute(Type policyType) : base()
{
Arguments = [new AuthorizationRequirementModel { PolicyType = policyType }];
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Filters.TypeFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
#endregion
namespace Lumina.Presentation.Web.Common.Attributes;
/// <summary>
/// Attribute that restricts endpoint access to users with specified roles.
/// </summary>
/// <remarks>
/// Can be applied to controllers or individual actions. Multiple roles create an OR condition.
/// </remarks>
public class RequireRoleAttribute : ApiAuthorizationAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequireRoleAttribute"/> class.
/// </summary>
/// <param name="roles">One or more roles that are allowed to access the endpoint.</param>
public RequireRoleAttribute(params AuthorizationRole[] roles) : base()
{
Arguments = [new AuthorizationRequirementModel { Roles = roles }];
}
}
@@ -3,8 +3,10 @@ using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
using Lumina.Presentation.Web.Common.Filters.ExceptionFilters;
using Lumina.Presentation.Web.Common.MiddlewareFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Lumina.Presentation.Web.Common.Security;
using Lumina.Presentation.Web.Common.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
@@ -203,9 +205,14 @@ public static class PresentationWebLayerServices
// register the HTTP typed client used for the API interaction
services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
.AddHttpMessageHandler<CachedAuthorizationHandler>()
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(circuitBreakerPolicy);
services.AddScoped<CachedAuthorizationHandler>();
services.AddScoped<ApiAuthorizationFilter>();
services.AddScoped<AuthorizationRequirementModel>();
// enable access to the current HTTP context in non-controller classes
services.AddHttpContextAccessor();
@@ -213,6 +220,7 @@ public static class PresentationWebLayerServices
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IUrlService, UrlService>();
services.AddHybridCache(); // used for caching authorization roles, permissions and policies
return services;
}
@@ -0,0 +1,12 @@
namespace Lumina.Presentation.Web.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization permissions.
/// </summary>
public enum AuthorizationPermission
{
None = 0,
CanViewUsers = 1,
CanDeleteUsers = 2,
CanRegisterUsers = 3
}
@@ -0,0 +1,10 @@
namespace Lumina.Presentation.Web.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization roles.
/// </summary>
public enum AuthorizationRole
{
None = 0,
Admin = 1
}
@@ -5,7 +5,7 @@ using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Filters;
namespace Lumina.Presentation.Web.Common.Filters.ActionFilters;
/// <summary>
/// Attribute that enforces application initialization checks on controller actions.
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
/// <summary>
/// Implements authorization filter logic for API endpoints by validating user roles, permissions, and policies.
/// </summary>
public class ApiAuthorizationFilter : IAsyncAuthorizationFilter
{
private readonly IApiHttpClient _apiHttpClient;
private readonly AuthorizationRequirementModel _requirement;
/// <summary>
/// Initializes a new instance of the <see cref="ApiAuthorizationFilter"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
/// <param name="requirement">Authorization requirements to evaluate.</param>
public ApiAuthorizationFilter(IApiHttpClient apiHttpClient, AuthorizationRequirementModel requirement)
{
_apiHttpClient = apiHttpClient;
_requirement = requirement;
}
/// <summary>
/// Performs authorization for the current request.
/// </summary>
/// <param name="context">The authorization filter context.</param>
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
// get the id of the currently logged in user
Claim? currentUserIdClaim = context.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier);
// if a valid user id cannot be retrieved, authorization fails
if (currentUserIdClaim is null || string.IsNullOrWhiteSpace(currentUserIdClaim.Value) || !Guid.TryParse(currentUserIdClaim.Value, out Guid currentUserId))
context.Result = new ForbidResult();
else
{
// ask the API for the user's authorization details
GetAuthorizationResponse userAuthorization = await GetUserAuthorizationAsync(currentUserId, context.HttpContext.RequestAborted);
// if the user's authorization details don't satisfy the requested authorization details, deny the request
if (!await EvaluateAuthorizationAsync(userAuthorization))
context.Result = new ForbidResult();
}
}
/// <summary>
/// Retrieves user authorization details from the authorization service.
/// </summary>
/// <param name="userId">The Id of the user to get authorization for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The user's authorization details.</returns>
private async Task<GetAuthorizationResponse> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken)
{
return await _apiHttpClient.GetAsync<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId.ToString())}", cancellationToken);
}
/// <summary>
/// Evaluates if the user meets all authorization requirements.
/// </summary>
/// <param name="authorization">The user's authorization details.</param>
/// <returns><see langword="true"/> if the user meets all requirements, <see langword="false"/> otherwise.</returns>
private async Task<bool> EvaluateAuthorizationAsync(GetAuthorizationResponse authorization)
{
if (_requirement.Roles?.Length > 0 && !_requirement.Roles.Any(role => authorization.Roles?.Contains(role) == true))
return false;
if (_requirement.Permissions?.Length > 0 && !_requirement.Permissions.Any(permission => authorization.Permissions.Contains(permission)))
return false;
//if (_requirement.PolicyType is not null)
//{
// bool response = await _apiHttpClient.PostAsync<bool, object>($"auth/evaluate-policy/{_requirement.PolicyType.Name}", null!);
// if (!response)
// return false;
//}
await Task.CompletedTask;
return true;
}
}
@@ -15,7 +15,7 @@ using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Filters;
namespace Lumina.Presentation.Web.Common.Filters.ExceptionFilters;
/// <summary>
/// Filters API exceptions and provides centralized handling for API-related errors.
@@ -45,7 +45,7 @@ public class ApiExceptionFilter : IExceptionFilter
// check if the exception is an ApiException
if (context.Exception is ApiException apiException)
{
// Log all available details for debugging/monitoring
// log all available details for debugging/monitoring
_logger.LogError(
apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
@@ -73,9 +73,7 @@ public class ApiExceptionFilter : IExceptionFilter
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Title]}</b><br>");
if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true)
{
if (errorsObj.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty error in errorsObj.EnumerateObject())
{
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
@@ -83,8 +81,6 @@ public class ApiExceptionFilter : IExceptionFilter
foreach (JsonElement errorValue in error.Value.EnumerateArray())
errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}<br>");
}
}
}
}
else
{
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
using Microsoft.AspNetCore.Mvc;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Filters.TypeFilters;
/// <summary>
/// Authorization filter for API endpoints.
/// </summary>
/// <remarks>
/// This attribute can be applied to both classes and methods and supports multiple instances on the same target.
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class ApiAuthorizationAttribute : TypeFilterAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiAuthorizationAttribute"/> class.
/// </summary>
public ApiAuthorizationAttribute() : base(typeof(ApiAuthorizationFilter))
{
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Model for storing the authorization requirements for accessing a resource.
/// </summary>
public class AuthorizationRequirementModel
{
/// <summary>
/// The collection of roles required for accessing the resource.
/// </summary>
public AuthorizationRole[]? Roles { get; set; }
/// <summary>
/// The collection of permissions required for accessing the resource.
/// </summary>
public AuthorizationPermission[]? Permissions { get; set; }
/// <summary>
/// The type of the policy required for accessing the resource.
/// </summary>
public Type? PolicyType { get; set; }
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Represents the response model for an account authorization request.
/// </summary>
/// <param name="UserId">The Id of the user for whom the authorization is retrieved.</param>
/// <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(
Guid UserId,
AuthorizationRole[] Roles,
AuthorizationPermission[] Permissions
);
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Services;
/// <summary>
/// Delegating handler that intercepts HTTP requests to an authorization endpoint and caches the response. All other requests are forwarded directly.
/// </summary>
public class CachedAuthorizationHandler : DelegatingHandler
{
private readonly HybridCache _hybridCache;
private const string AUTHORIZATION_ENDPOINT = "/auth/get-authorization";
/// <summary>
/// Initializes a new instance of the <see cref="CachedAuthorizationHandler"/> class with the specified hybrid cache.
/// </summary>
/// <param name="hybridCache">The hybrid caching mechanism to store and retrieve authorization responses.</param>
public CachedAuthorizationHandler(HybridCache hybridCache)
{
_hybridCache = hybridCache;
}
/// <summary>
/// Processes HTTP requests and intercepts calls to the authorization endpoint to provide a cached response.
/// Other requests are forwarded to the next handler in the pipeline.
/// </summary>
/// <param name="request">The HTTP request message to process.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message from either the cache or the original API call.</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// get the called API endpoint
string requestPath = request.RequestUri!.AbsolutePath;
// if it's any endpoint other than the one for the authorization request, fire it away towards the original API service
if (!requestPath.EndsWith(AUTHORIZATION_ENDPOINT, StringComparison.OrdinalIgnoreCase))
return await base.SendAsync(request, cancellationToken);
// otherwise, check the hybrid cache to see if there is a cached authorization
string response = await _hybridCache.GetOrCreateAsync(
AUTHORIZATION_ENDPOINT,
async (cancellationToken) =>
{
// perform the actual API call if cache is empty or expired
HttpResponseMessage result = await base.SendAsync(request, cancellationToken);
return await result.Content.ReadAsStringAsync(cancellationToken);
},
new HybridCacheEntryOptions()
{
Expiration = TimeSpan.FromMinutes(5) // cache for the next five minutes
},
cancellationToken: cancellationToken
);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(response)
};
}
}
@@ -1,5 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Attributes;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Models.Libraries;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Lumina.Presentation.Web.Common.Filters.ActionFilters;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Models.UsersManagement;
using Lumina.Presentation.Web.Common.Security;
@@ -115,6 +115,16 @@ public class AuthController : Controller
return View();
}
/// <summary>
/// Displays the view for registering a new account.
/// </summary>
[AllowAnonymous]
[HttpGet("access-denied")]
public IActionResult AccessDenied()
{
return View();
}
/// <summary>
/// Registers a new account.
/// </summary>
@@ -6,7 +6,7 @@
<BaseOutputPath>$(SolutionDir)..\bin\web\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904;EXTEXP0018</WarningsNotAsErrors>
<UserSecretsId>10a94da9-18ed-4c70-a9da-b461e08958c4</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<ContainerRepository>lumina-web</ContainerRepository>
@@ -21,6 +21,7 @@
<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.10.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.10.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="9.0.0-preview.9.24556.5" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="9.0.0" />
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>Sie sind nicht berechtigt, diese Ressource anzusehen!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>You are not authorized to view this resource!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>¡No estás autorizado para ver este recurso!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>Vous n'êtes pas autorisé à voir cette ressource !</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>Non sei autorizzato a visualizzare questa risorsa!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>このリソースを表示する権限がありません!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>You are not authorized to view this resource!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>Nu aveți autorizația necesară pentru vizualizarea aceastei resurse!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>У вас нет прав для просмотра этого ресурса!</value>
</data>
</root>
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NotAllowedToAccessResource" xml:space="preserve">
<value>您无权查看此资源!</value>
</data>
</root>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Neue bibliothek hinzufügen</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Administrator</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Audio</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Authentifizierung</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Autorisierung</value>
</data>
<data name="Books" xml:space="preserve">
<value>Bücher</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Add new library</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Administrator</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Audio</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Authentication</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Authorization</value>
</data>
<data name="Books" xml:space="preserve">
<value>Books</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Agregar nueva biblioteca</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Administrador</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Audio</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Autenticación</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Autorización</value>
</data>
<data name="Books" xml:space="preserve">
<value>Libros</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Ajouter une nouvelle bibliothèque</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Administrateur</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Audio</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Authentification</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Autorisation</value>
</data>
<data name="Books" xml:space="preserve">
<value>Livres</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Aggiungi nuova libreria</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Amministratore</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Audio</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Autenticazione</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Autorizzazione</value>
</data>
<data name="Books" xml:space="preserve">
<value>Libri</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>新規ライブラリを追加</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>管理者</value>
</data>
<data name="Audio" xml:space="preserve">
<value>音声</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>認証</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>認可</value>
</data>
<data name="Books" xml:space="preserve">
<value>書籍</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Add new library</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Administrator</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Audio</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Authentication</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Authorization</value>
</data>
<data name="Books" xml:space="preserve">
<value>Books</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Adăugare bibliotecă nouă</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Administrator</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Audio</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Autentificare</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Autorizare</value>
</data>
<data name="Books" xml:space="preserve">
<value>Cărți</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>Добавить новую библиотеку</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>Администратор</value>
</data>
<data name="Audio" xml:space="preserve">
<value>Аудио</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>Аутентификация</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>Авторизация</value>
</data>
<data name="Books" xml:space="preserve">
<value>Книги</value>
</data>
@@ -126,9 +126,18 @@
<data name="AddNewLibrary" xml:space="preserve">
<value>添加新媒体库</value>
</data>
<data name="Administrator" xml:space="preserve">
<value>管理员</value>
</data>
<data name="Audio" xml:space="preserve">
<value>音频</value>
</data>
<data name="Authentication" xml:space="preserve">
<value>身份验证</value>
</data>
<data name="Authorization" xml:space="preserve">
<value>授权</value>
</data>
<data name="Books" xml:space="preserve">
<value>图书</value>
</data>
@@ -0,0 +1,14 @@
@*
/auth/access-denied/
*@
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer _localizer
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-55 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<div class="text-center w-100">
<p id="change-password-success" class="invalid-feedback f-18 w-100"><b>@_localizer["NotAllowedToAccessResource"]</b></p>
</div>
</div>
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters;
/// <summary>
/// Custom JSON converter for readonly collections.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadOnlySetConverter<T> : JsonConverter<IReadOnlySet<T>>
{
/// <summary>
/// Reads and converts JSON to a <see cref="IReadOnlySet{T}"/> object.
/// </summary>
/// <param name="reader">The JSON reader.</param>
/// <param name="typeToConvert">The type of the object to convert.</param>
/// <param name="options">The serializer options.</param>
/// <returns>The converted readonly collection.</returns>
public override IReadOnlySet<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
HashSet<T>? list = JsonSerializer.Deserialize<HashSet<T>>(ref reader, options);
return list ?? [];
}
/// <summary>
/// Writes a readonly collection object to JSON. This method is not implemented.
/// </summary>
/// <param name="writer">The JSON writer.</param>
/// <param name="value">The <see cref="IReadOnlySet{T}"/> object to write.</param>
/// <param name="options">The serializer options.</param>
public override void Write(Utf8JsonWriter writer, IReadOnlySet<T> value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value.ToList(), options);
}
}
@@ -73,6 +73,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
// create test user
UserEntity user = new()
{
Id = Guid.NewGuid(),
Username = TestUsername!,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
@@ -14,6 +14,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -98,7 +99,27 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
dbContext.Database.Migrate();
}
});
}
}
/// <summary>
/// Resets the in-memory SQLite database to its original state.
/// </summary>
public async Task ResetDatabaseAsync()
{
using IServiceScope scope = Services.CreateScope();
LuminaDbContext context = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
context.Books.RemoveRange(context.Books);
context.Libraries.RemoveRange(context.Libraries);
context.RolePermissions.RemoveRange(context.RolePermissions);
context.UserRoles.RemoveRange(context.UserRoles);
context.Roles.RemoveRange(context.Roles);
context.Permissions.RemoveRange(context.Permissions);
context.Users.RemoveRange(context.Users);
context.UserPermissions.RemoveRange(context.UserPermissions);
await context.SaveChangesAsync();
}
/// <summary>
/// Disposes the connection to the database.
@@ -1,12 +1,15 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -67,6 +70,7 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
PasswordConfirm: "TestPass123!",
Use2fa: true
);
await _apiFactory.ResetDatabaseAsync();
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
@@ -84,6 +88,9 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
// verify default permissions, roles, and role permissions are set
await VerifyDefaultSetup(result.Id);
}
[Fact]
@@ -96,6 +103,7 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
PasswordConfirm: "TestPass123!",
Use2fa: false
);
await _apiFactory.ResetDatabaseAsync();
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
@@ -112,6 +120,9 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
// verify default permissions, roles, and role permissions are set
await VerifyDefaultSetup(result.Id);
}
[Fact]
@@ -163,6 +174,35 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
.WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]);
}
private async Task VerifyDefaultSetup(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// TODO: update list when defaults change
// verify default permissions
List<PermissionEntity> permissions = await dbContext.Permissions.ToListAsync();
permissions.Should().Contain(p => p.PermissionName == AuthorizationPermission.CanViewUsers);
permissions.Should().Contain(p => p.PermissionName == AuthorizationPermission.CanDeleteUsers);
permissions.Should().Contain(p => p.PermissionName == AuthorizationPermission.CanRegisterUsers);
// verify default roles
List<RoleEntity> roles = await dbContext.Roles.ToListAsync();
RoleEntity? adminRole = roles.FirstOrDefault(r => r.RoleName == AuthorizationRole.Admin);
adminRole.Should().NotBeNull();
// verify admin role permissions
List<RolePermissionEntity> rolePermissions = await dbContext.RolePermissions
.Where(rp => rp.RoleId == adminRole!.Id)
.ToListAsync();
rolePermissions.Should().NotBeEmpty();
rolePermissions.Should().Contain(rp => permissions.Any(p => p.Id == rp.PermissionId));
// verify user has admin role
UserRoleEntity? userRole = await dbContext.UserRoles.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == adminRole!.Id);
userRole.Should().NotBeNull();
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -0,0 +1,232 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
/// <summary>
/// Contains integration tests for the <see cref="GetAuthorizationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions;
private HttpClient _client;
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetAuthorizationEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_testUsername = $"testuser_{Guid.NewGuid()}";
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
new ReadOnlySetConverter<AuthorizationPermission>(),
new ReadOnlySetConverter<AuthorizationRole>()
}
};
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldReturnAuthorizationDetails()
{
// Arrange
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = await dbContext.Users
.Include(user => user.UserRoles)
.ThenInclude(userRole => userRole.Role)
.Include(user => user.UserPermissions)
.ThenInclude(userPermission => userPermission.Permission)
.FirstAsync(user => user.Username == _apiFactory.TestUsername);
await AddRolesAndPermissionsToUser(user, dbContext);
GetAuthorizationRequest request = new(user.Id);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
GetAuthorizationResponse? result = JsonSerializer.Deserialize<GetAuthorizationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.UserId.Should().Be(user.Id);
result.Roles.Should().Contain(AuthorizationRole.Admin);
result.Permissions.Should().Contain(AuthorizationPermission.CanViewUsers);
}
[Fact]
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnForbidden()
{
// Arrange
GetAuthorizationRequest request = new(Guid.NewGuid());
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/get-authorization");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenUserIdIsEmpty_ShouldReturnValidationError()
{
// Arrange
GetAuthorizationRequest request = new(Guid.Empty);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/get-authorization");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("UserIdCannotBeEmpty");
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
{
// Arrange
GetAuthorizationRequest request = new(Guid.NewGuid());
CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
private static async Task<UserEntity> AddRolesAndPermissionsToUser(UserEntity user, LuminaDbContext dbContext)
{
RoleEntity adminRole = new()
{
Id = Guid.NewGuid(),
RoleName = AuthorizationRole.Admin,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid()
};
PermissionEntity viewUsersPermission = new()
{
Id = Guid.NewGuid(),
PermissionName = AuthorizationPermission.CanViewUsers,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid()
};
RolePermissionEntity rolePermission = new()
{
Id = Guid.NewGuid(),
Permission = viewUsersPermission,
PermissionId = viewUsersPermission.Id,
Role = adminRole,
RoleId = adminRole.Id,
CreatedBy = user.Id,
CreatedOnUtc = DateTime.UtcNow
};
UserRoleEntity userRole = new()
{
Id = Guid.NewGuid(),
UserId = user.Id,
User = user,
RoleId = adminRole.Id,
Role = adminRole,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid()
};
dbContext.Roles.Add(adminRole);
dbContext.Permissions.Add(viewUsersPermission);
dbContext.RolePermissions.Add(rolePermission);
user.UserRoles.Add(userRole);
await dbContext.SaveChangesAsync();
return user;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
await dbContext.SaveChangesAsync();
}
}
}
@@ -6,6 +6,7 @@ using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
@@ -62,6 +63,16 @@ public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposa
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
[Fact]
@@ -138,6 +149,9 @@ public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposa
return user;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authorization;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
/// <summary>
/// Contains integration tests for the <see cref="GetAuthorizationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions;
private HttpClient _client;
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetAuthorizationEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Clear();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12");
_testUsername = $"testuser_{Guid.NewGuid()}";
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
}
[Fact]
public async Task ExecuteAsync_WhenUnauthorized_ShouldReturnUnauthorized()
{
// Arrange
_client = _apiFactory.CreateClient(); // unauthenticated client
GetAuthorizationRequest request = new(Guid.NewGuid());
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/auth/get-authorization");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
_client.DefaultRequestHeaders.Authorization = null;
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Contracts.Requests.Authorization;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="GetAuthorizationRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationRequestMappingTests
{
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
Guid userId = Guid.NewGuid();
GetAuthorizationRequest request = new(userId);
// Act
GetAuthorizationQuery result = request.ToQuery();
// Assert
result.Should().NotBeNull();
result.UserId.Should().Be(request.UserId);
}
[Fact]
public void ToQuery_WhenUserIdIsNull_ShouldMapCorrectly()
{
// Arrange
GetAuthorizationRequest request = new(null);
// Act
GetAuthorizationQuery result = request.ToQuery();
// Assert
result.Should().NotBeNull();
result.UserId.Should().BeNull();
}
[Theory]
[InlineData("00000000-0000-0000-0000-000000000000")]
[InlineData("12345678-1234-1234-1234-123456789012")]
[InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF")]
public void ToQuery_WhenMappingDifferentUserIds_ShouldMapCorrectly(string userIdString)
{
// Arrange
Guid userId = Guid.Parse(userIdString);
GetAuthorizationRequest request = new(userId);
// Act
GetAuthorizationQuery result = request.ToQuery();
// Assert
result.Should().NotBeNull();
result.UserId.Should().Be(request.UserId);
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.Mapping.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.Application.UnitTests.Common.Mapping.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="UserAuthorizationEntityMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserAuthorizationEntityMappingTests
{
[Fact]
public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly()
{
// Arrange
UserAuthorizationEntity entity = new()
{
UserId = Guid.NewGuid(),
Roles = new HashSet<AuthorizationRole> { AuthorizationRole.Admin },
Permissions = new HashSet<AuthorizationPermission> { AuthorizationPermission.CanViewUsers }
};
// Act
GetAuthorizationResponse result = entity.ToResponse();
// Assert
result.Should().NotBeNull();
result.UserId.Should().Be(entity.UserId);
result.Roles.Should().BeEquivalentTo(entity.Roles);
result.Permissions.Should().BeEquivalentTo(entity.Permissions);
}
[Fact]
public void ToResponse_WhenMappingEntityWithEmptyCollections_ShouldMapCorrectly()
{
// Arrange
UserAuthorizationEntity entity = new()
{
UserId = Guid.NewGuid(),
Roles = new HashSet<AuthorizationRole>(),
Permissions = new HashSet<AuthorizationPermission>()
};
// Act
GetAuthorizationResponse result = entity.ToResponse();
// Assert
result.Should().NotBeNull();
result.UserId.Should().Be(entity.UserId);
result.Roles.Should().BeEmpty();
result.Permissions.Should().BeEmpty();
}
[Fact]
public void ToResponse_WhenMappingEntityWithMultipleRolesAndPermissions_ShouldMapCorrectly()
{
// Arrange
UserAuthorizationEntity entity = new()
{
UserId = Guid.NewGuid(),
Roles = new HashSet<AuthorizationRole>
{
AuthorizationRole.Admin,
AuthorizationRole.None
},
Permissions = new HashSet<AuthorizationPermission>
{
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers,
AuthorizationPermission.CanRegisterUsers
}
};
// Act
GetAuthorizationResponse result = entity.ToResponse();
// Assert
result.Should().NotBeNull();
result.UserId.Should().Be(entity.UserId);
result.Roles.Should().BeEquivalentTo(entity.Roles);
result.Permissions.Should().BeEquivalentTo(entity.Permissions);
}
[Theory]
[InlineData("00000000-0000-0000-0000-000000000000")]
[InlineData("12345678-1234-1234-1234-123456789012")]
[InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF")]
public void ToResponse_WhenMappingDifferentUserIds_ShouldMapCorrectly(string userIdString)
{
// Arrange
UserAuthorizationEntity entity = new()
{
UserId = Guid.Parse(userIdString),
Roles = new HashSet<AuthorizationRole> { AuthorizationRole.Admin },
Permissions = new HashSet<AuthorizationPermission> { AuthorizationPermission.CanViewUsers }
};
// Act
GetAuthorizationResponse result = entity.ToResponse();
// Assert
result.Should().NotBeNull();
result.UserId.Should().Be(entity.UserId);
result.Roles.Should().BeEquivalentTo(entity.Roles);
result.Permissions.Should().BeEquivalentTo(entity.Permissions);
}
}
@@ -3,6 +3,7 @@ using ErrorOr;
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.Seed;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -35,6 +36,7 @@ public class SetupApplicationCommandHandlerTests
private readonly IQRCodeGenerator _mockQRCodeGenerator;
private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly IDataSeedService _mockDataSeedService;
private readonly SetupApplicationCommandHandler _sut;
private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture;
@@ -50,6 +52,7 @@ public class SetupApplicationCommandHandlerTests
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDataSeedService = Substitute.For<IDataSeedService>();
_setupApplicationCommandFixture = new SetupApplicationCommandFixture();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
@@ -61,7 +64,8 @@ public class SetupApplicationCommandHandlerTests
_mockCryptographyService,
_mockTotpTokenGenerator,
_mockQRCodeGenerator,
_mockDateTimeProvider);
_mockDateTimeProvider,
_mockDataSeedService);
}
[Fact]
@@ -196,4 +200,154 @@ public class SetupApplicationCommandHandlerTests
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenSetDefaultAuthorizationPermissionsFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
Error error = Error.Failure("Database.Error", "Failed to set default permissions");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenSetDefaultAuthorizationRolesFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
Error error = Error.Failure("Database.Error", "Failed to set default roles");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenSetAdminRolePermissionsFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
Error error = Error.Failure("Database.Error", "Failed to set admin role permissions");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.DidNotReceive().SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenSetAdminRoleToAdministratorAccountFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
Error error = Error.Failure("Database.Error", "Failed to set admin role to administrator account");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenAllOperationsSucceed_ShouldReturnSuccessResponse()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Username.Should().Be(command.Username);
await _mockDataSeedService.Received(1).SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetAuthorizationQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationQueryFixture
{
/// <summary>
/// Creates a random valid query to get authorization details.
/// </summary>
/// <param name="userId">Optional user Id to use. If null, a random GUID will be generated.</param>
/// <returns>The created query.</returns>
public static GetAuthorizationQuery CreateGetAuthorizationQuery(Guid? userId = null)
{
return new Faker<GetAuthorizationQuery>()
.CustomInstantiator(f => new GetAuthorizationQuery(
userId ?? f.Random.Guid()
))
.Generate();
}
/// <summary>
/// Creates a random valid authorization entity.
/// </summary>
/// <param name="userId">Optional user Id to use. If null, a random GUID will be generated.</param>
/// <param name="isAdmin">Whether the user should have admin role.</param>
/// <returns>The created entity.</returns>
public static UserAuthorizationEntity CreateUserAuthorizationEntity(Guid? userId = null, bool isAdmin = false)
{
IReadOnlySet<AuthorizationRole> roles = isAdmin
? [AuthorizationRole.Admin]
: new HashSet<AuthorizationRole> { AuthorizationRole.None };
return new UserAuthorizationEntity
{
UserId = userId ?? Guid.NewGuid(),
Roles = roles,
Permissions = new HashSet<AuthorizationPermission>
{
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanRegisterUsers
}
};
}
}
@@ -0,0 +1,153 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures;
using Lumina.Contracts.Responses.Authorization;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization;
/// <summary>
/// Contains unit tests for the <see cref="GetAuthorizationQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationQueryHandlerTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly GetAuthorizationQueryHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationQueryHandlerTests"/> class.
/// </summary>
public GetAuthorizationQueryHandlerTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_sut = new GetAuthorizationQueryHandler(_mockAuthorizationService, _mockCurrentUserService);
}
[Fact]
public async Task Handle_WhenRequestingOwnAuthorization_ShouldReturnAuthorization()
{
// Arrange
Guid userId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(userId);
UserAuthorizationEntity authEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(userId);
_mockCurrentUserService.UserId.Returns(userId);
_mockAuthorizationService.GetUserAuthorizationAsync(userId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(authEntity));
// Act
ErrorOr<GetAuthorizationResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.UserId.Should().Be(userId);
result.Value.Roles.Should().BeEquivalentTo(authEntity.Roles);
result.Value.Permissions.Should().BeEquivalentTo(authEntity.Permissions);
}
[Fact]
public async Task Handle_WhenAdminRequestingOtherUserAuthorization_ShouldReturnAuthorization()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
UserAuthorizationEntity adminAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(adminUserId, true);
UserAuthorizationEntity targetAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(targetUserId);
_mockCurrentUserService.UserId.Returns(adminUserId);
_mockAuthorizationService.GetUserAuthorizationAsync(adminUserId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(adminAuthEntity));
_mockAuthorizationService.GetUserAuthorizationAsync(targetUserId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(targetAuthEntity));
// Act
ErrorOr<GetAuthorizationResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.UserId.Should().Be(targetUserId);
result.Value.Roles.Should().BeEquivalentTo(targetAuthEntity.Roles);
result.Value.Permissions.Should().BeEquivalentTo(targetAuthEntity.Permissions);
}
[Fact]
public async Task Handle_WhenNonAdminRequestingOtherUserAuthorization_ShouldReturnError()
{
// Arrange
Guid currentUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
UserAuthorizationEntity currentUserAuth = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(currentUserId, false);
_mockCurrentUserService.UserId.Returns(currentUserId);
_mockAuthorizationService.GetUserAuthorizationAsync(currentUserId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(currentUserAuth));
// Act
ErrorOr<GetAuthorizationResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Authorization.NotAuthorized);
}
[Fact]
public async Task Handle_WhenGetCurrentUserAuthorizationFails_ShouldReturnError()
{
// Arrange
Guid currentUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
Error error = Error.Failure("Database.Error", "Failed to get user authorization");
_mockCurrentUserService.UserId.Returns(currentUserId);
_mockAuthorizationService.GetUserAuthorizationAsync(currentUserId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<GetAuthorizationResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
}
[Fact]
public async Task Handle_WhenGetTargetUserAuthorizationFails_ShouldReturnError()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
Guid targetUserId = Guid.NewGuid();
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId);
UserAuthorizationEntity adminAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(adminUserId, true);
Error error = Error.Failure("Database.Error", "Failed to get target user authorization");
_mockCurrentUserService.UserId.Returns(adminUserId);
_mockAuthorizationService.GetUserAuthorizationAsync(adminUserId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(adminAuthEntity));
_mockAuthorizationService.GetUserAuthorizationAsync(targetUserId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<GetAuthorizationResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
}
}
@@ -0,0 +1,70 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures;
using Lumina.Domain.Common.Errors;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization;
/// <summary>
/// Contains unit tests for the <see cref="GetAuthorizationQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationQueryValidatorTests
{
private readonly GetAuthorizationQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationQueryValidatorTests"/> class.
/// </summary>
public GetAuthorizationQueryValidatorTests()
{
_validator = new GetAuthorizationQueryValidator();
}
[Fact]
public void Validate_WhenUserIdIsNull_ShouldHaveValidationError()
{
// Arrange
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
query = query with { UserId = null };
// Act
TestValidationResult<GetAuthorizationQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.UserId)
.WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenUserIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
query = query with { UserId = Guid.Empty };
// Act
TestValidationResult<GetAuthorizationQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.UserId)
.WithErrorMessage(Errors.Users.UserIdCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenUserIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
// Act
TestValidationResult<GetAuthorizationQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.UserId);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Setup;
@@ -8,6 +9,7 @@ namespace Lumina.DataAccess.UnitTests.Common.Setup;
/// <summary>
/// Fake service for retrieving the current user's information during tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class TestCurrentUserService : ICurrentUserService
{
private Guid userId;
@@ -0,0 +1,6 @@
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures;
/// <summary>
/// Repository fixture interface for testing non registered repositories.
/// </summary>
public interface IUnregisteredRepository { }
@@ -6,6 +6,7 @@ using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.DataAccess.Core.Repositories.Common.Factory;
using Lumina.DataAccess.UnitTests.Common.Setup;
using Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -50,8 +51,6 @@ public class RepositoryFactoryTests
// Act & Assert
Action act = () => repositoryFactory.CreateRepository<IUnregisteredRepository>();
act.Should().Throw<InvalidOperationException>().WithMessage("No service for type 'Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.IUnregisteredRepository' has been registered.");
act.Should().Throw<InvalidOperationException>().WithMessage("No service for type 'Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures.IUnregisteredRepository' has been registered.");
}
}
public interface IUnregisteredRepository { }
@@ -101,7 +101,7 @@ public class UserEntityFixture
UserId = _fixture.Create<Guid>(),
Title = _fixture.Create<string>(),
LibraryType = _fixture.Create<LibraryType>(),
ContentLocations = new List<LibraryContentLocationEntity>(),
ContentLocations = [],
Created = _fixture.Create<DateTime>(),
Updated = _fixture.Create<DateTime>()
});
@@ -0,0 +1,587 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.Common.Errors;
using Lumina.Infrastructure.Core.Authorization;
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
using Lumina.Infrastructure.UnitTests.Core.Authorization.Fixtures;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="AuthorizationService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthorizationServiceTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IUserRepository _mockUserRepository;
private readonly IAuthorizationPolicyFactory _mockAuthorizationPolicyFactory;
private readonly AuthorizationService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationServiceTests"/> class.
/// </summary>
public AuthorizationServiceTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockAuthorizationPolicyFactory = Substitute.For<IAuthorizationPolicyFactory>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_sut = new AuthorizationService(_mockUnitOfWork, _mockAuthorizationPolicyFactory);
}
[Fact]
public async Task HasPermissionAsync_WhenUserDoesNotExist_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(null));
// Act
bool result = await _sut.HasPermissionAsync(userId, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenGetUserFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
bool result = await _sut.HasPermissionAsync(userId, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasDirectPermission_ShouldReturnTrue()
{
// Arrange
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanViewUsers]);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
result.Should().BeTrue();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasPermissionThroughRole_ShouldReturnTrue()
{
// Arrange
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ AuthorizationRole.Admin, new[] { AuthorizationPermission.CanViewUsers } }
};
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
result.Should().BeTrue();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasNoPermissions_ShouldReturnFalse()
{
// Arrange
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions();
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasDifferentPermission_ShouldReturnFalse()
{
// Arrange
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanDeleteUsers]);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasPermissionBothDirectlyAndThroughRole_ShouldReturnTrue()
{
// Arrange
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ AuthorizationRole.Admin, new[] { AuthorizationPermission.CanViewUsers } }
};
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanViewUsers],
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
result.Should().BeTrue();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserDoesNotExist_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(null));
// Act
bool result = await _sut.IsInRoleAsync(userId, AuthorizationRole.Admin, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenGetUserFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
bool result = await _sut.IsInRoleAsync(userId, AuthorizationRole.Admin, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserHasRole_ShouldReturnTrue()
{
// Arrange
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ AuthorizationRole.Admin, Array.Empty<AuthorizationPermission>() }
};
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.IsInRoleAsync(user.Id, AuthorizationRole.Admin, CancellationToken.None);
// Assert
result.Should().BeTrue();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserHasDifferentRole_ShouldReturnFalse()
{
// Arrange
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ AuthorizationRole.None, Array.Empty<AuthorizationPermission>() }
};
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.IsInRoleAsync(user.Id, AuthorizationRole.Admin, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserHasNoRoles_ShouldReturnFalse()
{
// Arrange
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions();
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
bool result = await _sut.IsInRoleAsync(user.Id, AuthorizationRole.Admin, CancellationToken.None);
// Assert
result.Should().BeFalse();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluatePolicyAsync_WhenPolicyEvaluationSucceeds_ShouldReturnTrue()
{
// Arrange
Guid userId = Guid.NewGuid();
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
// Assert
result.Should().BeTrue();
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenPolicyEvaluationFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
// Assert
result.Should().BeFalse();
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenPolicyThrowsException_ShouldPropagateException()
{
// Arrange
Guid userId = Guid.NewGuid();
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
.Throws(new InvalidOperationException("Policy evaluation failed"));
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<InvalidOperationException>()
.WithMessage("Policy evaluation failed");
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenFactoryThrowsException_ShouldPropagateException()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Throws(new InvalidOperationException("Policy creation failed"));
// Act
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<InvalidOperationException>()
.WithMessage("Policy creation failed");
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenCancellationRequested_ShouldPropagateToken()
{
// Arrange
Guid userId = Guid.NewGuid();
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
CancellationToken cancellationToken = new(true);
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, cancellationToken);
// Assert
await mockPolicy.Received(1).EvaluateAsync(userId, cancellationToken);
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WithConcretePolicy_ShouldCreateCorrectPolicyType()
{
// Arrange
Guid userId = Guid.NewGuid();
IAuthorizationPolicy mockPolicy = Substitute.For<ITestAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationPolicyFactory.CreatePolicy<ITestAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
bool result = await _sut.EvaluatePolicyAsync<ITestAuthorizationPolicy>(userId, CancellationToken.None);
// Assert
result.Should().BeTrue();
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<ITestAuthorizationPolicy>();
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserDoesNotExist_ShouldReturnError()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(null));
// Act
ErrorOr<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Users.UserDoesNotExist);
await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenGetUserFails_ShouldReturnError()
{
// Arrange
Guid userId = Guid.NewGuid();
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasNoRolesOrPermissions_ShouldReturnEmptySets()
{
// Arrange
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions();
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
ErrorOr<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.UserId.Should().Be(user.Id);
result.Value.Roles.Should().BeEmpty();
result.Value.Permissions.Should().BeEmpty();
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasOnlyDirectPermissions_ShouldReturnCorrectPermissions()
{
// Arrange
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
directPermissions:
[
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers
]);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
ErrorOr<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.UserId.Should().Be(user.Id);
result.Value.Roles.Should().BeEmpty();
result.Value.Permissions.Should().BeEquivalentTo(
[
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers
]);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasOnlyRolePermissions_ShouldReturnCorrectRolesAndPermissions()
{
// Arrange
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{
AuthorizationRole.Admin,
new[] { AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers }
}
};
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
ErrorOr<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.UserId.Should().Be(user.Id);
result.Value.Roles.Should().BeEquivalentTo([AuthorizationRole.Admin]);
result.Value.Permissions.Should().BeEquivalentTo(
[
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers
]);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasBothDirectAndRolePermissions_ShouldReturnCombinedPermissions()
{
// Arrange
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{
AuthorizationRole.Admin,
new[] { AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers }
}
};
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanRegisterUsers],
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
ErrorOr<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.UserId.Should().Be(user.Id);
result.Value.Roles.Should().BeEquivalentTo([AuthorizationRole.Admin]);
result.Value.Permissions.Should().BeEquivalentTo(
[
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers,
AuthorizationPermission.CanRegisterUsers
]);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasMultipleRoles_ShouldReturnAllRolesAndPermissions()
{
// Arrange
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{
AuthorizationRole.Admin,
new[] { AuthorizationPermission.CanViewUsers }
},
{
AuthorizationRole.None,
new[] { AuthorizationPermission.CanDeleteUsers }
}
};
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From<UserEntity?>(user));
// Act
ErrorOr<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.UserId.Should().Be(user.Id);
result.Value.Roles.Should().BeEquivalentTo([AuthorizationRole.Admin, AuthorizationRole.None]);
result.Value.Permissions.Should().BeEquivalentTo(
[
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers
]);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Fixtures;
/// <summary>
/// Fixture class for the <see cref="AuthorizationService"/> tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthorizationServiceFixture
{
/// <summary>
/// Creates a user entity with specified permissions and roles.
/// </summary>
/// <param name="directPermissions">Direct permissions to assign to the user.</param>
/// <param name="rolePermissions">Permissions to assign through roles.</param>
/// <returns>The created user entity.</returns>
public static UserEntity CreateUserWithPermissions(
IEnumerable<AuthorizationPermission>? directPermissions = null,
Dictionary<AuthorizationRole, IEnumerable<AuthorizationPermission>>? rolePermissions = null)
{
Guid userId = Guid.NewGuid();
DateTime utcNow = DateTime.UtcNow;
List<UserPermissionEntity> userPermissions = [];
List<UserRoleEntity> userRoles = [];
UserEntity user = new()
{
Id = userId,
Username = "test-user",
Password = "hashed-password",
CreatedOnUtc = utcNow,
CreatedBy = userId,
Libraries = [],
UserPermissions = userPermissions,
UserRoles = userRoles
};
if (directPermissions is not null)
{
foreach (AuthorizationPermission permission in directPermissions)
{
Guid permissionId = Guid.NewGuid();
PermissionEntity permissionEntity = new()
{
Id = permissionId,
PermissionName = permission,
CreatedOnUtc = utcNow,
CreatedBy = userId
};
userPermissions.Add(new UserPermissionEntity
{
Id = Guid.NewGuid(),
UserId = userId,
User = user,
PermissionId = permissionId,
Permission = permissionEntity,
CreatedOnUtc = utcNow,
CreatedBy = userId
});
}
}
if (rolePermissions is not null)
{
foreach (KeyValuePair<AuthorizationRole, IEnumerable<AuthorizationPermission>> rolePerm in rolePermissions)
{
Guid roleId = Guid.NewGuid();
RoleEntity role = new()
{
Id = roleId,
RoleName = rolePerm.Key,
CreatedOnUtc = utcNow,
CreatedBy = userId,
RolePermissions = []
};
foreach (AuthorizationPermission permission in rolePerm.Value)
{
Guid permissionId = Guid.NewGuid();
PermissionEntity permissionEntity = new()
{
Id = permissionId,
PermissionName = permission,
CreatedOnUtc = utcNow,
CreatedBy = userId
};
role.RolePermissions.Add(new RolePermissionEntity
{
Id = Guid.NewGuid(),
RoleId = roleId,
Role = role,
PermissionId = permissionId,
Permission = permissionEntity,
CreatedOnUtc = utcNow,
CreatedBy = userId
});
}
userRoles.Add(new UserRoleEntity
{
Id = Guid.NewGuid(),
UserId = userId,
User = user,
RoleId = roleId,
Role = role,
CreatedOnUtc = utcNow,
CreatedBy = userId
});
}
}
return user;
}
}
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more