mirror of
https://github.com/hmaxnl/DotBased.git
synced 2025-01-18 10:04:20 +01:00
[CHANGE] Implementing managers. repositories
This commit is contained in:
parent
2d96a25906
commit
efc8259930
|
@ -1,7 +1,7 @@
|
|||
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.Services;
|
||||
using DotBased.AspNet.Authority.Validators;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
namespace DotBased.AspNet.Authority.Services;
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public class AuthorityGroupManager<TGroup>
|
||||
{
|
|
@ -2,24 +2,21 @@ using System.Reflection;
|
|||
using DotBased.AspNet.Authority.Attributes;
|
||||
using DotBased.AspNet.Authority.Crypto;
|
||||
using DotBased.AspNet.Authority.Models.Options;
|
||||
using DotBased.AspNet.Authority.Repositories;
|
||||
using DotBased.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Services;
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public class AuthorityManager
|
||||
{
|
||||
public AuthorityManager(
|
||||
IOptions<AuthorityOptions> options,
|
||||
IServiceProvider services,
|
||||
IAuthorityRepository repository,
|
||||
ICryptographer cryptographer)
|
||||
{
|
||||
_logger = LogService.RegisterLogger<AuthorityManager>();
|
||||
Options = options.Value ?? new AuthorityOptions();
|
||||
Services = services;
|
||||
Repository = repository;
|
||||
Cryptographer = cryptographer;
|
||||
}
|
||||
|
||||
|
@ -27,7 +24,6 @@ public class AuthorityManager
|
|||
|
||||
public IServiceProvider Services { get; }
|
||||
public AuthorityOptions Options { get; }
|
||||
public IAuthorityRepository Repository { get; }
|
||||
public ICryptographer Cryptographer { get; }
|
||||
|
||||
|
||||
|
@ -38,7 +34,7 @@ public class AuthorityManager
|
|||
/// Protect or unprotect the properties with the <see cref="ProtectAttribute"/>
|
||||
/// </summary>
|
||||
/// <param name="data">The data model</param>
|
||||
/// <param name="protection">True for protection false for unprotection.</param>
|
||||
/// <param name="protection">True for protect false for unprotect.</param>
|
||||
/// <typeparam name="TModel">The class with the properties to protect.</typeparam>
|
||||
public async Task HandlePropertyProtection<TModel>(TModel data, bool protection)
|
||||
{
|
||||
|
@ -74,7 +70,7 @@ public class AuthorityManager
|
|||
|
||||
if (cryptString == null)
|
||||
{
|
||||
_logger.Warning("{Protection} failed for property {PropName}", protection ? "Encyption" : "Decyption", property.Name);
|
||||
_logger.Warning("{Protection} failed for property {PropName}", protection ? "Encryption" : "Decryption", property.Name);
|
||||
continue;
|
||||
}
|
||||
property.SetValue(data, cryptString);
|
|
@ -1,4 +1,4 @@
|
|||
namespace DotBased.AspNet.Authority.Services;
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public class AuthorityRoleManager<TRole>
|
||||
{
|
97
DotBased.AspNet.Authority/Managers/AuthorityUserManager.cs
Normal file
97
DotBased.AspNet.Authority/Managers/AuthorityUserManager.cs
Normal file
|
@ -0,0 +1,97 @@
|
|||
using DotBased.AspNet.Authority.Crypto;
|
||||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Repositories;
|
||||
using DotBased.AspNet.Authority.Validators;
|
||||
using DotBased.Logging;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public class AuthorityUserManager<TUser> where TUser : class
|
||||
{
|
||||
public AuthorityUserManager(
|
||||
AuthorityManager manager,
|
||||
IUserRepository<TUser> userRepository,
|
||||
IPasswordHasher passwordHasher,
|
||||
IEnumerable<IPasswordValidator<TUser>>? passwordValidators,
|
||||
IEnumerable<IUserValidator<TUser>>? userValidators)
|
||||
{
|
||||
_logger = LogService.RegisterLogger<AuthorityUserManager<TUser>>();
|
||||
AuthorityManager = manager;
|
||||
UserRepository = userRepository;
|
||||
PasswordHasher = passwordHasher;
|
||||
if (passwordValidators != null)
|
||||
PasswordValidators = passwordValidators;
|
||||
if (userValidators != null)
|
||||
UserValidators = userValidators;
|
||||
}
|
||||
|
||||
private readonly ILogger _logger;
|
||||
public AuthorityManager AuthorityManager { get; }
|
||||
public IUserRepository<TUser> UserRepository { get; }
|
||||
|
||||
public IPasswordHasher PasswordHasher { get; }
|
||||
|
||||
public IEnumerable<IPasswordValidator<TUser>> PasswordValidators { get; } = [];
|
||||
public IEnumerable<IUserValidator<TUser>> UserValidators { get; } = [];
|
||||
|
||||
public async Task<ValidationResult> ValidatePasswordAsync(TUser user, string password)
|
||||
{
|
||||
List<ValidationError> errors = [];
|
||||
foreach (var validator in PasswordValidators)
|
||||
{
|
||||
var validatorResult = await validator.ValidatePasswordAsync(this, user, password);
|
||||
if (!validatorResult.Success)
|
||||
{
|
||||
errors.AddRange(validatorResult.Errors);
|
||||
}
|
||||
}
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
|
||||
public async Task<ValidationResult> ValidateUserAsync(TUser user)
|
||||
{
|
||||
List<ValidationError> errors = [];
|
||||
foreach (var userValidator in UserValidators)
|
||||
{
|
||||
var validationResult = await userValidator.ValidateUserAsync(this, user);
|
||||
if (!validationResult.Success)
|
||||
{
|
||||
errors.AddRange(validationResult.Errors);
|
||||
}
|
||||
}
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
|
||||
public async Task<AuthorityResult<TUser>> CreateUserAsync(TUser 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)
|
||||
{
|
||||
List<ValidationError> errors = [];
|
||||
errors.AddRange(userValidation.Errors);
|
||||
errors.AddRange(passwordValidation.Errors);
|
||||
return AuthorityResult<TUser>.Failed(errors, ResultFailReason.Validation);
|
||||
}
|
||||
|
||||
var version = AuthorityManager.GenerateVersion();
|
||||
userBase.Version = version;
|
||||
var securityVersion = AuthorityManager.GenerateVersion();
|
||||
userBase.SecurityVersion = securityVersion;
|
||||
var hashedPassword = await PasswordHasher.HashPasswordAsync(password);
|
||||
userBase.PasswordHash = hashedPassword;
|
||||
|
||||
var userCreationResult = await UserRepository.CreateUserAsync(userModel);
|
||||
|
||||
return userCreationResult != null
|
||||
? AuthorityResult<TUser>.Ok(userCreationResult)
|
||||
: AuthorityResult<TUser>.Error("Failed to create user in repository!");
|
||||
}
|
||||
}
|
38
DotBased.AspNet.Authority/Models/AuthorityResult.cs
Normal file
38
DotBased.AspNet.Authority/Models/AuthorityResult.cs
Normal file
|
@ -0,0 +1,38 @@
|
|||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Models;
|
||||
|
||||
public class AuthorityResult<TResultValue>
|
||||
{
|
||||
public AuthorityResult(bool success, string errorMessage = "", TResultValue? value = default, ResultFailReason reason = ResultFailReason.None, List<ValidationError>? errors = null)
|
||||
{
|
||||
Success = success;
|
||||
ErrorMessage = errorMessage;
|
||||
Value = value;
|
||||
Reason = reason;
|
||||
ValidationErrors = errors;
|
||||
}
|
||||
|
||||
public bool Success { get; }
|
||||
public string ErrorMessage { get; }
|
||||
public TResultValue? Value { get; }
|
||||
public ResultFailReason Reason { get; }
|
||||
public List<ValidationError>? ValidationErrors { get; }
|
||||
|
||||
|
||||
public static AuthorityResult<TResultValue> Ok(TResultValue? value) => new AuthorityResult<TResultValue>(true, value:value);
|
||||
|
||||
public static AuthorityResult<TResultValue> Error(string errorMessage, ResultFailReason reason = ResultFailReason.Error) =>
|
||||
new AuthorityResult<TResultValue>(false, errorMessage, reason:reason);
|
||||
|
||||
public static AuthorityResult<TResultValue> Failed(List<ValidationError> errors, ResultFailReason reason = ResultFailReason.None)
|
||||
=> new AuthorityResult<TResultValue>(false, errors:errors, reason:reason);
|
||||
}
|
||||
|
||||
public enum ResultFailReason
|
||||
{
|
||||
None,
|
||||
Unknown,
|
||||
Validation,
|
||||
Error
|
||||
}
|
7
DotBased.AspNet.Authority/Models/Options/ListOption.cs
Normal file
7
DotBased.AspNet.Authority/Models/Options/ListOption.cs
Normal file
|
@ -0,0 +1,7 @@
|
|||
namespace DotBased.AspNet.Authority.Models.Options;
|
||||
|
||||
public enum ListOption
|
||||
{
|
||||
Blacklist,
|
||||
Whitelist
|
||||
}
|
|
@ -4,7 +4,8 @@ public class UserOptions
|
|||
{
|
||||
public bool EnableRegister { get; set; }
|
||||
public bool RequireUniqueEmail { get; set; }
|
||||
public string AllowedCharacters { get; set; } = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";
|
||||
public string UserNameCharacters { get; set; } = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";
|
||||
public ListOption UserNameCharacterListType { get; set; } = ListOption.Whitelist;
|
||||
|
||||
public List<string> UserNameBlackList { get; set; } = ["admin", "administrator", "dev", "developer"];
|
||||
public StringComparer UserNameBlackListComparer { get; set; } = StringComparer.OrdinalIgnoreCase;
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IAuthorityRepository
|
||||
{
|
||||
public Task<long> GetVersion();
|
||||
public Task SetVersion(long version);
|
||||
}
|
|
@ -4,6 +4,12 @@ public interface IUserRepository<TUser> where TUser : class
|
|||
{
|
||||
public Task<TUser?> GetUserByIdAsync(string id);
|
||||
public Task<string> GetUserIdAsync(TUser user);
|
||||
public Task SetVersion(TUser user, long version);
|
||||
public Task SetSecurityVersion(TUser user, long version);
|
||||
public Task<TUser?> GetUserByEmailAsync(string email);
|
||||
public Task SetVersionAsync(TUser user, long version);
|
||||
public Task<long> GetVersionAsync(TUser user);
|
||||
public Task SetSecurityVersionAsync(TUser user, long version);
|
||||
public Task<long> GetSecurityVersionAsync(TUser user);
|
||||
public Task<TUser?> CreateUserAsync(TUser user);
|
||||
public Task<TUser?> UpdateUserAsync(TUser user);
|
||||
public Task<bool> DeleteUserAsync(TUser user);
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public class RepositoryManager<TUser, TGroup> where TUser : class where TGroup : class
|
||||
{
|
||||
public RepositoryManager(IUserRepository<TUser> userRepository, IGroupRepository<TGroup> groupRepository)
|
||||
{
|
||||
UserRepository = userRepository;
|
||||
GroupRepository = groupRepository;
|
||||
}
|
||||
|
||||
public IUserRepository<TUser> UserRepository { get; set; }
|
||||
public IGroupRepository<TGroup> GroupRepository { get; set; }
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
using DotBased.AspNet.Authority.Crypto;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Repositories;
|
||||
using DotBased.AspNet.Authority.Validators;
|
||||
using DotBased.Logging;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Services;
|
||||
|
||||
public class AuthorityUserManager<TUser> where TUser : class
|
||||
{
|
||||
public AuthorityUserManager(
|
||||
AuthorityManager manager,
|
||||
IUserRepository<TUser> userRepository,
|
||||
IPasswordHasher passwordHasher,
|
||||
IEnumerable<IPasswordValidator<TUser>>? passwordValidators,
|
||||
IEnumerable<IUserValidator<TUser>>? userValidators)
|
||||
{
|
||||
_logger = LogService.RegisterLogger<AuthorityUserManager<TUser>>();
|
||||
AuthorityManager = manager;
|
||||
UserRepository = userRepository;
|
||||
PasswordHasher = passwordHasher;
|
||||
if (passwordValidators != null)
|
||||
PasswordValidators = passwordValidators;
|
||||
if (userValidators != null)
|
||||
UserValidators = userValidators;
|
||||
}
|
||||
|
||||
private readonly ILogger _logger;
|
||||
public AuthorityManager AuthorityManager { get; }
|
||||
public IUserRepository<TUser> UserRepository { get; }
|
||||
|
||||
public IPasswordHasher PasswordHasher { get; }
|
||||
|
||||
public IEnumerable<IPasswordValidator<TUser>> PasswordValidators { get; } = [];
|
||||
public IEnumerable<IUserValidator<TUser>> UserValidators { get; } = [];
|
||||
|
||||
public async Task<ValidationResult> ValidatePasswordAsync(TUser user, string password)
|
||||
{
|
||||
List<ValidationError> errors = [];
|
||||
foreach (var validator in PasswordValidators)
|
||||
{
|
||||
var validatorResult = await validator.ValidatePasswordAsync(this, user, password);
|
||||
if (!validatorResult.Success)
|
||||
{
|
||||
errors.AddRange(validatorResult.Errors);
|
||||
}
|
||||
}
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Services;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
public interface IUserValidator<TUser>
|
||||
public interface IUserValidator<TUser> where TUser : class
|
||||
{
|
||||
|
||||
public Task<ValidationResult> ValidateUserAsync(AuthorityUserManager<TUser> manager, TUser user);
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Services;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
|
@ -10,9 +10,9 @@ public class PasswordEqualsValidator<TUser> : IPasswordValidator<TUser> where TU
|
|||
private const string ValidationBase = "Authority.Validation.Password";
|
||||
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUserManager<TUser> userManager, TUser user, string password)
|
||||
{
|
||||
if (user == null || user is not AuthorityUserBase authorityUser)
|
||||
if (user is not AuthorityUserBase authorityUser)
|
||||
{
|
||||
throw new ArgumentException("Invalid user given!", nameof(user));
|
||||
throw new ArgumentException($"User is not type of {nameof(AuthorityUserBase)}!", nameof(user));
|
||||
}
|
||||
|
||||
List<ValidationError> errors = [];
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Services;
|
||||
using DotBased.Extensions;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
|
|
@ -1,6 +1,88 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Options;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
public class UserValidator<TUser> : IUserValidator<TUser>
|
||||
public class UserValidator<TUser> : IUserValidator<TUser> where TUser : class
|
||||
{
|
||||
private const string ValidatorId = "Authority.Validator.User";
|
||||
private const string ValidationBase = "Authority.Validation.User";
|
||||
|
||||
public async Task<ValidationResult> ValidateUserAsync(AuthorityUserManager<TUser> manager, TUser 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))
|
||||
{
|
||||
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);
|
||||
if (userEmailResult != null)
|
||||
{
|
||||
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.EmailExists",
|
||||
"Given email has already registered an account!"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(userBase.UserName))
|
||||
{
|
||||
if (userOptions.UserNameBlackList.Count != 0 && userOptions.UserNameBlackList.Contains(userBase.UserName, userOptions.UserNameBlackListComparer))
|
||||
{
|
||||
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.Blacklisted", "Given username is not allowed (blacklisted)"));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(userOptions.UserNameCharacters))
|
||||
{
|
||||
List<char> chars = [];
|
||||
if (userOptions.UserNameCharacterListType == ListOption.Whitelist)
|
||||
{
|
||||
chars.AddRange(userBase.UserName.Where(userNameChar => !userOptions.UserNameCharacters.Contains(userNameChar)));
|
||||
}
|
||||
if (userOptions.UserNameCharacterListType == ListOption.Blacklist)
|
||||
{
|
||||
chars.AddRange(userBase.UserName.Where(userNameChar => userOptions.UserNameCharacters.Contains(userNameChar)));
|
||||
}
|
||||
|
||||
if (chars.Count <= 0) return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
var errorCode = "";
|
||||
var description = "";
|
||||
switch (userOptions.UserNameCharacterListType)
|
||||
{
|
||||
case ListOption.Whitelist:
|
||||
errorCode = "CharactersNotOnWhitelist";
|
||||
description = $"Found characters in username that were not on the whitelist! Chars: [{string.Join(',', chars)}]";
|
||||
break;
|
||||
case ListOption.Blacklist:
|
||||
errorCode = "CharactersOnBlacklist";
|
||||
description = $"Found characters in username that are on the blacklist! Chars: [{string.Join(',', chars)}]";
|
||||
break;
|
||||
}
|
||||
|
||||
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.UserName.{errorCode}", description));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.InvalidUserName", "No username given!"));
|
||||
}
|
||||
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user