using System.Net; using Application.Services.Database.PostgreSQL; using Application.Services.HashingAlgorithms; using FluentValidation; namespace Application.Endpoints.Authorization.Patient; public class PatientResetPasswordValidation : AbstractValidator { private readonly IPatientRepository _patientRepository; private readonly IHashingAlgorithms _hashingAlgorithms; public PatientResetPasswordValidation(IPatientRepository patientRepository, IHashingAlgorithms hashingAlgorithms) { _patientRepository = patientRepository; _hashingAlgorithms = hashingAlgorithms; RuleFor(x => x.Email) .NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .MustAsync(BeExistingPatient).WithMessage("Patient with this email does not exist.") .WithErrorCode(HttpStatusCodes.NotFound.ToString()); RuleFor(x => x.Password) .NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .WithErrorCode(HttpStatusCode.BadRequest.ToString()); RuleFor(x => x) .MustAsync(BeDifferentFromOldPassword).WithMessage("Password can't be as the previous.") .WithErrorCode(HttpStatusCode.BadRequest.ToString()).WithErrorCode(HttpStatusCodes.BadRequest.ToString()); } private async Task BeExistingPatient(string email, CancellationToken cancellationToken) { var patient = await _patientRepository.FindByEmailAsync(email); return patient != null; } private async Task BeDifferentFromOldPassword(LoginDto dto, CancellationToken cancellationToken) { var currentPatient = await _patientRepository.FindByEmailAsync(dto.Email); return !_hashingAlgorithms.SHA256Algorithm(dto.Password) .Equals(currentPatient?.Password, StringComparison.Ordinal); } }