Merge pull request #81 from BinaryAlley/feature/implement-authorization-system

Implements Authorization system
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-11-22 18:06:42 +02:00
commit 118be1f8f1
68 files changed
+2734 -336

No files matched your search

@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// <summary>
/// Represents a permission that can be assigned to roles or users within the authorization system.
/// </summary>
[DebuggerDisplay("PermissionName: {PermissionName}")]
public class PermissionEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the permission.
/// </summary>
public Guid Id { get; init; }
/// <summary>
/// Gets the name of the permission.
/// </summary>
public required string PermissionName { get; init; }
/// <summary>
/// Gets the collection of role permission associations that include this permission.
/// </summary>
public required ICollection<RolePermissionEntity> RolePermissions { get; init; } = [];
/// <summary>
/// Gets the collection of user permission associations that include this permission.
/// </summary>
public required ICollection<UserPermissionEntity> UserPermissions { get; init; } = [];
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// <summary>
/// Repository entity for a permission in the authorization system.
/// </summary>
[DebuggerDisplay("RoleName: {RoleName}")]
public class RoleEntity : IStorageEntity
{
/// <summary>
/// Gets the Id of the role.
/// </summary>
public Guid Id { get; init; }
/// <summary>
/// Gets the name of the role.
/// </summary>
public required string RoleName { get; init; }
/// <summary>
/// Gets the collection of user roles associations that include this role.
/// </summary>
public required ICollection<UserRoleEntity> UserRoles { get; init; } = [];
/// <summary>
/// Gets the collection of role permission associations that include this role.
/// </summary>
public required ICollection<RolePermissionEntity> RolePermissions { get; init; } = [];
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// <summary>
/// Represents the association between a role and a permission within the authorization system.
/// </summary>
[DebuggerDisplay("Role: {Role.RoleName}, Permission: {Permission.PermissionName}")]
public class RolePermissionEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the role permission.
/// </summary>
public Guid Id { get; init; }
/// <summary>
/// Gets the Id of the role of the role permission.
/// </summary>
public required Guid RoleId { get; init; }
/// <summary>
/// Gets the role of the role permission.
/// </summary>
public required RoleEntity Role { get; init; }
/// <summary>
/// Gets the Id of the permission of the role permissions.
/// </summary>
public required Guid PermissionId { get; init; }
/// <summary>
/// Gets the permission of the role permission.
/// </summary>
public required PermissionEntity Permission { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// <summary>
/// Represents the association between a user and a permission within the authorization system.
/// </summary>
[DebuggerDisplay("User: {User.Username}, Permission: {Permission.PermissionName}")]
public class UserPermissionEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the user permission.
/// </summary>
public Guid Id { get; init; }
/// <summary>
/// Gets the Id of the user of the user permission.
/// </summary>
public required Guid UserId { get; init; }
/// <summary>
/// Gets the user of the user permission.
/// </summary>
public required UserEntity User { get; init; }
/// <summary>
/// Gets the Id of the permission of the user permission.
/// </summary>
public required Guid PermissionId { get; init; }
/// <summary>
/// Gets the permission of the user permission.
/// </summary>
public required PermissionEntity Permission { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Authorization;
/// <summary>
/// Represents the association between a user and a role within the authorization system.
/// </summary>
[DebuggerDisplay("User: {User.Username}, Role: {Role.RoleName}")]
public class UserRoleEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the user role.
/// </summary>
public Guid Id { get; init; }
/// <summary>
/// Gets the Id of the user of the user role.
/// </summary>
public required Guid UserId { get; init; }
/// <summary>
/// Gets the user of the user role.
/// </summary>
public required UserEntity User { get; init; }
/// <summary>
/// Gets the Id of the role of the user role.
/// </summary>
public required Guid RoleId { get; init; }
/// <summary>
/// Gets the role of the user role.
/// </summary>
public required RoleEntity Role { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Common;
/// <summary>
/// Interface for the properties required for auditing changes to an entity.
/// </summary>
public interface IAuditableEntity
{
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
Guid? UpdatedBy { get; set; }
}
@@ -13,14 +13,4 @@ public interface IStorageEntity
/// Gets or sets the identifier of the entity.
/// </summary>
Guid Id { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
DateTime Created { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
DateTime? Updated { get; set; }
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using System;
@@ -12,7 +13,7 @@ namespace Lumina.Application.Common.DataAccess.Entities.UsersManagement;
/// Repository entity for a user.
/// </summary>
[DebuggerDisplay("Username: {Username}")]
public class UserEntity : IStorageEntity
public class UserEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the user.
@@ -39,16 +40,6 @@ public class UserEntity : IStorageEntity
/// </summary>
public string? TotpSecret { get; set; }
/// <summary>
/// Gets or sets the optional token used for account verification or password reset.
/// </summary>
public string? VerificationToken { get; set; } // TODO: to be deleted, not used
/// <summary>
/// Gets or sets the optional date and time when the verification token was created.
/// </summary>
public DateTime? VerificationTokenCreated { get; set; } // TODO: to be deleted, not used
/// <summary>
/// Gets or sets the date and time when the temporary password used in password recovery was created.
/// </summary>
@@ -59,13 +50,33 @@ public class UserEntity : IStorageEntity
/// </summary>
public required ICollection<LibraryEntity> Libraries { get; init; } = [];
/// <summary>
/// Gets the collection of user roles associations that include this user.
/// </summary>
public required ICollection<UserRoleEntity> UserRoles { get; init; } = [];
/// <summary>
/// Gets the collection of user permission associations that include this user.
/// </summary>
public required ICollection<UserPermissionEntity> UserPermissions { get; init; } = [];
/// <summary>
/// Gets the time and date when the entity was added.
/// </summary>
public required DateTime Created { get; set; }
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets the optional time and date when the entity was updated.
/// </summary>
public DateTime? Updated { get; set; }
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public Guid? UpdatedBy { get; set; }
}
@@ -3,6 +3,7 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -13,6 +14,7 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users;
/// Interface for the repository for users.
/// </summary>
public interface IUserRepository : IRepository<UserEntity>,
IGetByIdRepositoryAction<UserEntity, Guid>,
IGetAllRepositoryAction<UserEntity>,
IInsertRepositoryAction<UserEntity>,
IUpdateRepositoryAction<UserEntity>
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.Infrastructure.Authentication;
/// <summary>
/// Defines a contract for accessing the current user's information.
/// </summary>
public interface ICurrentUserService
{
/// <summary>
/// Gets the unique identifier of the currently authenticated user. Returns <see langword="null"/> if no user is authenticated.
/// </summary>
Guid? UserId { get; }
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Infrastructure.Authorization;
/// <summary>
/// Interface for the service for managing authorization.
/// </summary>
public interface IAuthorizationService
{
/// <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>
Task<bool> HasPermissionAsync(Guid userId, string 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="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);
/// <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>
Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(Guid userId, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy;
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
/// <summary>
/// Defines a contract for policy evaluation in the application.
/// </summary>
public interface IAuthorizationPolicy
{
/// <summary>
/// Evaluates a policy for a 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>
Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken);
}
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
#endregion
namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
/// <summary>
/// Interface for the Over18 authorization policy.
/// </summary>
public interface IOver18Policy : IAuthorizationPolicy
{
}
@@ -20,8 +20,8 @@ public static class UserEntityMapping
return new UserResponse(
repositoryEntity.Id,
repositoryEntity.Username,
repositoryEntity.Created,
repositoryEntity.Updated
repositoryEntity.CreatedOnUtc,
repositoryEntity.UpdatedOnUtc
);
}
}
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
@@ -27,6 +28,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
private readonly ICryptographyService _cryptographyService;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationCommandHandler"/> class.
@@ -36,18 +38,21 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <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>
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator)
IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_cryptographyService = cryptographyService;
_totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
@@ -69,13 +74,17 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
return Errors.Authorization.AdminAccountAlreadyCreated;
// no users are present, register the admin one
string? totpSecret = null;
Guid id = Guid.NewGuid();
UserEntity user = new()
{
Id = Guid.NewGuid(),
Id = id,
Username = request.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
Created = DateTime.UtcNow,
Libraries = []
CreatedOnUtc = _dateTimeProvider.UtcNow,
Libraries = [],
UserPermissions = [], // TODO: implement default roles and permissions
UserRoles = [],
CreatedBy = id
};
// if the user enabled two factor auth, include a QR with the totp secret
if (request.Use2fa)
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
@@ -25,6 +26,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
private readonly ICryptographyService _cryptographyService;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterUserCommandHandler"/> class.
@@ -34,18 +36,21 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <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>
public RegisterUserCommandHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
ICryptographyService cryptographyService,
ITotpTokenGenerator totpTokenGenerator,
IQRCodeGenerator qRCodeGenerator)
IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_cryptographyService = cryptographyService;
_totpTokenGenerator = totpTokenGenerator;
_qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
@@ -66,13 +71,17 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
else if (resultSelectUser.Value is not null)
return Errors.Authentication.UsernameAlreadyExists;
string? totpSecret = null;
Guid id = Guid.NewGuid();
UserEntity user = new()
{
Id = Guid.NewGuid(),
Id = id,
Username = request.Username!,
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
Created = DateTime.UtcNow,
Libraries = []
CreatedOnUtc = _dateTimeProvider.UtcNow,
Libraries = [],
UserPermissions = [],
UserRoles = [],
CreatedBy = id
};
// if the user enabled two factor auth, include a QR with the totp secret
if (request.Use2fa)
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
@@ -25,6 +26,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
private readonly IJwtTokenGenerator _jwtTokenGenerator;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly ICryptographyService _cryptographyService;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryHandler"/> class.
@@ -34,18 +36,21 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
/// <param name="jwtTokenGenerator">Injected service for generating JWT tokens.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
public LoginUserQueryHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IJwtTokenGenerator jwtTokenGenerator,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService)
ICryptographyService cryptographyService,
IDateTimeProvider dateTimeProvider)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_jwtTokenGenerator = jwtTokenGenerator;
_totpTokenGenerator = totpTokenGenerator;
_cryptographyService = cryptographyService;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
@@ -72,7 +77,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
if (resultSelectUser.Value.TempPassword is not null)
{
// the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < DateTime.UtcNow)
if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow)
{
resultSelectUser.Value.TempPassword = null;
resultSelectUser.Value.TempPasswordCreated = null;
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="PermissionEntity"/> entity.
/// </summary>
public class PermissionConfiguration : IEntityTypeConfiguration<PermissionEntity>
{
/// <summary>
/// Configures the <see cref="PermissionEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<PermissionEntity> builder)
{
builder.ToTable("Permissions");
builder.HasKey(permission => permission.Id);
builder.Property(permission => permission.Id)
.ValueGeneratedOnAdd()
.HasColumnOrder(0);
builder.Property(permission => permission.PermissionName)
.IsRequired()
.HasMaxLength(100)
.HasColumnOrder(1);
// audit
builder.Property(permission => permission.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(2);
builder.Property(permission => permission.CreatedBy)
.IsRequired()
.HasColumnOrder(3);
builder.Property(permission => permission.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(4);
builder.Property(permission => permission.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(5);
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="RoleEntity"/> entity.
/// </summary>
public class RoleConfiguration : IEntityTypeConfiguration<RoleEntity>
{
/// <summary>
/// Configures the <see cref="RoleEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<RoleEntity> builder)
{
builder.ToTable("Roles");
builder.HasKey(role => role.Id);
builder.Property(role => role.Id)
.ValueGeneratedOnAdd()
.HasColumnOrder(0);
builder.Property(role => role.RoleName)
.IsRequired()
.HasMaxLength(100)
.HasColumnOrder(1);
// audit
builder.Property(role => role.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(2);
builder.Property(role => role.CreatedBy)
.IsRequired()
.HasColumnOrder(3);
builder.Property(role => role.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(4);
builder.Property(role => role.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(5);
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="RolePermissionEntity"/> entity.
/// </summary>
public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermissionEntity>
{
/// <summary>
/// Configures the <see cref="RolePermissionEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<RolePermissionEntity> builder)
{
builder.ToTable("RolePermissions");
// composite primary key
builder.HasKey(rolePermission => new { rolePermission.RoleId, rolePermission.PermissionId });
// foreign key: Role
builder.HasOne(rolePermission => rolePermission.Role)
.WithMany(user => user.RolePermissions)
.HasForeignKey(rolePermission => rolePermission.RoleId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade); // deleting a Role deletes associated RolePermission
// foreign key: Permission
builder.HasOne(rolePermission => rolePermission.Permission)
.WithMany(role => role.RolePermissions)
.HasForeignKey(rolePermission => rolePermission.PermissionId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade); // deleting a Permission deletes associated RolePermission
// audit
builder.Property(rolePermission => rolePermission.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(1);
builder.Property(rolePermission => rolePermission.CreatedBy)
.IsRequired()
.HasColumnOrder(2);
builder.Property(rolePermission => rolePermission.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(3);
builder.Property(rolePermission => rolePermission.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(4);
// indexes
builder.HasIndex(userRole => new { userRole.RoleId, userRole.PermissionId })
.IsUnique();
}
}
@@ -33,24 +33,53 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
.HasColumnOrder(2);
builder.Property(user => user.TempPassword)
.HasDefaultValue(null)
.HasColumnOrder(3);
builder.Property(user => user.TotpSecret)
.HasDefaultValue(null)
.HasColumnOrder(4);
builder.Property(user => user.VerificationToken)
builder.Property(user => user.TempPasswordCreated)
.HasDefaultValue(null)
.HasColumnOrder(5);
builder.Property(user => user.VerificationTokenCreated)
.HasColumnOrder(6);
builder.Property(user => user.TempPasswordCreated)
.HasColumnOrder(7);
// relationships
builder.HasMany(user => user.Libraries)
.WithOne(library => library.User)
.HasForeignKey(library => library.UserId)
.IsRequired() // a library must have a user
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(user => user.UserRoles)
.WithOne(userRole => userRole.User)
.HasForeignKey(userRole => userRole.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(user => user.UserPermissions)
.WithOne(userPermission => userPermission.User)
.HasForeignKey(userPermission => userPermission.UserId)
.OnDelete(DeleteBehavior.Cascade);
// audit
builder.Property(user => user.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(6);
builder.Property(user => user.CreatedBy)
.IsRequired()
.HasColumnOrder(7);
builder.Property(user => user.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(8);
builder.Property(user => user.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(9);
// indexes
builder.HasIndex(user => user.Username)
.IsUnique(); // queried frequently
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="UserPermissionEntity"/> entity.
/// </summary>
public class UserPermissionConfiguration : IEntityTypeConfiguration<UserPermissionEntity>
{
/// <summary>
/// Configures the <see cref="UserPermissionEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<UserPermissionEntity> builder)
{
builder.ToTable("UserPermissions");
// composite primary key
builder.HasKey(userPermission => new { userPermission.UserId, userPermission.PermissionId });
// foreign key: User
builder.HasOne(userPermission => userPermission.User)
.WithMany(user => user.UserPermissions)
.HasForeignKey(userPermission => userPermission.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade); // deleting a User deletes associated UserPermissions
// foreign key: Permission
builder.HasOne(userPermission => userPermission.Permission)
.WithMany(role => role.UserPermissions)
.HasForeignKey(userPermission => userPermission.PermissionId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade); // deleting a Permission deletes associated UserPermissions
// audit
builder.Property(userPermission => userPermission.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(1);
builder.Property(userPermission => userPermission.CreatedBy)
.IsRequired()
.HasColumnOrder(2);
builder.Property(userPermission => userPermission.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(3);
builder.Property(userPermission => userPermission.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(4);
// indexes
builder.HasIndex(userRole => new { userRole.UserId, userRole.PermissionId })
.IsUnique();
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="UserRoleEntity"/> entity.
/// </summary>
public class UserRoleConfiguration : IEntityTypeConfiguration<UserRoleEntity>
{
/// <summary>
/// Configures the <see cref="UserRoleEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<UserRoleEntity> builder)
{
builder.ToTable("UserRoles");
// composite primary key
builder.HasKey(userRole => new { userRole.UserId, userRole.RoleId });
// foreign key: User
builder.HasOne(userRole => userRole.User)
.WithMany(user => user.UserRoles)
.HasForeignKey(userRole => userRole.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade); // deleting a User deletes associated UserRoles
// foreign key: Role
builder.HasOne(userRole => userRole.Role)
.WithMany(role => role.UserRoles)
.HasForeignKey(userRole => userRole.RoleId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade); // deleting a Role deletes associated UserRoles
// audit
builder.Property(userRole => userRole.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(1);
builder.Property(userRole => userRole.CreatedBy)
.IsRequired()
.HasColumnOrder(2);
builder.Property(userRole => userRole.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(3);
builder.Property(userRole => userRole.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(4);
// indexes
builder.HasIndex(userRole => new { userRole.UserId, userRole.RoleId })
.IsUnique();
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.Repositories.Common.Factory;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
@@ -31,11 +32,13 @@ public static class DataAccessLayerServices
string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(basePath))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
services.AddDbContext<LuminaDbContext>(options =>
services.AddDbContext<LuminaDbContext>((serviceProvider, options) =>
{
options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}");
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
});
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<UpdateAuditableEntitiesInterceptor>();
Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes();
Type? genericRepositoryType = typeof(IRepository<>);
@@ -45,16 +48,16 @@ public static class DataAccessLayerServices
services.AddScoped(iRepositoryFactoryType!, repositoryFactoryType!);
// get all classes implementing IRepository (all repository classes) and register them as their corresponding repository interface
IEnumerable<Type> repositoryTypes = dataAccessLayerTypes.Where(t => !t.IsInterface &&
t.GetInterfaces()
.Any(i => i.IsGenericType &&
i.GetGenericTypeDefinition() == genericRepositoryType));
IEnumerable<Type> repositoryTypes = dataAccessLayerTypes.Where(type => !type.IsInterface &&
type.GetInterfaces()
.Any(type => type.IsGenericType &&
type.GetGenericTypeDefinition() == genericRepositoryType));
foreach (Type type in repositoryTypes)
{
services.AddScoped(type.GetInterfaces() // TODO: change to scoped when DbContext is implemented
.Where(i => !i.IsGenericType &&
i.GetInterfaces()
.Any(j => j.GetGenericTypeDefinition() == genericRepositoryType))
.Where(type => !type.IsGenericType &&
type.GetInterfaces()
.Any(type => type.GetGenericTypeDefinition() == genericRepositoryType))
.First(), type);
}
}
@@ -0,0 +1,111 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Common.Interceptors;
/// <summary>
/// Interceptor for updating audit fields automatically for entities implementing <see cref="IAuditableEntity"/>.
/// </summary>
public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
{
private readonly ICurrentUserService _currentUserService;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAuditableEntitiesInterceptor"/> class.
/// </summary>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
public UpdateAuditableEntitiesInterceptor(ICurrentUserService currentUserService, IDateTimeProvider dateTimeProvider)
{
_currentUserService = currentUserService;
_dateTimeProvider = dateTimeProvider;
}
/// <summary>
/// Intercepts the synchronous SaveChanges operation to update audit fields.
/// </summary>
/// <param name="eventData">The event data containing the <see cref="DbContext"/>.</param>
/// <param name="result">The result of the SaveChanges operation.</param>
/// <returns>The interception result.</returns>
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
UpdateAuditableEntities(eventData.Context);
return base.SavingChanges(eventData, result);
}
/// <summary>
/// Intercepts the asynchronous SaveChangesAsync operation to update audit fields.
/// </summary>
/// <param name="eventData">The event data containing the <see cref="DbContext"/>.</param>
/// <param name="result">The result of the SaveChanges operation.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A <see cref="ValueTask"/> containing the interception result.</returns>
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
UpdateAuditableEntities(eventData.Context);
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
/// <summary>
/// Updates the audit fields for all changed entities that implement IAuditableEntity.
/// </summary>
/// <param name="context">The <see cref="DbContext"/> containing the entities to update.</param>
private void UpdateAuditableEntities(DbContext? context)
{
if (context is null)
return;
Guid? userId = _currentUserService.UserId;
DateTime utcNow = _dateTimeProvider.UtcNow;
// retrieve all entities implementing IAuditableEntity that are being tracked and have either Added or Modified state
foreach (EntityEntry<IAuditableEntity> entry in context.ChangeTracker.Entries<IAuditableEntity>())
{
if (entry.State == EntityState.Added)
SetCreationProperties(entry.Entity, userId, utcNow);
else if(entry.State == EntityState.Modified)
SetModificationProperties(entry, userId, utcNow);
}
}
/// <summary>
/// Sets the creation audit properties for a newly added entity.
/// </summary>
/// <param name="entity">The entity being created.</param>
/// <param name="userId">The Id of the user creating the entity.</param>
/// <param name="utcNow">The current UTC timestamp.</param>
private static void SetCreationProperties(IAuditableEntity entity, Guid? userId, DateTime utcNow)
{
entity.CreatedOnUtc = utcNow;
entity.CreatedBy = userId ?? default;
entity.UpdatedOnUtc = null;
entity.UpdatedBy = null;
}
/// <summary>
/// Sets the modification audit properties for an updated entity while protecting creation properties.
/// </summary>
/// <param name="entry">The entity entry being modified.</param>
/// <param name="userId">The Id of the user modifying the entity.</param>
/// <param name="utcNow">The current UTC timestamp.</param>
private static void SetModificationProperties(EntityEntry<IAuditableEntity> entry, Guid? userId, DateTime utcNow)
{
// prevent modification of creation properties
entry.Property(auditableEntity => auditableEntity.CreatedOnUtc).IsModified = false;
entry.Property(auditableEntity => auditableEntity.CreatedBy).IsModified = false;
// set modification properties
entry.Entity.UpdatedOnUtc = utcNow;
entry.Entity.UpdatedBy = userId;
}
}
@@ -0,0 +1,706 @@
// <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("20241122152616_AddRolesAndPermissions")]
partial class AddRolesAndPermissions
{
/// <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(3);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("PermissionName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
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(3);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
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>("Id")
.HasColumnType("TEXT");
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>("Id")
.HasColumnType("TEXT");
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>("Id")
.HasColumnType("TEXT");
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,331 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations;
/// <inheritdoc />
public partial class AddRolesAndPermissions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Updated",
table: "Users");
migrationBuilder.RenameColumn(
name: "VerificationTokenCreated",
table: "Users",
newName: "UpdatedOnUtc");
migrationBuilder.RenameColumn(
name: "VerificationToken",
table: "Users",
newName: "UpdatedBy");
migrationBuilder.RenameColumn(
name: "Created",
table: "Users",
newName: "CreatedOnUtc");
migrationBuilder.AlterColumn<DateTime>(
name: "TempPasswordCreated",
table: "Users",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 7);
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "Users",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 8)
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AlterColumn<Guid>(
name: "UpdatedBy",
table: "Users",
type: "TEXT",
nullable: true,
oldClrType: typeof(string),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 9)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<DateTime>(
name: "CreatedOnUtc",
table: "Users",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 6);
migrationBuilder.AddColumn<Guid>(
name: "CreatedBy",
table: "Users",
type: "TEXT",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"))
.Annotation("Relational:ColumnOrder", 7);
migrationBuilder.CreateTable(
name: "Permissions",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
PermissionName = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Permissions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Roles",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
RoleName = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Roles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "UserPermissions",
columns: table => new
{
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true),
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
PermissionId = table.Column<Guid>(type: "TEXT", nullable: false),
Id = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserPermissions", x => new { x.UserId, x.PermissionId });
table.ForeignKey(
name: "FK_UserPermissions_Permissions_PermissionId",
column: x => x.PermissionId,
principalTable: "Permissions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserPermissions_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "RolePermissions",
columns: table => new
{
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true),
RoleId = table.Column<Guid>(type: "TEXT", nullable: false),
PermissionId = table.Column<Guid>(type: "TEXT", nullable: false),
Id = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RolePermissions", x => new { x.RoleId, x.PermissionId });
table.ForeignKey(
name: "FK_RolePermissions_Permissions_PermissionId",
column: x => x.PermissionId,
principalTable: "Permissions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_RolePermissions_Roles_RoleId",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "UserRoles",
columns: table => new
{
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true),
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
RoleId = table.Column<Guid>(type: "TEXT", nullable: false),
Id = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_UserRoles_Roles_RoleId",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserRoles_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Users_Username",
table: "Users",
column: "Username",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_RolePermissions_PermissionId",
table: "RolePermissions",
column: "PermissionId");
migrationBuilder.CreateIndex(
name: "IX_RolePermissions_RoleId_PermissionId",
table: "RolePermissions",
columns: new[] { "RoleId", "PermissionId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserPermissions_PermissionId",
table: "UserPermissions",
column: "PermissionId");
migrationBuilder.CreateIndex(
name: "IX_UserPermissions_UserId_PermissionId",
table: "UserPermissions",
columns: new[] { "UserId", "PermissionId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserRoles_RoleId",
table: "UserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_UserRoles_UserId_RoleId",
table: "UserRoles",
columns: new[] { "UserId", "RoleId" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "RolePermissions");
migrationBuilder.DropTable(
name: "UserPermissions");
migrationBuilder.DropTable(
name: "UserRoles");
migrationBuilder.DropTable(
name: "Permissions");
migrationBuilder.DropTable(
name: "Roles");
migrationBuilder.DropIndex(
name: "IX_Users_Username",
table: "Users");
migrationBuilder.DropColumn(
name: "CreatedBy",
table: "Users");
migrationBuilder.RenameColumn(
name: "UpdatedOnUtc",
table: "Users",
newName: "VerificationTokenCreated");
migrationBuilder.RenameColumn(
name: "UpdatedBy",
table: "Users",
newName: "VerificationToken");
migrationBuilder.RenameColumn(
name: "CreatedOnUtc",
table: "Users",
newName: "Created");
migrationBuilder.AlterColumn<DateTime>(
name: "TempPasswordCreated",
table: "Users",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 7)
.OldAnnotation("Relational:ColumnOrder", 5);
migrationBuilder.AlterColumn<DateTime>(
name: "VerificationTokenCreated",
table: "Users",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 6)
.OldAnnotation("Relational:ColumnOrder", 8);
migrationBuilder.AlterColumn<string>(
name: "VerificationToken",
table: "Users",
type: "TEXT",
nullable: true,
oldClrType: typeof(Guid),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 5)
.OldAnnotation("Relational:ColumnOrder", 9);
migrationBuilder.AlterColumn<DateTime>(
name: "Created",
table: "Users",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AddColumn<DateTime>(
name: "Updated",
table: "Users",
type: "TEXT",
nullable: true);
}
}
@@ -15,7 +15,7 @@ namespace Lumina.DataAccess.Common.Migrations
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.10");
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
modelBuilder.Entity("BookGenres", b =>
{
@@ -47,6 +47,185 @@ namespace Lumina.DataAccess.Common.Migrations
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(3);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("PermissionName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
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(3);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
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>("Id")
.HasColumnType("TEXT");
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>("Id")
.HasColumnType("TEXT");
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>("Id")
.HasColumnType("TEXT");
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")
@@ -254,8 +433,13 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<DateTime>("Created")
.HasColumnType("TEXT");
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<string>("Password")
.IsRequired()
@@ -268,14 +452,19 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<DateTime?>("TempPasswordCreated")
.HasColumnType("TEXT")
.HasColumnOrder(7);
.HasColumnOrder(5);
b.Property<string>("TotpSecret")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<DateTime?>("Updated")
.HasColumnType("TEXT");
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("Username")
.IsRequired()
@@ -283,16 +472,11 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<string>("VerificationToken")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<DateTime?>("VerificationTokenCreated")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
@@ -326,6 +510,63 @@ namespace Lumina.DataAccess.Common.Migrations
.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")
@@ -375,8 +616,7 @@ namespace Lumina.DataAccess.Common.Migrations
b1.Property<Guid>("BookId")
.HasColumnType("TEXT");
b1.Property<decimal?>("MaxValue")
.IsRequired()
b1.Property<decimal>("MaxValue")
.HasColumnType("decimal(3,2)");
b1.Property<string>("Source")
@@ -384,8 +624,7 @@ namespace Lumina.DataAccess.Common.Migrations
.HasMaxLength(50)
.HasColumnType("TEXT");
b1.Property<decimal?>("Value")
.IsRequired()
b1.Property<decimal>("Value")
.HasColumnType("decimal(3,2)");
b1.Property<int?>("VoteCount")
@@ -436,9 +675,27 @@ namespace Lumina.DataAccess.Common.Migrations
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
}
@@ -1,4 +1,4 @@
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
/// <summary>
/// Interface for the repositories factory.
@@ -6,9 +6,10 @@
public interface IRepositoryFactory
{
/// <summary>
/// Creates a new repository of type <typeparamref name="TResult"/>.
/// Creates a new repository of type <typeparamref name="TRepository"/>.
/// </summary>
/// <typeparam name="TResult">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TResult"/>.</returns>
TResult CreateRepository<TResult>() where TResult : notnull;
}
/// <typeparam name="TRepository">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
TRepository CreateRepository<TRepository>() where TRepository : notnull;
}
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
@@ -22,13 +22,13 @@ public class RepositoryFactory : IRepositoryFactory
}
/// <summary>
/// Creates a new repository of type <typeparamref name="TResult"/>.
/// Creates a new repository of type <typeparamref name="TRepository"/>.
/// </summary>
/// <typeparam name="TResult">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TResult"/>.</returns>
/// <typeparam name="TRepository">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
public TResult CreateRepository<TResult>() where TResult : notnull
public TRepository CreateRepository<TRepository>() where TRepository : notnull
{
return _serviceProvider.GetRequiredService<TResult>() ?? throw new ArgumentException();
return _serviceProvider.GetRequiredService<TRepository>() ?? throw new ArgumentException();
}
}
}
@@ -1,13 +1,14 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Users;
@@ -62,7 +63,17 @@ internal sealed class UserRepository : IUserRepository
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="UserEntity"/> if found, or an error.</returns>
public async Task<ErrorOr<UserEntity?>> GetByUsernameAsync(string username, CancellationToken cancellationToken)
{
return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false);
return await _luminaDbContext.Users
.Include(user => user.Libraries)
.ThenInclude(library => library.ContentLocations)
.Include(user => user.UserPermissions)
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRoles)
.ThenInclude(userRole => userRole.Role)
.ThenInclude(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.FirstOrDefaultAsync(user => user.Username == username, cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
@@ -73,10 +84,41 @@ internal sealed class UserRepository : IUserRepository
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Updated>> UpdateAsync(UserEntity data, CancellationToken cancellationToken)
{
UserEntity? foundUser = await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken).ConfigureAwait(false);
UserEntity? foundUser = await _luminaDbContext.Users
.Include(user => user.Libraries)
.ThenInclude(library => library.ContentLocations)
.Include(user => user.UserPermissions)
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRoles)
.ThenInclude(userRole => userRole.Role)
.ThenInclude(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken)
.ConfigureAwait(false);
if (foundUser is null)
return Errors.Users.UserDoesNotExist;
_luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data);
return Result.Updated;
}
/// <summary>
/// Gets a <see cref="UserEntity"/> identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the user 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="UserEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<ErrorOr<UserEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Users
.Include(user => user.Libraries)
.ThenInclude(library => library.ContentLocations)
.Include(user => user.UserPermissions)
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRoles)
.ThenInclude(userRole => userRole.Role)
.ThenInclude(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.FirstOrDefaultAsync(user => user.Id == id, cancellationToken)
.ConfigureAwait(false);
}
}
@@ -1,16 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Events;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.UoW;
@@ -25,6 +20,11 @@ public class LuminaDbContext : DbContext
public virtual DbSet<BookEntity> Books { get; set; } = null!;
public virtual DbSet<UserEntity> Users { get; set; } = null!;
public virtual DbSet<LibraryEntity> Libraries { get; set; } = null!;
public virtual DbSet<RoleEntity> Roles { get; set; } = null!;
public virtual DbSet<UserRoleEntity> UserRoles { get; set; } = null!;
public virtual DbSet<PermissionEntity> Permissions { get; set; } = null!;
public virtual DbSet<UserPermissionEntity> UserPermissions { get; set; } = null!;
public virtual DbSet<RolePermissionEntity> RolePermissions { get; set; } = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
@@ -46,51 +46,4 @@ public class LuminaDbContext : DbContext
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// Overrides the SaveChanges method of the DbContext class to automatically set the Created and Updated properties of entities that implement the <see cref="IStorageEntity"/>.
/// </summary>
/// <returns>The number of objects written to the underlying database.</returns>
public override int SaveChanges()
{
HandleTimestamps();
return base.SaveChanges();
}
/// <summary>
/// Overrides the SaveChangesAsync method of the DbContext class to automatically set the Created and Updated properties of entities that implement the <see cref="IStorageEntity"/>.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns>A <see cref="Task"/> containing the number of objects written to the underlying database.</returns>
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
HandleTimestamps();
return base.SaveChangesAsync(cancellationToken);
}
/// <summary>
/// Updates timestamp properties for tracked entities implementing <see cref="IStorageEntity"/> based on their state in the change tracker.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description><c>Created</c>: Set for added entities.</description></item>
/// <item><description><c>Updated</c>: Set for modified entities.</description></item>
/// </list>
/// </remarks>
private void HandleTimestamps()
{
// get all the entity entries that are either added or modified
IEnumerable<EntityEntry> entries = ChangeTracker.Entries()
.Where(entity => entity.Entity is IStorageEntity &&
(entity.State is EntityState.Added or EntityState.Modified));
foreach (EntityEntry? entityEntry in entries)
{
// if the entity is in Added state, set the Created property to the current date and time
if (entityEntry.State == EntityState.Added)
((IStorageEntity)entityEntry.Entity).Created = DateTime.UtcNow;
// otherwise, if the entity is in Modified state, set the Updated property to the current date and time
else if (entityEntry.State == EntityState.Modified)
((IStorageEntity)entityEntry.Entity).Updated = DateTime.UtcNow;
}
}
}
@@ -244,7 +244,7 @@ public sealed class Book : AggregateRoot<BookId>
googleBooksId,
barnesAndNobleId,
appleBooksId,
DateTime.UtcNow,
DateTime.UtcNow, // TODO: should be IDateTimeProvider
default,
isbns,
contributors,
@@ -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);
}
}
@@ -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();
}
}
@@ -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;
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
#endregion
namespace Lumina.Presentation.Api.Common.Authentication;
/// <summary>
/// Service for retrieving the current user's information from the HTTP context.
/// </summary>
public class HttpContextCurrentUserService : ICurrentUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;
/// <summary>
/// Initializes a new instance of the <see cref="HttpContextCurrentUserService"/> class.
/// </summary>
/// <param name="httpContextAccessor">The <see cref="IHttpContextAccessor"/> used to access the current HTTP context.</param>
public HttpContextCurrentUserService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
/// Gets the unique identifier of the currently authenticated user. Returns <see langword="null"/> if no user is authenticated or if the claim is not present.
/// </summary>
public Guid? UserId
{
get
{
string? userIdClaim = _httpContextAccessor.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return Guid.TryParse(userIdClaim, out Guid userId) ? userId : null;
}
}
}
@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Presentation.Api.Common.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
@@ -206,6 +208,8 @@ public static class PresentationApiLayerServices
.AllowAnyHeader());
});
services.AddScoped<ICurrentUserService, HttpContextCurrentUserService>();
return services;
}
}
-7
View File
@@ -66,8 +66,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "books", "books", "{FAFD9E43
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IntegrationTests", "IntegrationTests", "{3F057926-562F-4EF4-BFC0-EE62372D4551}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.DataAccess.IntegrationTests", "..\tests\IntegrationTests\Lumina.DataAccess.IntegrationTests\Lumina.DataAccess.IntegrationTests.csproj", "{6B3FC07B-6208-4544-ACFB-79243A59EA1A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Api.IntegrationTests\Lumina.Presentation.Api.IntegrationTests.csproj", "{3680DAFB-10BA-4A0F-AE40-620D06DAF617}"
EndProject
Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{D4C61542-FC91-47FA-B1D2-11CC99617454}"
@@ -136,10 +134,6 @@ Global
{4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4D5E4789-8437-4F3B-883E-28BBF8A4848F}.Release|Any CPU.Build.0 = Release|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6B3FC07B-6208-4544-ACFB-79243A59EA1A}.Release|Any CPU.Build.0 = Release|Any CPU
{3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3680DAFB-10BA-4A0F-AE40-620D06DAF617}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -182,7 +176,6 @@ Global
{C17A1188-FA69-42BC-92E6-4F91D31B3A58} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2}
{FAFD9E43-508B-4F20-8AA2-8CADA697ED2D} = {C17A1188-FA69-42BC-92E6-4F91D31B3A58}
{3F057926-562F-4EF4-BFC0-EE62372D4551} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11}
{6B3FC07B-6208-4544-ACFB-79243A59EA1A} = {3F057926-562F-4EF4-BFC0-EE62372D4551}
{3680DAFB-10BA-4A0F-AE40-620D06DAF617} = {3F057926-562F-4EF4-BFC0-EE62372D4551}
{6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC} = {3C316ABB-08D5-4450-9A4E-91059DB54254}
{A0D07244-9CB2-4E30-85A5-97D520E4B9CC} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2}
@@ -1,23 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.Repositories.Common.Factory;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Common.Factory;
/// <summary>
/// Contains integration tests for the <see cref="RepositoryFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RepositoryFactoryTests
{
[Fact]
public void RepositoryFactoryImplementsRepositoryFactoryInterface_InterfaceIsImplemented_ReturnsTrue()
{
// Arrange
RepositoryFactory repositoryFactory = new(null!);
// Assert
Assert.True(repositoryFactory is IRepositoryFactory);
}
}
@@ -1,30 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.DataAccess.Core.UoW;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.UoW;
/// <summary>
/// Contains integration tests for the <see cref="UnitOfWork"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UnitOfWorkTests
{
[Fact]
public void UnitOfWorkImplementsUnitOfWorkInterface_InterfaceIsImplemented_ReturnsTrue()
{
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
// Assert
Assert.True(unitOfWork is IUnitOfWork);
}
}
@@ -1,44 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.49">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Lumina.DataAccess\Lumina.DataAccess.csproj" />
</ItemGroup>
</Project>
@@ -76,7 +76,10 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
Username = TestUsername!,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.UoW;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting;
@@ -69,7 +70,11 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
if (descriptor is not null)
services.Remove(descriptor);
// add SQLite DbContext configuration
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite(_connection));
services.AddDbContext<LuminaDbContext>((serviceProvider, options) =>
{
options.UseSqlite(_connection);
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
});
// configure JWT authentication for testing
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
@@ -119,7 +119,10 @@ public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLumin
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -173,7 +173,10 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [], // TODO: test default role and permissions?
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -245,7 +245,10 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -265,7 +268,10 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
Password = _hashService.HashString("TestPass123!"),
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -285,7 +291,10 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
TempPasswordCreated = DateTime.UtcNow,
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -305,7 +314,10 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old)
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -242,7 +242,10 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
Password = _hashService.HashString("OldPass123!"),
TotpSecret = null, // No TOTP configured
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(userWithoutTotp);
await dbContext.SaveChangesAsync();
@@ -306,7 +309,10 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
Password = _hashService.HashString("OldPass123!"),
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -325,7 +331,10 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
Password = _hashService.HashString("OldPass123!"),
TotpSecret = null,
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -191,7 +191,10 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.UoW;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting;
@@ -64,7 +65,11 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
if (descriptor is not null)
services.Remove(descriptor);
// add SQLite DbContext configuration
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite(_connection));
services.AddDbContext<LuminaDbContext>((serviceProvider, options) =>
{
options.UseSqlite(_connection);
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
});
// configure JWT authentication for testing
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
@@ -113,7 +113,10 @@ public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposa
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserRoles = [],
UserPermissions = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -79,7 +79,7 @@ public class AuthLoginTests : IClassFixture<LuminaApiFactory>, IDisposable
// Assert
JwtSecurityTokenHandler handler = new();
JwtSecurityToken token = handler.ReadJwtToken(result!.Token);
string expValue = token.Claims.First(c => c.Type == "exp").Value; // get token claims
DateTimeOffset tokenExpiration = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expValue));
DateTimeOffset expectedExpiration = beforeRequest.AddMinutes(15);
@@ -142,7 +142,7 @@ public class AuthLoginTests : IClassFixture<LuminaApiFactory>, IDisposable
// Assert
// check for timing consistency to prevent timing attacks
double stdDev = CalculateStandardDeviation(timings);
stdDev.Should().BeLessThan(200);
stdDev.Should().BeLessThan(200);
}
[Fact]
@@ -267,7 +267,10 @@ public class AuthLoginTests : IClassFixture<LuminaApiFactory>, IDisposable
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -287,47 +290,10 @@ public class AuthLoginTests : IClassFixture<LuminaApiFactory>, IDisposable
Password = _hashService.HashString("TestPass123!"),
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
private async Task<UserEntity> CreateTestUserWithTempPassword()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
TempPasswordCreated = DateTime.UtcNow,
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
private async Task<UserEntity> CreateTestUserWithExpiredTempPassword()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old)
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -223,7 +223,10 @@ public class AuthRegisterTests : IClassFixture<LuminaApiFactory>, IDisposable
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow
};
dbContext.Users.Add(user);
@@ -44,13 +44,16 @@ public class UserEntityFixture
Id = userId,
Username = default!,
Password = default!,
Created = default,
CreatedOnUtc = default,
TotpSecret = default,
Libraries = libraries
Libraries = libraries,
UserPermissions = [],
UserRoles = [],
CreatedBy = userId
})
.RuleFor(x => x.Username, f => f.Internet.UserName())
.RuleFor(x => x.Password, f => Uri.EscapeDataString(f.Internet.Password()))
.RuleFor(x => x.Created, f => f.Date.Past())
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null)
.Generate();
}
@@ -42,8 +42,8 @@ public class UserEntityMappingTests
result.Should().NotBeNull();
result.Id.Should().Be(entity.Id);
result.Username.Should().Be(entity.Username);
result.Created.Should().Be(entity.Created);
result.Updated.Should().Be(entity.Updated);
result.Created.Should().Be(entity.CreatedOnUtc);
result.Updated.Should().Be(entity.UpdatedOnUtc);
}
[Theory]
@@ -70,14 +70,14 @@ public class UserEntityMappingTests
{
// Arrange
UserEntity entity = UserEntityFixture.CreateUserEntity();
entity.Updated = DateTime.UtcNow.AddDays(-1);
entity.UpdatedOnUtc = DateTime.UtcNow.AddDays(-1);
// Act
UserResponse result = entity.ToResponse();
// Assert
result.Should().NotBeNull();
result.Updated.Should().Be(entity.Updated);
result.Updated.Should().Be(entity.UpdatedOnUtc);
}
[Fact]
@@ -93,7 +93,7 @@ public class UserEntityMappingTests
result.Should().NotBeNull();
result.Id.Should().Be(entity.Id);
result.Username.Should().Be(entity.Username);
result.Created.Should().Be(entity.Created);
result.Updated.Should().Be(entity.Updated);
result.Created.Should().Be(entity.CreatedOnUtc);
result.Updated.Should().Be(entity.UpdatedOnUtc);
}
}
@@ -36,11 +36,12 @@ public class UserMappingTests
Username = "oldusername",
Password = "hashedpassword",
TotpSecret = "totpsecret",
VerificationToken = "verificationtoken",
VerificationTokenCreated = DateTime.UtcNow,
Libraries = [],
Created = DateTime.UtcNow,
Updated = null
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = null
};
// Act
@@ -55,11 +56,13 @@ public class UserMappingTests
result.Id.Should().Be(repositoryEntity.Id);
result.Password.Should().Be(repositoryEntity.Password);
result.TotpSecret.Should().Be(repositoryEntity.TotpSecret);
result.VerificationToken.Should().Be(repositoryEntity.VerificationToken);
result.VerificationTokenCreated.Should().Be(repositoryEntity.VerificationTokenCreated);
result.Libraries.Should().BeSameAs(repositoryEntity.Libraries);
result.Created.Should().Be(repositoryEntity.Created);
result.Updated.Should().Be(repositoryEntity.Updated);
result.UserPermissions.Should().BeSameAs(repositoryEntity.UserPermissions);
result.UserRoles.Should().BeSameAs(repositoryEntity.UserRoles);
result.CreatedOnUtc.Should().Be(repositoryEntity.CreatedOnUtc);
result.CreatedBy.Should().Be(repositoryEntity.CreatedBy);
result.UpdatedOnUtc.Should().Be(repositoryEntity.UpdatedOnUtc);
result.UpdatedBy.Should().Be(repositoryEntity.UpdatedBy);
}
[Theory]
@@ -81,8 +84,11 @@ public class UserMappingTests
Username = "oldusername",
Password = "hashedpassword",
Libraries = [],
Created = DateTime.UtcNow,
Updated = null
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = null
};
// Act
@@ -132,8 +138,11 @@ public class UserMappingTests
Username = "oldusername",
Password = "hashedpassword",
Libraries = libraries,
Created = DateTime.UtcNow,
Updated = null
UserPermissions = [],
UserRoles = [],
CreatedBy = Guid.NewGuid(),
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = null
};
// Act
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures;
@@ -33,6 +34,7 @@ public class SetupApplicationCommandHandlerTests
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
private readonly IQRCodeGenerator _mockQRCodeGenerator;
private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly SetupApplicationCommandHandler _sut;
private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture;
@@ -47,16 +49,19 @@ public class SetupApplicationCommandHandlerTests
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_setupApplicationCommandFixture = new SetupApplicationCommandFixture();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
_sut = new SetupApplicationCommandHandler(
_mockUnitOfWork,
_mockHashService,
_mockCryptographyService,
_mockTotpTokenGenerator,
_mockQRCodeGenerator);
_mockQRCodeGenerator,
_mockDateTimeProvider);
}
[Fact]
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
@@ -32,6 +33,7 @@ public class RegisterUserCommandHandlerTests
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
private readonly IQRCodeGenerator _mockQRCodeGenerator;
private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly RegisterUserCommandHandler _sut;
/// <summary>
@@ -45,15 +47,18 @@ public class RegisterUserCommandHandlerTests
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
_sut = new RegisterUserCommandHandler(
_mockUnitOfWork,
_mockHashService,
_mockCryptographyService,
_mockTotpTokenGenerator,
_mockQRCodeGenerator);
_mockQRCodeGenerator,
_mockDateTimeProvider);
}
[Fact]
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Contracts.Responses.Authentication;
@@ -31,6 +32,7 @@ public class LoginUserQueryHandlerTests
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
private readonly ICryptographyService _mockCryptographyService;
private readonly IUserRepository _mockUserRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly LoginUserQueryHandler _sut;
/// <summary>
@@ -44,15 +46,18 @@ public class LoginUserQueryHandlerTests
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
_sut = new LoginUserQueryHandler(
_mockUnitOfWork,
_mockHashService,
_mockJwtTokenGenerator,
_mockTotpTokenGenerator,
_mockCryptographyService);
_mockCryptographyService,
_mockDateTimeProvider);
}
[Fact]
@@ -2,10 +2,13 @@
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.Repositories.Common.Factory;
using Lumina.DataAccess.Core.UoW;
using Lumina.DataAccess.UnitTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
@@ -46,6 +49,8 @@ public class DataAccessLayerServicesTests
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
// Assert
ServiceDescriptor? descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
@@ -65,6 +70,10 @@ public class DataAccessLayerServicesTests
// Act
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using System;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Setup;
/// <summary>
/// Fake service for retrieving the current user's information during tests.
/// </summary>
public class TestCurrentUserService : ICurrentUserService
{
private Guid userId;
public Guid? UserId => userId;
/// <summary>
/// Sets the test value of the user id.
/// </summary>
/// <param name="userId">The user id to use during tests.</param>
public void SetUserId(Guid userId)
{
this.userId = userId;
}
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Time;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.UnitTests.Common.Setup;
/// <summary>
/// Service for time related concerns
/// </summary>
[ExcludeFromCodeCoverage]
public class TestDateTimeProvider : IDateTimeProvider
{
/// <summary>
/// The current UTC time.
/// </summary>
public DateTime UtcNow => DateTime.UtcNow;
}
@@ -1,8 +1,11 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.Infrastructure.Authentication;
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 Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -22,6 +25,9 @@ public class RepositoryFactoryTests
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
RepositoryFactory repositoryFactory = new(serviceProvider);
@@ -48,4 +54,4 @@ public class RepositoryFactoryTests
}
}
public interface IUnregisteredRepository { }
public interface IUnregisteredRepository { }
@@ -44,12 +44,12 @@ public class UserEntityFixture
.RuleFor(x => x.Password, f => f.Internet.Password(12))
.RuleFor(x => x.TempPassword, f => f.Random.Bool() ? f.Internet.Password(8) : null)
.RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") : null)
.RuleFor(x => x.VerificationToken, f => f.Random.Bool() ? f.Random.Guid().ToString() : null)
.RuleFor(x => x.VerificationTokenCreated, (f, u) => u.VerificationToken != null ? f.Date.Past() : null)
.RuleFor(x => x.TempPasswordCreated, (f, u) => u.TempPassword != null ? f.Date.Past() : null)
.RuleFor(x => x.Libraries, _ => CreateLibraries(_faker.Random.Number(1, 3), userId))
.RuleFor(x => x.Created, f => f.Date.Past())
.RuleFor(x => x.Updated, f => f.Random.Bool() ? f.Date.Recent() : null)
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.CreatedBy, _ => userId)
.RuleFor(x => x.UpdatedOnUtc, f => f.Random.Bool() ? f.Date.Recent() : null)
.RuleFor(x => x.UpdatedBy, _ => userId)
.Generate();
}
@@ -155,8 +155,11 @@ public class UserRepositoryTests
TempPassword = "TempPass456",
TotpSecret = "NewSecret",
Libraries = [],
Created = existingUser.Created,
Updated = DateTime.UtcNow
UserRoles = [],
UserPermissions = [],
CreatedBy = existingUser.Id,
CreatedOnUtc = existingUser.CreatedOnUtc,
UpdatedOnUtc = DateTime.UtcNow
};
// Act
@@ -1,12 +1,15 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.DataAccess.Core.Repositories.Common.Factory;
using Lumina.DataAccess.Core.UoW;
using Lumina.DataAccess.UnitTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
@@ -47,6 +50,8 @@ public class UnitOfWorkTests
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
@@ -63,6 +68,8 @@ public class UnitOfWorkTests
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
int initialCount = unitOfWork.Repositories.Count;
@@ -96,6 +103,8 @@ public class UnitOfWorkTests
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
unitOfWork.ResetRepositories();
@@ -113,6 +122,8 @@ public class UnitOfWorkTests
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
@@ -135,4 +146,4 @@ public class UnitOfWorkTests
// Assert
await dbContext.Received(1).SaveChangesAsync(cancellationToken);
}
}
}