mirror of
https://github.com/hmaxnl/DotBased.git
synced 2025-01-18 10:04:20 +01:00
Compare commits
4 Commits
12efc92ac4
...
3ccd3106c1
Author | SHA1 | Date | |
---|---|---|---|
|
3ccd3106c1 | ||
|
fd733b7238 | ||
|
28fcd74acf | ||
|
90cd0a2828 |
|
@ -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,13 @@ 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>>();
|
||||
return new AuthorityBuilder(services);
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public class AuthorityGroupManager<TGroup>
|
||||
public partial class AuthorityManager
|
||||
{
|
||||
|
||||
}
|
|
@ -2,22 +2,30 @@ 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.AspNet.Authority.Validators;
|
||||
using DotBased.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public class AuthorityManager
|
||||
public partial class AuthorityManager
|
||||
{
|
||||
public AuthorityManager(
|
||||
IOptions<AuthorityOptions> options,
|
||||
IServiceProvider services,
|
||||
ICryptographer cryptographer)
|
||||
ICryptographer cryptographer,
|
||||
IUserRepository userRepository,
|
||||
IRoleRepository roleRepository,
|
||||
IPasswordHasher passwordHasher)
|
||||
{
|
||||
_logger = LogService.RegisterLogger<AuthorityManager>();
|
||||
Options = options.Value ?? new AuthorityOptions();
|
||||
Options = options.Value;
|
||||
Services = services;
|
||||
Cryptographer = cryptographer;
|
||||
UserRepository = userRepository;
|
||||
RoleRepository = roleRepository;
|
||||
PasswordHasher = passwordHasher;
|
||||
}
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
@ -26,6 +34,14 @@ public class AuthorityManager
|
|||
public AuthorityOptions Options { get; }
|
||||
public ICryptographer Cryptographer { get; }
|
||||
|
||||
public IUserRepository UserRepository { get; }
|
||||
public IRoleRepository RoleRepository { get; }
|
||||
|
||||
public IPasswordHasher PasswordHasher { get; }
|
||||
|
||||
public IEnumerable<IPasswordValidator> PasswordValidators { get; } = [];
|
||||
public IEnumerable<IUserValidator> UserValidators { get; } = [];
|
||||
|
||||
|
||||
public long GenerateVersion() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
|
||||
|
@ -38,12 +54,7 @@ public class AuthorityManager
|
|||
/// <typeparam name="TModel">The class with the properties to protect.</typeparam>
|
||||
public async Task HandlePropertyProtection<TModel>(TModel data, bool protection)
|
||||
{
|
||||
var props = GetProtectedPropertiesValues<TModel>(data);
|
||||
if (Cryptographer == null)
|
||||
{
|
||||
_logger.Warning("No cryptographer specified! Cannot encrypt/decrypt properties.");
|
||||
return;
|
||||
}
|
||||
var props = GetProtectedPropertiesValues(data);
|
||||
if (props.Count == 0)
|
||||
{
|
||||
return;
|
||||
|
|
|
@ -1,6 +1,34 @@
|
|||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public class AuthorityRoleManager<TRole>
|
||||
public partial class AuthorityManager
|
||||
{
|
||||
public async Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
return Result<AuthorityRole>.Failed("Not implemented!");
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteRoleAsync(AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
return Result.Failed("Not implemented!");
|
||||
}
|
||||
|
||||
public async Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
return Result<AuthorityRole>.Failed("Not implemented!");
|
||||
}
|
||||
|
||||
public async Task AddRoleToUserAsync(AuthorityUser user, AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public async Task RemoveRoleFromUserAsync(AuthorityRole role, AuthorityUser user, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
}
|
||||
|
||||
public async Task AddRoleToGroupAsync(AuthorityRole role, AuthorityGroup group, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
}
|
||||
}
|
|
@ -1,42 +1,12 @@
|
|||
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 partial class AuthorityManager
|
||||
{
|
||||
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)
|
||||
public async Task<ValidationResult> ValidatePasswordAsync(AuthorityUser user, string password)
|
||||
{
|
||||
List<ValidationError> errors = [];
|
||||
foreach (var validator in PasswordValidators)
|
||||
|
@ -50,7 +20,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 +34,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, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
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, cancellationToken);
|
||||
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, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
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 = GenerateVersion();
|
||||
|
||||
var updateResult = await UserRepository.UpdateUserAsync(user);
|
||||
return updateResult == null ? AuthorityResult<TUser>.Error("Failed to save updates!") : AuthorityResult<TUser>.Ok(updateResult);
|
||||
var updateResult = await UserRepository.UpdateUserAsync(user, cancellationToken);
|
||||
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, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
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,30 +66,30 @@ 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 = GenerateVersion();
|
||||
userModel.SecurityVersion = GenerateVersion();
|
||||
var hashedPassword = await PasswordHasher.HashPasswordAsync(password);
|
||||
userBase.PasswordHash = hashedPassword;
|
||||
userModel.PasswordHash = hashedPassword;
|
||||
|
||||
var userCreationResult = await UserRepository.CreateUserAsync(userModel);
|
||||
var userCreationResult = await UserRepository.CreateUserAsync(userModel, cancellationToken);
|
||||
|
||||
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, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var updateResult = await UserRepository.UpdateUserAsync(model);
|
||||
return updateResult != null ? Result<TUser>.Ok(updateResult) : Result<TUser>.Failed("Failed to update user in repository!");
|
||||
var updateResult = await UserRepository.UpdateUserAsync(model, cancellationToken);
|
||||
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, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var deleteResult = await UserRepository.DeleteUserAsync(model);
|
||||
var deleteResult = await UserRepository.DeleteUserAsync(model, cancellationToken);
|
||||
return deleteResult;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
public class AuthorityGroup : AuthorityGroup<Guid>
|
||||
public class AuthorityGroup
|
||||
{
|
||||
public AuthorityGroup(string name) : this()
|
||||
{
|
||||
|
@ -12,11 +12,8 @@ public class AuthorityGroup : AuthorityGroup<Guid>
|
|||
Id = Guid.NewGuid();
|
||||
CreatedDate = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class AuthorityGroup<TKey> where TKey : IEquatable<TKey>
|
||||
{
|
||||
public TKey Id { get; set; }
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public string? Name { get; set; }
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
public class AuthorityRole : AuthorityRole<Guid>
|
||||
public abstract class AuthorityRole
|
||||
{
|
||||
public AuthorityRole(string name) : this()
|
||||
{
|
||||
|
@ -12,11 +12,8 @@ public class AuthorityRole : AuthorityRole<Guid>
|
|||
Id = Guid.NewGuid();
|
||||
CreatedDate = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class AuthorityRole<TKey> where TKey : IEquatable<TKey>
|
||||
{
|
||||
public TKey Id { get; set; }
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public string? Name { get; set; }
|
||||
|
||||
|
|
|
@ -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 Guid Id { get; set; }
|
||||
|
||||
public abstract class AuthorityUserBase
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
public bool Confirmed { get; set; }
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IAttributeRepository<TAttribute, TId> where TAttribute : class where TId : IEquatable<TId>
|
||||
public interface IAttributeRepository
|
||||
{
|
||||
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IGroupRepository<TGroup> where TGroup : class
|
||||
public interface IGroupRepository
|
||||
{
|
||||
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IRoleRepository<TRole, TId> where TRole : class where TId : IEquatable<TId>
|
||||
public interface IRoleRepository
|
||||
{
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
|
@ -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(AuthorityManager manager, AuthorityUser user, string password);
|
||||
}
|
|
@ -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(AuthorityManager manager, AuthorityUser user);
|
||||
}
|
|
@ -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(AuthorityManager 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!"));
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.Extensions;
|
||||
|
||||
|
@ -7,19 +8,18 @@ namespace DotBased.AspNet.Authority.Validators;
|
|||
/// <summary>
|
||||
/// 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(AuthorityManager userManager, AuthorityUser user, string password)
|
||||
{
|
||||
if (userManager == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(userManager), "User manager is not provided!");
|
||||
}
|
||||
var passwordOptions = userManager.AuthorityManager.Options.Password;
|
||||
var passwordOptions = userManager.Options.Password;
|
||||
var errors = new List<ValidationError>();
|
||||
|
||||
if (password.IsNullOrEmpty() || password.Length < passwordOptions.RequiredLength)
|
||||
|
|
|
@ -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(AuthorityManager 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);
|
||||
}
|
||||
var userOptions = manager.Options.User;
|
||||
|
||||
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();
|
||||
|
|
Loading…
Reference in New Issue
Block a user