mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 12:11:10 +00:00
Implements Authorization system
This commit is contained in:
1 parent
5bfb2ca212
commit
2c9c210e43
68 files changed
+2734
-336
No files matched your search
@@ -1,9 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
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.Policies.Common.Factory;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Infrastructure.Core.Time;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -37,6 +40,10 @@ public static class InfrastructureLayerServices
|
||||
services.AddSingleton<ITotpTokenGenerator, TotpTokenGenerator>();
|
||||
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
|
||||
|
||||
// authorization
|
||||
services.AddScoped<IOver18Policy, Over18Policy>();
|
||||
services.AddScoped<IAuthorizationPolicyFactory, AuthorizationPolicyFactory>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing authorization.
|
||||
/// </summary>
|
||||
public class AuthorizationService : IAuthorizationService
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IAuthorizationPolicyFactory _authorizationPolicyFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationPolicyFactory">The factory used to generate authorization policies.</param>
|
||||
public AuthorizationService(IUnitOfWork unitOfWork, IAuthorizationPolicyFactory authorizationPolicyFactory)
|
||||
{
|
||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
||||
_authorizationPolicyFactory = authorizationPolicyFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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="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)
|
||||
{
|
||||
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError || getUserResult.Value is null)
|
||||
return false;
|
||||
|
||||
// check if the user has the permission directly
|
||||
if (getUserResult.Value.UserPermissions.Any(userPermission => userPermission.Permission.PermissionName == permission))
|
||||
return true;
|
||||
|
||||
// check if any of the user's roles grant the permission
|
||||
return getUserResult.Value.UserRoles
|
||||
.SelectMany(userRole => userRole.Role.RolePermissions)
|
||||
.Any(rolePermission => rolePermission.Permission.PermissionName == permission);
|
||||
}
|
||||
|
||||
/// <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="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)
|
||||
{
|
||||
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError || getUserResult.Value is null)
|
||||
return false;
|
||||
return getUserResult.Value.UserRoles.Any(userRole => userRole.Role.RoleName == role);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates whether the specified user meets the conditions defined in the specified authorization policy.
|
||||
/// </summary>
|
||||
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to evaluate.</typeparam>
|
||||
/// <param name="userId">The Id of the user for whom to evaluate the policy.</param>
|
||||
/// <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>
|
||||
public async Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(Guid userId, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy
|
||||
{
|
||||
// resolve the authorization policy dynamically using the factory
|
||||
IAuthorizationPolicy policy = _authorizationPolicyFactory.CreatePolicy<TAuthorizationPolicy>();
|
||||
return await policy.EvaluateAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
|
||||
|
||||
/// <summary>
|
||||
/// Concrete implementation for the authorization policies factory.
|
||||
/// </summary>
|
||||
public class AuthorizationPolicyFactory : IAuthorizationPolicyFactory
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationPolicyFactory"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider.</param>
|
||||
public AuthorizationPolicyFactory(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new authorization policy of type <typeparamref name="TAuthorizationPolicy"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to create.</typeparam>
|
||||
/// <returns>An authorization policy of type <typeparamref name="TAuthorizationPolicy"/>.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
|
||||
public TAuthorizationPolicy CreatePolicy<TAuthorizationPolicy>() where TAuthorizationPolicy : notnull, IAuthorizationPolicy
|
||||
{
|
||||
return _serviceProvider.GetRequiredService<TAuthorizationPolicy>() ?? throw new ArgumentException();
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the authorization policies factory.
|
||||
/// </summary>
|
||||
public interface IAuthorizationPolicyFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new authorization policy of type <typeparamref name="TAuthorizationPolicy"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to create.</typeparam>
|
||||
/// <returns>An authorization policy of type <typeparamref name="TAuthorizationPolicy"/>.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
|
||||
TAuthorizationPolicy CreatePolicy<TAuthorizationPolicy>() where TAuthorizationPolicy : notnull, IAuthorizationPolicy;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authorization.Policies.Over18;
|
||||
|
||||
/// <summary>
|
||||
/// Authorization policy that checks if a user if over 18 years old.
|
||||
/// </summary>
|
||||
public class Over18Policy : IOver18Policy
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IDateTimeProvider _dateTimeProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Over18Policy"/> 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 functionality.</param>
|
||||
public Over18Policy(IUnitOfWork unitOfWork, IDateTimeProvider dateTimeProvider)
|
||||
{
|
||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
||||
_dateTimeProvider = dateTimeProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates the policy for the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user for which to evaluate the policy.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns><see langword="true"/> if the policy evaluation succeeds, <see langword="false"/> otherwise.</returns>
|
||||
public async Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError || getUserResult.Value is null)
|
||||
return false;
|
||||
|
||||
// TODO: uncomment when Date of Birth is implemented for users registration
|
||||
//if (!getUserResult.Value.DateOfBirth.HasValue)
|
||||
// return false;
|
||||
|
||||
int age = 18; // _dateTimeProvider.UtcNow.Year - getUserResult.Value.DateOfBirth.Value.Year;
|
||||
return age >= 18;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user