DotBased/DotBased.AspNet.Authority/Validators/PasswordEqualsValidator.cs

27 lines
1.2 KiB
C#
Raw Normal View History

using DotBased.AspNet.Authority.Managers;
2024-12-26 20:01:57 +01:00
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Models.Validation;
namespace DotBased.AspNet.Authority.Validators;
public class PasswordEqualsValidator<TUser> : IPasswordValidator<TUser> where TUser : class
{
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)
{
if (user is not AuthorityUserBase authorityUser)
2024-12-26 20:01:57 +01:00
{
throw new ArgumentException($"User is not type of {nameof(AuthorityUserBase)}!", nameof(user));
2024-12-26 20:01:57 +01:00
}
List<ValidationError> errors = [];
var hashedPassword = await userManager.PasswordHasher.HashPasswordAsync(password);
if (authorityUser.PasswordHash != null && authorityUser.PasswordHash.Equals(hashedPassword, StringComparison.Ordinal))
{
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.InUse", "User uses this password already!"));
}
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
}
}