mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 13:11:10 +00:00
Implements authorization caching and check in the web client
This commit is contained in:
1 parent
7bca5b1ba3
commit
8eb1b9f13c
108 files changed
+5931
-73
No files matched your search
+11
-5
@@ -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.
|
||||
|
||||
+30
@@ -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; }
|
||||
}
|
||||
+16
@@ -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>
|
||||
{
|
||||
}
|
||||
+15
@@ -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>
|
||||
{
|
||||
}
|
||||
+27
@@ -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);
|
||||
}
|
||||
+15
@@ -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));
|
||||
}
|
||||
}
|
||||
+15
-4
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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!);
|
||||
|
||||
+34
-9
@@ -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);
|
||||
|
||||
+18
@@ -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>>;
|
||||
+61
@@ -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);
|
||||
}
|
||||
}
|
||||
+23
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user