[CHANGE] Removed generics and using base classes

This commit is contained in:
max 2025-01-08 15:55:00 +01:00
parent 12efc92ac4
commit 90cd0a2828
14 changed files with 77 additions and 105 deletions

View File

@ -1,6 +1,5 @@
using DotBased.AspNet.Authority.Crypto;
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Models.Options;
using DotBased.AspNet.Authority.Validators;
using Microsoft.Extensions.DependencyInjection;
@ -11,10 +10,6 @@ namespace DotBased.AspNet.Authority;
public static class AuthorityProviderExtensions
{
public static AuthorityBuilder AddAuthority(this IServiceCollection services, Action<AuthorityOptions>? optionsAction = null)
=> services.AddAuthority<AuthorityUser, AuthorityGroup, AuthorityRole>(optionsAction);
public static AuthorityBuilder AddAuthority<TUser, TGroup, TRole>(this IServiceCollection services, Action<AuthorityOptions>? optionsAction = null)
where TUser : class where TGroup : class where TRole : class
{
if (optionsAction != null)
{
@ -24,16 +19,16 @@ public static class AuthorityProviderExtensions
services.TryAddScoped<ICryptographer, Cryptographer>();
services.TryAddScoped<IPasswordHasher, PasswordHasher>();
services.TryAddScoped<IPasswordValidator<TUser>, PasswordOptionsValidator<TUser>>();
services.TryAddScoped<IPasswordValidator<TUser>, PasswordEqualsValidator<TUser>>();
services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
services.TryAddScoped<IPasswordValidator, PasswordOptionsValidator>();
services.TryAddScoped<IPasswordValidator, PasswordEqualsValidator>();
services.TryAddScoped<IUserValidator, UserValidator>();
/*services.TryAddScoped<IEmailVerifier, EmailVerifier>();
services.TryAddScoped<IPhoneNumberVerifier, PhoneNumberVerifier>();
services.TryAddScoped<IUserVerifier, UserVerifier>();*/
services.TryAddScoped<AuthorityManager>();
services.TryAddScoped<AuthorityUserManager<TUser>>();
services.TryAddScoped<AuthorityGroupManager<TGroup>>();
services.TryAddScoped<AuthorityRoleManager<TRole>>();
services.TryAddScoped<AuthorityUserManager>();
services.TryAddScoped<AuthorityGroupManager>();
services.TryAddScoped<AuthorityRoleManager>();
return new AuthorityBuilder(services);
}

View File

@ -1,6 +1,6 @@
namespace DotBased.AspNet.Authority.Managers;
public class AuthorityGroupManager<TGroup>
public class AuthorityGroupManager
{
}

View File

@ -1,6 +1,6 @@
namespace DotBased.AspNet.Authority.Managers;
public class AuthorityRoleManager<TRole>
public class AuthorityRoleManager
{
}

View File

@ -8,16 +8,16 @@ using DotBased.Logging;
namespace DotBased.AspNet.Authority.Managers;
public class AuthorityUserManager<TUser> where TUser : class
public class AuthorityUserManager
{
public AuthorityUserManager(
AuthorityManager manager,
IUserRepository<TUser> userRepository,
IUserRepository userRepository,
IPasswordHasher passwordHasher,
IEnumerable<IPasswordValidator<TUser>>? passwordValidators,
IEnumerable<IUserValidator<TUser>>? userValidators)
IEnumerable<IPasswordValidator>? passwordValidators,
IEnumerable<IUserValidator>? userValidators)
{
_logger = LogService.RegisterLogger<AuthorityUserManager<TUser>>();
_logger = LogService.RegisterLogger<AuthorityUserManager>();
AuthorityManager = manager;
UserRepository = userRepository;
PasswordHasher = passwordHasher;
@ -29,14 +29,14 @@ public class AuthorityUserManager<TUser> where TUser : class
private readonly ILogger _logger;
public AuthorityManager AuthorityManager { get; }
public IUserRepository<TUser> UserRepository { get; }
public IUserRepository UserRepository { get; }
public IPasswordHasher PasswordHasher { get; }
public IEnumerable<IPasswordValidator<TUser>> PasswordValidators { get; } = [];
public IEnumerable<IUserValidator<TUser>> UserValidators { get; } = [];
public IEnumerable<IPasswordValidator> PasswordValidators { get; } = [];
public IEnumerable<IUserValidator> UserValidators { get; } = [];
public async Task<ValidationResult> ValidatePasswordAsync(TUser user, string password)
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUser user, string password)
{
List<ValidationError> errors = [];
foreach (var validator in PasswordValidators)
@ -50,7 +50,7 @@ public class AuthorityUserManager<TUser> where TUser : class
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
}
public async Task<ValidationResult> ValidateUserAsync(TUser user)
public async Task<ValidationResult> ValidateUserAsync(AuthorityUser user)
{
List<ValidationError> errors = [];
foreach (var userValidator in UserValidators)
@ -64,41 +64,31 @@ public class AuthorityUserManager<TUser> where TUser : class
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
}
public async Task<ListResult<TUser>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0)
public async Task<ListResult<AuthorityUser>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0)
{
var searchResult = await UserRepository.GetUsersAsync(query, maxResults, offset);
return searchResult.Item1 == null ? ListResult<TUser>.Failed("No results!") : ListResult<TUser>.Ok(searchResult.Item1, searchResult.Item2);
var searchResult = await UserRepository.GetAuthorityUsersAsync(query, maxResults, offset);
return searchResult.Item1 == null ? ListResult<AuthorityUser>.Failed("No results!") : ListResult<AuthorityUser>.Ok(searchResult.Item1, searchResult.Item2);
}
public async Task<AuthorityResult<TUser>> UpdatePasswordAsync(TUser user, string password)
public async Task<AuthorityResult<AuthorityUser>> UpdatePasswordAsync(AuthorityUser user, string password)
{
if (user is not AuthorityUserBase userBase)
{
return AuthorityResult<TUser>.Error($"Given user is not of base type {nameof(AuthorityUserBase)}!");
}
var passwordValidation = await ValidatePasswordAsync(user, password);
if (!passwordValidation.Success)
{
List<ValidationError> errors = [];
errors.AddRange(passwordValidation.Errors);
return AuthorityResult<TUser>.Failed(errors, ResultFailReason.Validation);
return AuthorityResult<AuthorityUser>.Failed(errors, ResultFailReason.Validation);
}
userBase.PasswordHash = await PasswordHasher.HashPasswordAsync(password);
userBase.SecurityVersion = AuthorityManager.GenerateVersion();
user.PasswordHash = await PasswordHasher.HashPasswordAsync(password);
user.SecurityVersion = AuthorityManager.GenerateVersion();
var updateResult = await UserRepository.UpdateUserAsync(user);
return updateResult == null ? AuthorityResult<TUser>.Error("Failed to save updates!") : AuthorityResult<TUser>.Ok(updateResult);
return updateResult == null ? AuthorityResult<AuthorityUser>.Error("Failed to save updates!") : AuthorityResult<AuthorityUser>.Ok(updateResult);
}
public async Task<AuthorityResult<TUser>> CreateUserAsync(TUser userModel, string password)
public async Task<AuthorityResult<AuthorityUser>> CreateUserAsync(AuthorityUser userModel, string password)
{
if (userModel is not AuthorityUserBase userBase)
{
return AuthorityResult<TUser>.Error($"Given user is not of base type {nameof(AuthorityUserBase)}!");
}
var userValidation = await ValidateUserAsync(userModel);
var passwordValidation = await ValidatePasswordAsync(userModel, password);
if (!userValidation.Success || !passwordValidation.Success)
@ -106,28 +96,28 @@ public class AuthorityUserManager<TUser> where TUser : class
List<ValidationError> errors = [];
errors.AddRange(userValidation.Errors);
errors.AddRange(passwordValidation.Errors);
return AuthorityResult<TUser>.Failed(errors, ResultFailReason.Validation);
return AuthorityResult<AuthorityUser>.Failed(errors, ResultFailReason.Validation);
}
userBase.Version = AuthorityManager.GenerateVersion();
userBase.SecurityVersion = AuthorityManager.GenerateVersion();
userModel.Version = AuthorityManager.GenerateVersion();
userModel.SecurityVersion = AuthorityManager.GenerateVersion();
var hashedPassword = await PasswordHasher.HashPasswordAsync(password);
userBase.PasswordHash = hashedPassword;
userModel.PasswordHash = hashedPassword;
var userCreationResult = await UserRepository.CreateUserAsync(userModel);
return userCreationResult != null
? AuthorityResult<TUser>.Ok(userCreationResult)
: AuthorityResult<TUser>.Error("Failed to create user in repository!");
? AuthorityResult<AuthorityUser>.Ok(userCreationResult)
: AuthorityResult<AuthorityUser>.Error("Failed to create user in repository!");
}
public async Task<Result<TUser>> UpdateUserAsync(TUser model)
public async Task<Result<AuthorityUser>> UpdateUserAsync(AuthorityUser model)
{
var updateResult = await UserRepository.UpdateUserAsync(model);
return updateResult != null ? Result<TUser>.Ok(updateResult) : Result<TUser>.Failed("Failed to update user in repository!");
return updateResult != null ? Result<AuthorityUser>.Ok(updateResult) : Result<AuthorityUser>.Failed("Failed to update user in repository!");
}
public async Task<bool> DeleteUserAsync(TUser model)
public async Task<bool> DeleteUserAsync(AuthorityUser model)
{
var deleteResult = await UserRepository.DeleteUserAsync(model);
return deleteResult;

View File

@ -2,7 +2,7 @@ using DotBased.AspNet.Authority.Attributes;
namespace DotBased.AspNet.Authority.Models.Authority;
public class AuthorityUser : AuthorityUser<Guid>
public class AuthorityUser
{
public AuthorityUser(string userName) : this()
{
@ -14,15 +14,9 @@ public class AuthorityUser : AuthorityUser<Guid>
Id = Guid.NewGuid();
CreatedDate = DateTime.Now;
}
}
public abstract class AuthorityUser<TKey> : AuthorityUserBase where TKey : IEquatable<TKey>
{
public TKey Id { get; set; }
}
public abstract class AuthorityUserBase
{
public Guid Id { get; set; }
public bool Enabled { get; set; }
public bool Confirmed { get; set; }

View File

@ -1,6 +1,6 @@
namespace DotBased.AspNet.Authority.Repositories;
public interface IAttributeRepository<TAttribute, TId> where TAttribute : class where TId : IEquatable<TId>
public interface IAttributeRepository
{
}

View File

@ -1,6 +1,6 @@
namespace DotBased.AspNet.Authority.Repositories;
public interface IGroupRepository<TGroup> where TGroup : class
public interface IGroupRepository
{
}

View File

@ -1,6 +1,6 @@
namespace DotBased.AspNet.Authority.Repositories;
public interface IRoleRepository<TRole, TId> where TRole : class where TId : IEquatable<TId>
public interface IRoleRepository
{
}

View File

@ -1,16 +1,18 @@
using DotBased.AspNet.Authority.Models.Authority;
namespace DotBased.AspNet.Authority.Repositories;
public interface IUserRepository<TUser> where TUser : class
public interface IUserRepository
{
public Task<TUser?> GetUserByIdAsync(string id, CancellationToken? cancellationToken = null);
public Task<string> GetUserIdAsync(TUser user, CancellationToken? cancellationToken = null);
public Task<Tuple<List<TUser>?, int>> GetUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken? cancellationToken = null);
public Task<TUser?> GetUserByEmailAsync(string email, CancellationToken? cancellationToken = null);
public Task SetVersionAsync(TUser user, long version, CancellationToken? cancellationToken = null);
public Task<long> GetVersionAsync(TUser user, CancellationToken? cancellationToken = null);
public Task SetSecurityVersionAsync(TUser user, long version, CancellationToken? cancellationToken = null);
public Task<long> GetSecurityVersionAsync(TUser user, CancellationToken? cancellationToken = null);
public Task<TUser?> CreateUserAsync(TUser user, CancellationToken? cancellationToken = null);
public Task<TUser?> UpdateUserAsync(TUser user, CancellationToken? cancellationToken = null);
public Task<bool> DeleteUserAsync(TUser user, CancellationToken? cancellationToken = null);
public Task<AuthorityUser?> GetAuthorityUserByIdAsync(string id, CancellationToken? cancellationToken = null);
public Task<string> GetAuthorityUserIdAsync(AuthorityUser user, CancellationToken? cancellationToken = null);
public Task<Tuple<List<AuthorityUser>?, int>> GetAuthorityUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken? cancellationToken = null);
public Task<AuthorityUser?> GetAuthorityUserByEmailAsync(string email, CancellationToken? cancellationToken = null);
public Task SetVersionAsync(AuthorityUser user, long version, CancellationToken? cancellationToken = null);
public Task<long> GetVersionAsync(AuthorityUser user, CancellationToken? cancellationToken = null);
public Task SetSecurityVersionAsync(AuthorityUser user, long version, CancellationToken? cancellationToken = null);
public Task<long> GetSecurityVersionAsync(AuthorityUser user, CancellationToken? cancellationToken = null);
public Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken? cancellationToken = null);
public Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken? cancellationToken = null);
public Task<bool> DeleteUserAsync(AuthorityUser user, CancellationToken? cancellationToken = null);
}

View File

@ -1,9 +1,10 @@
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Models.Validation;
namespace DotBased.AspNet.Authority.Validators;
public interface IPasswordValidator<TUser> where TUser : class
public interface IPasswordValidator
{
public Task<ValidationResult> ValidatePasswordAsync(AuthorityUserManager<TUser> userManager, TUser user, string password);
public Task<ValidationResult> ValidatePasswordAsync(AuthorityUserManager userManager, AuthorityUser user, string password);
}

View File

@ -1,9 +1,10 @@
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Models.Validation;
namespace DotBased.AspNet.Authority.Validators;
public interface IUserValidator<TUser> where TUser : class
public interface IUserValidator
{
public Task<ValidationResult> ValidateUserAsync(AuthorityUserManager<TUser> manager, TUser user);
public Task<ValidationResult> ValidateUserAsync(AuthorityUserManager manager, AuthorityUser user);
}

View File

@ -4,20 +4,15 @@ using DotBased.AspNet.Authority.Models.Validation;
namespace DotBased.AspNet.Authority.Validators;
public class PasswordEqualsValidator<TUser> : IPasswordValidator<TUser> where TUser : class
public class PasswordEqualsValidator : IPasswordValidator
{
private const string ValidatorId = "Authority.Validator.Password.Equals";
private const string ValidationBase = "Authority.Validation.Password";
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUserManager<TUser> userManager, TUser user, string password)
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUserManager userManager, AuthorityUser user, string password)
{
if (user is not AuthorityUserBase authorityUser)
{
throw new ArgumentException($"User is not type of {nameof(AuthorityUserBase)}!", nameof(user));
}
List<ValidationError> errors = [];
var hashedPassword = await userManager.PasswordHasher.HashPasswordAsync(password);
if (authorityUser.PasswordHash != null && authorityUser.PasswordHash.Equals(hashedPassword, StringComparison.Ordinal))
if (user.PasswordHash != null && user.PasswordHash.Equals(hashedPassword, StringComparison.Ordinal))
{
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.InUse", "User uses this password already!"));
}

View File

@ -1,4 +1,5 @@
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Models.Validation;
using DotBased.Extensions;
@ -8,12 +9,12 @@ namespace DotBased.AspNet.Authority.Validators;
/// Validates the password against the options that is configured.
/// </summary>
/// <typeparam name="TUser">The user model used.</typeparam>
public class PasswordOptionsValidator<TUser> : IPasswordValidator<TUser> where TUser : class
public class PasswordOptionsValidator : IPasswordValidator
{
private const string ValidatorId = "Authority.Validator.Password.Options";
private const string ValidationBase = "Authority.Validation.Password";
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUserManager<TUser> userManager, TUser user, string password)
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUserManager userManager, AuthorityUser user, string password)
{
if (userManager == null)
{

View File

@ -5,34 +5,27 @@ using DotBased.AspNet.Authority.Models.Validation;
namespace DotBased.AspNet.Authority.Validators;
public class UserValidator<TUser> : IUserValidator<TUser> where TUser : class
public class UserValidator : IUserValidator
{
private const string ValidatorId = "Authority.Validator.User";
private const string ValidationBase = "Authority.Validation.User";
public async Task<ValidationResult> ValidateUserAsync(AuthorityUserManager<TUser> manager, TUser user)
public async Task<ValidationResult> ValidateUserAsync(AuthorityUserManager manager, AuthorityUser user)
{
List<ValidationError> errors = [];
var userOptions = manager.AuthorityManager.Options.User;
if (user is not AuthorityUserBase userBase)
{
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.NotAuthorityUser",
$"Given user model is not an type of {nameof(AuthorityUserBase)}"));
return ValidationResult.Failed(errors);
}
if (userOptions.RequireUniqueEmail)
{
if (string.IsNullOrWhiteSpace(userBase.EmailAddress))
if (string.IsNullOrWhiteSpace(user.EmailAddress))
{
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.NoEmail",
$"Option {nameof(UserOptions.RequireUniqueEmail)} is set to true but given user does not have an email address!"));
}
else
{
var userEmailResult = await manager.UserRepository.GetUserByEmailAsync(userBase.EmailAddress);
var userEmailResult = await manager.UserRepository.GetAuthorityUserByEmailAsync(user.EmailAddress);
if (userEmailResult != null)
{
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.EmailExists",
@ -41,9 +34,9 @@ public class UserValidator<TUser> : IUserValidator<TUser> where TUser : class
}
}
if (!string.IsNullOrWhiteSpace(userBase.UserName))
if (!string.IsNullOrWhiteSpace(user.UserName))
{
if (userOptions.UserNameBlackList.Count != 0 && userOptions.UserNameBlackList.Contains(userBase.UserName, userOptions.UserNameBlackListComparer))
if (userOptions.UserNameBlackList.Count != 0 && userOptions.UserNameBlackList.Contains(user.UserName, userOptions.UserNameBlackListComparer))
{
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.Blacklisted", "Given username is not allowed (blacklisted)"));
}
@ -53,11 +46,11 @@ public class UserValidator<TUser> : IUserValidator<TUser> where TUser : class
List<char> chars = [];
if (userOptions.UserNameCharacterListType == ListOption.Whitelist)
{
chars.AddRange(userBase.UserName.Where(userNameChar => !userOptions.UserNameCharacters.Contains(userNameChar)));
chars.AddRange(user.UserName.Where(userNameChar => !userOptions.UserNameCharacters.Contains(userNameChar)));
}
if (userOptions.UserNameCharacterListType == ListOption.Blacklist)
{
chars.AddRange(userBase.UserName.Where(userNameChar => userOptions.UserNameCharacters.Contains(userNameChar)));
chars.AddRange(user.UserName.Where(userNameChar => userOptions.UserNameCharacters.Contains(userNameChar)));
}
if (chars.Count <= 0) return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();