This commit is contained in:
andrei-mihnea-cerbu
2024-04-08 00:03:24 +03:00
parent 2ccec617a5
commit b48d5ee19e
168 changed files with 2877 additions and 1146 deletions
@@ -2,7 +2,7 @@
public class BaseResponse
{
public bool Success { get; set; }
public int StatusCode { get; set; }
public string? Message { get; set; }
public object? Data { get; set; }
}
}
@@ -1,7 +1,7 @@
namespace Application.Endpoints.Doctors.Login;
public class DoctorLoginDTO
public class DoctorLoginDto
{
public string? Email { get; set; }
public string? Password { get; set; }
}
}
@@ -1,37 +1,42 @@
using Application.Services.Database;
using Application.Services.HashingAlgorithms;
namespace Application.Endpoints.Doctors.Login;
public class DoctorLoginHandler
{
private readonly IDoctorRepository _database;
private readonly IHashingAlgorithms _hashingAlgorithms;
public DoctorLoginHandler(IDoctorRepository database)
public DoctorLoginHandler(IDoctorRepository database, IHashingAlgorithms hashingAlgorithms)
{
_database = database;
_hashingAlgorithms = hashingAlgorithms;
}
public async Task<BaseResponse> Handle(DoctorLoginDTO loginDTO)
public async Task<BaseResponse> Handle(DoctorLoginDto loginDTO)
{
loginDTO.Password = _hashingAlgorithms.SHA256Algorithm(loginDTO.Password);
var validation = new DoctorLoginValidation(_database);
var validationResult = await validation.ValidateAsync(loginDTO);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.FirstOrDefault()?.ErrorMessage;
if (validationResult.IsValid)
return new BaseResponse
{
Success = false,
Message = errorMessage,
StatusCode = HttpStatusCodes.OK,
Message = "Authentication successful",
Data = null
};
}
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
Success = true,
Message = "Authentication successful",
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
}
}
@@ -3,7 +3,7 @@ using FluentValidation;
namespace Application.Endpoints.Doctors.Login;
public class DoctorLoginValidation : AbstractValidator<DoctorLoginDTO>
public class DoctorLoginValidation : AbstractValidator<DoctorLoginDto>
{
private readonly IDoctorRepository _doctorRepository;
@@ -12,13 +12,16 @@ public class DoctorLoginValidation : AbstractValidator<DoctorLoginDTO>
_doctorRepository = doctorRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeExistingDoctor).WithMessage("Doctor with this email does not exist.");
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeExistingDoctor).WithMessage("Doctor with this email does not exist.")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.");
.NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync((dto, password, cancellationToken) => CredentialsMatch(dto.Email, password, cancellationToken))
.WithMessage("Incorrect email or password.")
.WithErrorCode(HttpStatusCodes.Unauthorized.ToString());
}
private async Task<bool> BeExistingDoctor(string email, CancellationToken cancellationToken)
@@ -26,4 +29,10 @@ public class DoctorLoginValidation : AbstractValidator<DoctorLoginDTO>
var doctor = await _doctorRepository.FindByEmailAsync(email);
return doctor != null;
}
}
private async Task<bool> CredentialsMatch(string email, string password, CancellationToken cancellationToken)
{
var code = await _doctorRepository.CredentialsMatch(email, password);
return code;
}
}
@@ -1,32 +1,33 @@
using Application.Services.Database;
using Application.Services.HashingAlgorithms;
namespace Application.Endpoints.Doctors.Profile;
public class DoctorProfileHandler
{
private readonly IDoctorRepository _doctorRepository;
private readonly IDoctorRepository _database;
private readonly IHashingAlgorithms _hashingAlgorithms;
public DoctorProfileHandler(IDoctorRepository doctorRepository)
public DoctorProfileHandler(IDoctorRepository database, IHashingAlgorithms hashingAlgorithms)
{
_doctorRepository = doctorRepository;
_database = database;
_hashingAlgorithms = hashingAlgorithms;
}
public async Task<BaseResponse> HandleGet(Guid id)
{
var doctor = await _doctorRepository.GetByIdAsync(id).ConfigureAwait(false);
var doctor = await _database.GetByIdAsync(id).ConfigureAwait(false);
if (doctor != null)
{
return new BaseResponse
{
Success = true,
StatusCode = HttpStatusCodes.OK,
Message = $"Retrieved doctor with id: {id}",
Data = doctor
};
}
return new BaseResponse
{
Success = false,
StatusCode = HttpStatusCodes.NotFound,
Message = $"Doctor with id: {id} not found",
Data = null
};
@@ -34,88 +35,76 @@ public class DoctorProfileHandler
public async Task<BaseResponse> HandleGetAll()
{
var doctors = await _doctorRepository.GetAllAsync().ConfigureAwait(false);
var doctors = await _database.GetAllAsync().ConfigureAwait(false);
if (doctors.Any())
{
return new BaseResponse
{
Success = true,
StatusCode = HttpStatusCodes.OK,
Message = "Retrieved doctors",
Data = doctors.ToList()
};
}
return new BaseResponse
{
Success = false,
StatusCode = HttpStatusCodes.NotFound,
Message = "Doctors not found",
Data = null
};
}
public async Task<BaseResponse> HandleUpdate(Guid id, DoctorProfileDTO updateDto)
public async Task<BaseResponse> HandleUpdate(DoctorProfileUpdateDto doctorProfileUpdateDto)
{
var validation = new DoctorProfileValidation(_doctorRepository);
var validationResult = await validation.ValidateAsync(updateDto);
var validation = new DoctorProfileValidation(_database);
var validationResult = await validation.ValidateAsync(doctorProfileUpdateDto);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var doctorToUpdate = await _doctorRepository.GetByIdAsync(id);
var doctorToUpdate = await _database.GetByIdAsync(doctorProfileUpdateDto.Id);
doctorToUpdate.SetEmail(doctorProfileUpdateDto.Email);
doctorToUpdate.SetPassword(_hashingAlgorithms.SHA256Algorithm(doctorProfileUpdateDto.Password));
doctorToUpdate.SetName(doctorProfileUpdateDto.Name);
doctorToUpdate.SetDescription(doctorProfileUpdateDto.Description);
if (doctorToUpdate == null)
{
return new BaseResponse
{
Success = false,
Message = "Doctor not found for given Id",
Data = null
};
}
doctorToUpdate.Email = updateDto.Email;
doctorToUpdate.Password = updateDto.Password;
doctorToUpdate.Name = updateDto.Name;
doctorToUpdate.Description = updateDto.Description;
await _doctorRepository.UpdateAsync(doctorToUpdate);
await _database.UpdateAsync(doctorToUpdate);
return new BaseResponse
{
Success = true,
Message = "Doctor updated successfully",
Data = doctorToUpdate
StatusCode = HttpStatusCodes.NoContent,
Message = null,
Data = null
};
}
public async Task<BaseResponse> HandleDelete(Guid id)
{
var doctorToDelete = await _doctorRepository.GetByIdAsync(id);
var doctorToDelete = await _database.GetByIdAsync(id);
if (doctorToDelete == null)
{
return new BaseResponse
{
Success = false,
Message = $"Doctor with id: {id} does not exist",
StatusCode = HttpStatusCodes.NotFound,
Message = "Doctor was not found.",
Data = null
};
}
await _doctorRepository.DeleteAsync(doctorToDelete);
await _database.DeleteAsync(doctorToDelete);
return new BaseResponse
{
Success = true,
Message = $"Doctor with id: {id} was succesfully deleted",
Data = doctorToDelete
StatusCode = HttpStatusCodes.NoContent,
Message = null,
Data = null
};
}
}
}
@@ -1,9 +1,10 @@
namespace Application.Endpoints.Doctors.Profile;
public class DoctorProfileDTO
public class DoctorProfileUpdateDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Description { get; set; }
}
}
@@ -3,7 +3,7 @@ using FluentValidation;
namespace Application.Endpoints.Doctors.Profile;
public class DoctorProfileValidation : AbstractValidator<DoctorProfileDTO>
public class DoctorProfileValidation : AbstractValidator<DoctorProfileUpdateDto>
{
private readonly IDoctorRepository _doctorRepository;
@@ -11,30 +11,41 @@ public class DoctorProfileValidation : AbstractValidator<DoctorProfileDTO>
{
_doctorRepository = doctorRepository;
RuleFor(x => x.Id)
.NotEmpty().WithMessage("Id is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(IsDoctorRegistered).WithMessage("Doctor is registered in system")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeUniqueEmail).WithMessage("Email in use by another doctor.");
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeUniqueEmail).WithMessage("Email in use by another doctor.")
.WithErrorCode(HttpStatusCodes.Conflict.ToString());
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.");
.NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required.")
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.");
.NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Description)
.MaximumLength(3000).WithMessage("Description must not exceed 3000 characters.");
.MaximumLength(3000).WithMessage("Description must not exceed 3000 characters.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> IsDoctorRegistered(Guid id, CancellationToken cancellationToken)
{
var doctor = await _doctorRepository.GetByIdAsync(id);
return doctor == null;
}
private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
{
var doctor = await _doctorRepository.FindByEmailAsync(email);
if (doctor != null)
{
return doctor.Email.Equals(email, StringComparison.OrdinalIgnoreCase);
}
return doctor == null;
}
}
}
@@ -1,9 +1,9 @@
namespace Application.Endpoints.Doctors.Login;
namespace Application.Endpoints.Doctors.Registration;
public class DoctorRegistrationDto
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Description { get; set; }
}
public string? Name { get; set; }
public string? Email { get; set; }
public string? Password { get; set; }
public string? Description { get; set; }
}
@@ -1,5 +1,5 @@
using Application.Endpoints.Doctors.Login;
using Application.Services.Database;
using Application.Services.Database;
using Application.Services.HashingAlgorithms;
using Core.Entities;
namespace Application.Endpoints.Doctors.Registration;
@@ -7,10 +7,12 @@ namespace Application.Endpoints.Doctors.Registration;
public class DoctorRegistrationHandler
{
private readonly IDoctorRepository _doctorRepository;
private readonly IHashingAlgorithms _hashingAlgorithms;
public DoctorRegistrationHandler(IDoctorRepository doctorRepository)
public DoctorRegistrationHandler(IDoctorRepository doctorRepository, IHashingAlgorithms hashingAlgorithms)
{
_doctorRepository = doctorRepository;
_hashingAlgorithms = hashingAlgorithms;
}
public async Task<BaseResponse> Handle(DoctorRegistrationDto registrationDTO)
@@ -20,30 +22,31 @@ public class DoctorRegistrationHandler
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var doctor = new Doctor
{
Email = registrationDTO.Email,
Password = registrationDTO.Password,
Name = registrationDTO.Name,
Description = registrationDTO.Description
};
var doctor = new Doctor();
doctor.SetEmail(registrationDTO.Email);
doctor.SetPassword(_hashingAlgorithms.SHA256Algorithm(registrationDTO.Password));
doctor.SetName(registrationDTO.Name);
doctor.SetDescription(registrationDTO.Description);
await _doctorRepository.AddAsync(doctor);
return new BaseResponse
{
Success = true,
StatusCode = HttpStatusCodes.Created,
Message = "Doctor registered successfully",
Data = doctor // Be careful with sending sensitive data like Passwords
Data = null
};
}
}
}
@@ -1,5 +1,4 @@
using Application.Endpoints.Doctors.Login;
using Application.Services.Database;
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Doctors.Registration;
@@ -13,20 +12,24 @@ public class DoctorRegistrationValidation : AbstractValidator<DoctorRegistration
_doctorRepository = doctorRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeUniqueEmail).WithMessage("Email already exists.");
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeUniqueEmail).WithMessage("Email already exists.")
.WithErrorCode(HttpStatusCodes.Conflict.ToString());
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.");
.NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required.")
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.");
.NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Description)
.MaximumLength(3000).WithMessage("Description must not exceed 3000 characters.");
.MaximumLength(3000).WithMessage("Description must not exceed 3000 characters.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
@@ -34,4 +37,4 @@ public class DoctorRegistrationValidation : AbstractValidator<DoctorRegistration
var doctor = await _doctorRepository.FindByEmailAsync(email);
return doctor == null;
}
}
}
@@ -0,0 +1,7 @@
namespace Application.Endpoints.Doctors.ResetPassword;
public class DoctorResetPasswordDto
{
public string? Email { get; set; }
public string? Password { get; set; }
}
@@ -1,58 +1,49 @@
using Application.Endpoints.Doctors.Login;
using Application.Services.Database;
using Application.Services.Database;
using Application.Services.HashingAlgorithms;
namespace Application.Endpoints.Doctors.ResetPassword;
public class DoctorResetPasswordHandler
{
private readonly IDoctorRepository _doctorRepository;
private readonly IHashingAlgorithms _hashingAlgorithms;
public DoctorResetPasswordHandler(IDoctorRepository doctorRepository)
public DoctorResetPasswordHandler(IDoctorRepository doctorRepository, IHashingAlgorithms hashingAlgorithms)
{
_doctorRepository = doctorRepository;
_hashingAlgorithms = hashingAlgorithms;
}
public async Task<BaseResponse> Handle(DoctorLoginDTO resetDoctorDto)
public async Task<BaseResponse> Handle(DoctorResetPasswordDto resetDoctorDto)
{
var validation = new DoctorResetPasswordValidation(_doctorRepository);
var validationResult = await validation.ValidateAsync(resetDoctorDto);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var currentDoctor = await _doctorRepository.FindByEmailAsync(resetDoctorDto.Email);
var updatedDoctor = currentDoctor;
updatedDoctor.Password = resetDoctorDto.Password;
updatedDoctor.SetPassword(_hashingAlgorithms.SHA256Algorithm(resetDoctorDto.Password));
await _doctorRepository.UpdateAsync(updatedDoctor);
updatedDoctor = await _doctorRepository.GetByIdAsync(currentDoctor.Id);
if (updatedDoctor.Password != resetDoctorDto.Password)
{
return new BaseResponse
{
Success = false,
Message = $"Failed to update passwor for doctor {updatedDoctor.Name}",
Data = null
};
}
return new BaseResponse
{
Success = true,
Message = $"Password of doctor {updatedDoctor.Name} has been reset succesfully",
Data = updatedDoctor.Email
StatusCode = HttpStatusCodes.OK,
Message = "Password successfully changed!",
Data = null
};
}
}
}
@@ -1,9 +1,9 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Doctors.Login;
namespace Application.Endpoints.Doctors.ResetPassword;
public class DoctorResetPasswordValidation : AbstractValidator<DoctorLoginDTO>
public class DoctorResetPasswordValidation : AbstractValidator<DoctorResetPasswordDto>
{
private readonly IDoctorRepository _doctorRepository;
@@ -12,15 +12,19 @@ public class DoctorResetPasswordValidation : AbstractValidator<DoctorLoginDTO>
_doctorRepository = doctorRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeExistingDoctor).WithMessage("Doctor with this email does not exist.");
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeExistingDoctor).WithMessage("Doctor with this email does not exist.")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
.MustAsync((dto, password, context, cancellationToken) => BeDifferentFromOldPassword(dto.Email, password, cancellationToken))
.WithMessage("New password cannot be the same as old password.");
.WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync((dto, password, context, cancellationToken) =>
BeDifferentFromOldPassword(dto.Email, password, cancellationToken))
.WithMessage("New password cannot be the same as old password.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> BeExistingDoctor(string email, CancellationToken cancellationToken)
@@ -29,9 +33,10 @@ public class DoctorResetPasswordValidation : AbstractValidator<DoctorLoginDTO>
return doctor != null;
}
private async Task<bool> BeDifferentFromOldPassword(string email, string newPassword, CancellationToken cancellationToken)
private async Task<bool> BeDifferentFromOldPassword(string email, string newPassword,
CancellationToken cancellationToken)
{
var currentDoctor = await _doctorRepository.FindByEmailAsync(email);
return !newPassword.Equals(currentDoctor?.Password, StringComparison.Ordinal);
}
}
}
@@ -0,0 +1,16 @@
namespace Application.Endpoints;
public static class HttpStatusCodes
{
public const int OK = 200;
public const int Created = 201;
public const int NoContent = 204;
public const int BadRequest = 400;
public const int Unauthorized = 401;
public const int Forbidden = 403;
public const int NotFound = 404;
public const int Conflict = 409;
public const int InternalServerError = 500;
// Add more status codes as needed
}
@@ -1,7 +1,7 @@
namespace Application.Endpoints.MedicalHistories;
public class MedicalHistoryDTO
public class MedicalHistoryCreateDto
{
public Guid UserId { get; set; }
public byte[] Description { get; set; } = [];
}
public byte[] Content { get; set; } = [];
}
@@ -3,25 +3,26 @@ using FluentValidation;
namespace Application.Endpoints.MedicalHistories;
public class MedicalHistoryCreateValidation : AbstractValidator<MedicalHistoryDTO>
public class MedicalHistoryCreateValidation : AbstractValidator<MedicalHistoryCreateDto>
{
private readonly IPacientRepository _pacientRepository;
private readonly IPatientRepository _patientRepository;
public MedicalHistoryCreateValidation(IPacientRepository pacientRepository)
public MedicalHistoryCreateValidation(IPatientRepository patientRepository)
{
_pacientRepository = pacientRepository;
_patientRepository = patientRepository;
RuleFor(x => x.UserId)
.NotEmpty().WithMessage("Pacient is required.")
.MustAsync(BeExistingUser).WithMessage("Specified pacient id doesn't exist.");
.NotEmpty().WithMessage("Patient is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeExistingUser).WithMessage("Specified patient doesn't exist.")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
RuleFor(x => x.Description)
.NotEmpty().WithMessage("Description is required.");
RuleFor(x => x.Content)
.NotEmpty().WithMessage("Description is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> BeExistingUser(Guid userId, CancellationToken cancellationToken)
{
var pacient = await _pacientRepository.GetByIdAsync(userId);
return pacient != null;
var patient = await _patientRepository.GetByIdAsync(userId);
return patient != null;
}
}
}
@@ -6,104 +6,142 @@ namespace Application.Endpoints.MedicalHistories;
public class MedicalHistoryHandler
{
private readonly IMedicalHistoryRepository _medicalHistoryRepository;
private readonly IPacientRepository _pacientRepository;
private readonly IMongoDbService _mongoDbService;
private readonly IPatientRepository _patientRepository;
public MedicalHistoryHandler(IMedicalHistoryRepository medicalHistoryRepository, IPacientRepository pacientRepository)
public MedicalHistoryHandler(IMedicalHistoryRepository medicalHistoryRepository,
IPatientRepository patientRepository, IMongoDbService mongoDbService)
{
_medicalHistoryRepository = medicalHistoryRepository;
_pacientRepository = pacientRepository;
_patientRepository = patientRepository;
_mongoDbService = mongoDbService;
}
public async Task<BaseResponse> HandleGet(Guid id)
public async Task<BaseResponse> HandleGetAll()
{
var medicalHistory = await _medicalHistoryRepository.GetByIdAsync(id).ConfigureAwait(false);
if (medicalHistory != null)
{
var documents = await _medicalHistoryRepository.GetAllAsync().ConfigureAwait(false);
if (documents.Any())
return new BaseResponse
{
Success = true,
Message = $"Retrieved Medical History with id: {id}",
Data = medicalHistory
StatusCode = HttpStatusCodes.OK,
Message = "Retrieved medical histories",
Data = documents.ToList()
};
}
return new BaseResponse
{
Success = false,
Message = $"Medical History with id: {id} not found",
StatusCode = HttpStatusCodes.NotFound,
Message = "Medical histories not found",
Data = null
};
}
public async Task<BaseResponse> HandleCreate(Guid userId, byte[] description)
public async Task<BaseResponse> HandleGet(Guid id)
{
var validation = new MedicalHistoryCreateValidation(_pacientRepository);
var validationResult = await validation.ValidateAsync(new MedicalHistoryDTO { UserId = userId, Description = description});
var medicalHistory = await _medicalHistoryRepository.GetByIdAsync(id).ConfigureAwait(false);
if (medicalHistory != null)
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = "Medical history successfully retrieved",
Data = medicalHistory
};
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Medical history not found in system.",
Data = null
};
}
public async Task<BaseResponse> HandleCreate(MedicalHistoryCreateDto medicalHistoryCreateDto)
{
var validation = new MedicalHistoryCreateValidation(_patientRepository);
var validationResult = await validation.ValidateAsync(medicalHistoryCreateDto);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var medicalHistory = new MedicalHistory
{
UserId = userId,
Description = description
UserId = medicalHistoryCreateDto.UserId,
Content = medicalHistoryCreateDto.Content
};
await _medicalHistoryRepository.AddAsync(medicalHistory);
//TODO add to MongoDB
return new BaseResponse
{
Success = true,
StatusCode = HttpStatusCodes.Created,
Message = "Medical history record registered successfully",
Data = medicalHistory
};
}
public async Task<BaseResponse> HandleUpdate(Guid id, MedicalHistoryDTO updateDto)
public async Task<BaseResponse> HandleUpdate(MedicalHistoryUpdateDto updateDto)
{
var validation = new MedicalHistoryUpdateValidation(_medicalHistoryRepository, _pacientRepository);
var validationResult = await validation.ValidateAsync(new MedicalHistoryUpdateDTO { Id = id, UserId = updateDto.UserId, Description = updateDto.Description});
var validation = new MedicalHistoryUpdateValidation(_medicalHistoryRepository, _patientRepository);
var validationResult = await validation.ValidateAsync(updateDto);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var medicalHistoryToUpdate = await _medicalHistoryRepository.GetByIdAsync(id);
if (medicalHistoryToUpdate == null)
{
return new BaseResponse
{
Success = false,
Message = "Medical history not found for given Id",
Data = null
};
}
medicalHistoryToUpdate.UserId = updateDto.UserId;
medicalHistoryToUpdate.Description = updateDto.Description;
var medicalHistoryToUpdate = await _medicalHistoryRepository.GetByIdAsync(updateDto.Id);
medicalHistoryToUpdate.Content = updateDto.Content;
await _medicalHistoryRepository.UpdateAsync(medicalHistoryToUpdate);
return new BaseResponse
{
Success = true,
Message = "Pacient updated successfully",
Data = medicalHistoryToUpdate
StatusCode = HttpStatusCodes.NoContent,
Message = "Medical record updated successfully",
Data = null
};
}
}
public async Task<BaseResponse> HandleDelete(Guid id)
{
var medicalRecord = await _medicalHistoryRepository.GetByIdAsync(id);
if (medicalRecord == null)
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Medical record is not in system.",
Data = null
};
await _medicalHistoryRepository.DeleteAsync(medicalRecord);
//TODO delete from MongoDB
return new BaseResponse
{
StatusCode = HttpStatusCodes.NoContent,
Message = null,
Data = null
};
}
}
@@ -1,8 +1,7 @@
namespace Application.Endpoints.MedicalHistories;
public class MedicalHistoryUpdateDTO
public class MedicalHistoryUpdateDto
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public byte[] Description { get; set; } = [];
}
public byte[] Content { get; set; } = [];
}
@@ -3,25 +3,22 @@ using FluentValidation;
namespace Application.Endpoints.MedicalHistories;
public class MedicalHistoryUpdateValidation : AbstractValidator<MedicalHistoryUpdateDTO>
public class MedicalHistoryUpdateValidation : AbstractValidator<MedicalHistoryUpdateDto>
{
private readonly IMedicalHistoryRepository _medicalHistoryRepository;
private readonly IPacientRepository _pacientRepository;
private readonly IPatientRepository _patientRepository;
public MedicalHistoryUpdateValidation(IMedicalHistoryRepository medicalHistoryRepository, IPacientRepository pacientRepository)
public MedicalHistoryUpdateValidation(IMedicalHistoryRepository medicalHistoryRepository,
IPatientRepository patientRepository)
{
_medicalHistoryRepository = medicalHistoryRepository;
_pacientRepository = pacientRepository;
_patientRepository = patientRepository;
RuleFor(x => x.Id)
.NotEmpty().WithMessage("Id is required")
.MustAsync(BeExistingMedicalHistoryRecord).WithMessage("Medical hostory record does not exist");
.MustAsync(BeExistingMedicalHistoryRecord).WithMessage("Medical history record does not exist");
RuleFor(x => x.UserId)
.NotEmpty().WithMessage("Pacient is required.")
.MustAsync(BeExistingUser).WithMessage("Specified pacient id doesn't exist.");
RuleFor(x => x.Description)
RuleFor(x => x.Content)
.NotEmpty().WithMessage("Description is required.");
}
@@ -30,10 +27,4 @@ public class MedicalHistoryUpdateValidation : AbstractValidator<MedicalHistoryUp
var record = await _medicalHistoryRepository.GetByIdAsync(guid);
return record != null;
}
private async Task<bool> BeExistingUser(Guid userId, CancellationToken cancellationToken)
{
var pacient = await _pacientRepository.GetByIdAsync(userId);
return pacient != null;
}
}
}
@@ -1,37 +0,0 @@
using Application.Services.Database;
namespace Application.Endpoints.Pacients.Login;
public class PacientLoginHandler
{
private readonly IPacientRepository _database;
public PacientLoginHandler(IPacientRepository database)
{
_database = database;
}
public async Task<BaseResponse> Handle(PacientLoginDTO loginDTO)
{
var validation = new PacientLoginValidation(_database);
var validationResult = await validation.ValidateAsync(loginDTO);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.FirstOrDefault()?.ErrorMessage;
return new BaseResponse
{
Success = false,
Message = errorMessage,
Data = null
};
}
return new BaseResponse
{
Success = true,
Message = "Authentication successful",
Data = null
};
}
}
@@ -1,29 +0,0 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Pacients.Login;
public class PacientLoginValidation : AbstractValidator<PacientLoginDTO>
{
private readonly IPacientRepository _pacientRepository;
public PacientLoginValidation(IPacientRepository pacientRepository)
{
_pacientRepository = pacientRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeExistingPacient).WithMessage("Pacient with this email does not exist.");
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.");
}
private async Task<bool> BeExistingPacient(string email, CancellationToken cancellationToken)
{
var pacient = await _pacientRepository.FindByEmailAsync(email);
return pacient != null;
}
}
@@ -1,9 +0,0 @@
namespace Application.Endpoints.Pacients.Profile;
public class PacientProfileDTO
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Description { get; set; }
}
@@ -1,120 +0,0 @@
using Application.Services.Database;
namespace Application.Endpoints.Pacients.Profile;
public class PacientProfileHandler
{
private readonly IPacientRepository _pacientRepository;
public PacientProfileHandler(IPacientRepository pacientRepository)
{
_pacientRepository = pacientRepository;
}
public async Task<BaseResponse> HandleGet(Guid id)
{
var pacient = await _pacientRepository.GetByIdAsync(id).ConfigureAwait(false);
if (pacient != null)
{
return new BaseResponse
{
Success = true,
Message = $"Retrieved pacient with id: {id}",
Data = pacient
};
}
return new BaseResponse
{
Success = false,
Message = $"Pacient with id: {id} not found",
Data = null
};
}
public async Task<BaseResponse> HandleGetAll()
{
var pacients = await _pacientRepository.GetAllAsync().ConfigureAwait(false);
if (pacients.Any())
{
return new BaseResponse
{
Success = true,
Message = "Retrieved pacients",
Data = pacients.ToList()
};
}
return new BaseResponse
{
Success = false,
Message = "Pacients not found",
Data = null
};
}
public async Task<BaseResponse> HandleUpdate(Guid id, PacientProfileDTO updateDto)
{
var validation = new PacientProfileValidation(_pacientRepository);
var validationResult = await validation.ValidateAsync(updateDto);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
Data = null
};
}
var pacientToUpdate = await _pacientRepository.GetByIdAsync(id);
if (pacientToUpdate == null)
{
return new BaseResponse
{
Success = false,
Message = "Pacient not found for given Id",
Data = null
};
}
pacientToUpdate.Email = updateDto.Email;
pacientToUpdate.Password = updateDto.Password;
pacientToUpdate.Name = updateDto.Name;
await _pacientRepository.UpdateAsync(pacientToUpdate);
return new BaseResponse
{
Success = true,
Message = "Pacient updated successfully",
Data = pacientToUpdate
};
}
public async Task<BaseResponse> HandleDelete(Guid id)
{
var pacientToDelete = await _pacientRepository.GetByIdAsync(id);
if (pacientToDelete == null)
{
return new BaseResponse
{
Success = false,
Message = $"Pacient with id: {id} does not exist",
Data = null
};
}
await _pacientRepository.DeleteAsync(pacientToDelete);
return new BaseResponse
{
Success = true,
Message = $"Pacient with id: {id} was succesfully deleted",
Data = pacientToDelete
};
}
}
@@ -1,40 +0,0 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Pacients.Profile;
public class PacientProfileValidation : AbstractValidator<PacientProfileDTO>
{
private readonly IPacientRepository _pacientRepository;
public PacientProfileValidation(IPacientRepository pacientRepository)
{
_pacientRepository = pacientRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeUniqueEmail).WithMessage("Email in use by another pacient.");
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.");
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required.")
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.");
RuleFor(x => x.Description)
.MaximumLength(3000).WithMessage("Description must not exceed 3000 characters.");
}
private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
{
var pacient = await _pacientRepository.FindByEmailAsync(email);
if (pacient != null)
{
return pacient.Email.Equals(email, StringComparison.OrdinalIgnoreCase);
}
return pacient == null;
}
}
@@ -1,48 +0,0 @@
using Application.Endpoints.Pacients.Login;
using Application.Services.Database;
using Core.Entities;
namespace Application.Endpoints.Pacients.Registration;
public class PacientRegistrationHandler
{
private readonly IPacientRepository _pacientRepository;
public PacientRegistrationHandler(IPacientRepository pacientRepository)
{
_pacientRepository = pacientRepository;
}
public async Task<BaseResponse> Handle(PacientRegistrationDto registrationDTO)
{
var validation = new PacientRegistrationValidation(_pacientRepository);
var validationResult = await validation.ValidateAsync(registrationDTO);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
Data = null
};
}
var pacient = new Pacient
{
Email = registrationDTO.Email,
Password = registrationDTO.Password,
Name = registrationDTO.Name
};
await _pacientRepository.AddAsync(pacient);
return new BaseResponse
{
Success = true,
Message = "Pacient registered successfully",
Data = pacient // Be careful with sending sensitive data like Passwords
};
}
}
@@ -1,34 +0,0 @@
using Application.Endpoints.Pacients.Login;
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Pacients.Registration;
public class PacientRegistrationValidation : AbstractValidator<PacientRegistrationDto>
{
private readonly IPacientRepository _pacientRepository;
public PacientRegistrationValidation(IPacientRepository pacientRepository)
{
_pacientRepository = pacientRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeUniqueEmail).WithMessage("Email already exists.");
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.");
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required.")
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.");
}
private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
{
var pacient = await _pacientRepository.FindByEmailAsync(email);
return pacient == null;
}
}
@@ -1,58 +0,0 @@
using Application.Endpoints.Pacients.Login;
using Application.Services.Database;
namespace Application.Endpoints.Pacients.ResetPassword;
public class PacientResetPasswordHandler
{
private readonly IPacientRepository _pacientRepository;
public PacientResetPasswordHandler(IPacientRepository pacientRepository)
{
_pacientRepository = pacientRepository;
}
public async Task<BaseResponse> Handle(PacientLoginDTO resetPacientDto)
{
var validation = new PacientResetPasswordValidation(_pacientRepository);
var validationResult = await validation.ValidateAsync(resetPacientDto);
if (!validationResult.IsValid)
{
var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
return new BaseResponse
{
Success = false,
Message = string.Join(", ", errorMessage),
Data = null
};
}
var currentPacient = await _pacientRepository.FindByEmailAsync(resetPacientDto.Email);
var updatedPacient = currentPacient;
updatedPacient.Password = resetPacientDto.Password;
await _pacientRepository.UpdateAsync(updatedPacient);
updatedPacient = await _pacientRepository.GetByIdAsync(currentPacient.Id);
if (updatedPacient.Password != resetPacientDto.Password)
{
return new BaseResponse
{
Success = false,
Message = $"Failed to update passwor for pacient {updatedPacient.Name}",
Data = null
};
}
return new BaseResponse
{
Success = true,
Message = $"Password of pacient {updatedPacient.Name} has been reset succesfully",
Data = updatedPacient.Email
};
}
}
@@ -1,37 +0,0 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Pacients.Login;
public class PacientResetPasswordValidation : AbstractValidator<PacientLoginDTO>
{
private readonly IPacientRepository _pacientRepository;
public PacientResetPasswordValidation(IPacientRepository pacientRepository)
{
_pacientRepository = pacientRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email format.")
.MustAsync(BeExistingPacient).WithMessage("Pacient with this email does not exist.");
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
.MustAsync((dto, password, context, cancellationToken) => BeDifferentFromOldPassword(dto.Email, password, cancellationToken))
.WithMessage("New password cannot be the same as old password.");
}
private async Task<bool> BeExistingPacient(string email, CancellationToken cancellationToken)
{
var pacient = await _pacientRepository.FindByEmailAsync(email);
return pacient != null;
}
private async Task<bool> BeDifferentFromOldPassword(string email, string newPassword, CancellationToken cancellationToken)
{
var currentPacient = await _pacientRepository.FindByEmailAsync(email);
return !newPassword.Equals(currentPacient?.Password, StringComparison.Ordinal);
}
}
@@ -1,7 +1,7 @@
namespace Application.Endpoints.Pacients.Login;
namespace Application.Endpoints.Patients.Login;
public class PacientLoginDTO
public class PatientLoginDto
{
public string? Email { get; set; }
public string? Password { get; set; }
}
}
@@ -0,0 +1,37 @@
using Application.Services.Database;
namespace Application.Endpoints.Patients.Login;
public class PatientLoginHandler
{
private readonly IPatientRepository _database;
public PatientLoginHandler(IPatientRepository database)
{
_database = database;
}
public async Task<BaseResponse> Handle(PatientLoginDto loginDTO)
{
var validation = new PatientLoginValidation(_database);
var validationResult = await validation.ValidateAsync(loginDTO);
if (validationResult.IsValid)
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = "Authentication successful",
Data = null
};
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
}
@@ -0,0 +1,31 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Patients.Login;
public class PatientLoginValidation : AbstractValidator<PatientLoginDto>
{
private readonly IPatientRepository _patientRepository;
public PatientLoginValidation(IPatientRepository patientRepository)
{
_patientRepository = patientRepository;
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())
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> BeExistingPatient(string email, CancellationToken cancellationToken)
{
var patient = await _patientRepository.FindByEmailAsync(email);
return patient != null;
}
}
@@ -0,0 +1,9 @@
namespace Application.Endpoints.Patients.Profile;
public class PatientProfileDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
@@ -0,0 +1,110 @@
using Application.Services.Database;
using Application.Services.HashingAlgorithms;
namespace Application.Endpoints.Patients.Profile;
public class PatientProfileHandler
{
private readonly IHashingAlgorithms _hashingAlgorithms;
private readonly IPatientRepository _patientRepository;
public PatientProfileHandler(IPatientRepository patientRepository, IHashingAlgorithms hashingAlgorithms)
{
_patientRepository = patientRepository;
_hashingAlgorithms = hashingAlgorithms;
}
public async Task<BaseResponse> HandleGet(Guid id)
{
var patient = await _patientRepository.GetByIdAsync(id).ConfigureAwait(false);
if (patient != null)
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = $"Retrieved patient with id: {id}",
Data = patient
};
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = $"Patient with id: {id} not found",
Data = null
};
}
public async Task<BaseResponse> HandleGetAll()
{
var patients = await _patientRepository.GetAllAsync().ConfigureAwait(false);
if (patients.Any())
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = "Retrieved patients",
Data = patients.ToList()
};
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Patients not found",
Data = null
};
}
public async Task<BaseResponse> HandleUpdate(PatientProfileDto updateDto)
{
var validation = new PatientProfileValidation(_patientRepository);
var validationResult = await validation.ValidateAsync(updateDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var patientToUpdate = await _patientRepository.GetByIdAsync(updateDto.Id);
patientToUpdate.SetEmail(updateDto.Email);
patientToUpdate.SetPassword(_hashingAlgorithms.SHA256Algorithm(updateDto.Password));
patientToUpdate.SetName(updateDto.Name);
await _patientRepository.UpdateAsync(patientToUpdate);
return new BaseResponse
{
StatusCode = HttpStatusCodes.NoContent,
Message = null,
Data = null
};
}
public async Task<BaseResponse> HandleDelete(Guid id)
{
var patientToDelete = await _patientRepository.GetByIdAsync(id);
if (patientToDelete == null)
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Patient not found.",
Data = null
};
await _patientRepository.DeleteAsync(patientToDelete);
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = null,
Data = null
};
}
}
@@ -0,0 +1,47 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Patients.Profile;
public class PatientProfileValidation : AbstractValidator<PatientProfileDto>
{
private readonly IPatientRepository _patientRepository;
public PatientProfileValidation(IPatientRepository patientRepository)
{
_patientRepository = patientRepository;
RuleFor(x => x.Id)
.NotEmpty().WithMessage("Id is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(IsPatientRegistered).WithMessage("Patient is registered in system")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeUniqueEmail).WithMessage("Email in use by another patient.")
.WithErrorCode(HttpStatusCodes.Conflict.ToString());
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> IsPatientRegistered(Guid id, CancellationToken cancellationToken)
{
var doctor = await _patientRepository.GetByIdAsync(id);
return doctor == null;
}
private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
{
var patient = await _patientRepository.FindByEmailAsync(email);
return patient == null;
}
}
@@ -1,8 +1,8 @@
namespace Application.Endpoints.Pacients.Login;
namespace Application.Endpoints.Patients.Registration;
public class PacientRegistrationDto
public class PatientRegistrationDto
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
}
@@ -0,0 +1,51 @@
using Application.Services.Database;
using Application.Services.HashingAlgorithms;
using Core.Entities;
namespace Application.Endpoints.Patients.Registration;
public class PatientRegistrationHandler
{
private readonly IHashingAlgorithms _hashingAlgorithms;
private readonly IPatientRepository _patientRepository;
public PatientRegistrationHandler(IPatientRepository patientRepository, IHashingAlgorithms hashingAlgorithms)
{
_patientRepository = patientRepository;
_hashingAlgorithms = hashingAlgorithms;
}
public async Task<BaseResponse> Handle(PatientRegistrationDto registrationDTO)
{
var validation = new PatientRegistrationValidation(_patientRepository);
var validationResult = await validation.ValidateAsync(registrationDTO);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var patient = new Patient();
patient.SetEmail(registrationDTO.Email);
patient.SetName(registrationDTO.Name);
patient.SetPassword(_hashingAlgorithms.SHA256Algorithm(registrationDTO.Password));
await _patientRepository.AddAsync(patient);
return new BaseResponse
{
StatusCode = HttpStatusCodes.Created,
Message = "Patient registered successfully",
Data = patient // Be careful with sending sensitive data like Passwords
};
}
}
@@ -0,0 +1,34 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Patients.Registration;
public class PatientRegistrationValidation : AbstractValidator<PatientRegistrationDto>
{
private readonly IPatientRepository _patientRepository;
public PatientRegistrationValidation(IPatientRepository patientRepository)
{
_patientRepository = patientRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeUniqueEmail).WithMessage("Email already exists.").WithErrorCode(HttpStatusCodes.Conflict.ToString());
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
{
var pacient = await _patientRepository.FindByEmailAsync(email);
return pacient == null;
}
}
@@ -0,0 +1,7 @@
namespace Application.Endpoints.Patients.ResetPassword;
public class PatientResetPasswordDto
{
public string? Email { get; set; }
public string? Password { get; set; }
}
@@ -0,0 +1,50 @@
using Application.Services.Database;
using Application.Services.HashingAlgorithms;
namespace Application.Endpoints.Patients.ResetPassword;
public class PatientResetPasswordHandler
{
private readonly IHashingAlgorithms _hashingAlgorithms;
private readonly IPatientRepository _patientRepository;
public PatientResetPasswordHandler(IPatientRepository patientRepository, IHashingAlgorithms hashingAlgorithms)
{
_patientRepository = patientRepository;
_hashingAlgorithms = hashingAlgorithms;
}
public async Task<BaseResponse> Handle(PatientResetPasswordDto patientResetPasswordDto)
{
patientResetPasswordDto.Password = _hashingAlgorithms.SHA256Algorithm(patientResetPasswordDto.Password);
var validation = new PatientResetPasswordValidation(_patientRepository);
var validationResult = await validation.ValidateAsync(patientResetPasswordDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var currentPatient = await _patientRepository.FindByEmailAsync(patientResetPasswordDto.Email);
var updatedPatient = currentPatient;
updatedPatient.SetPassword(_hashingAlgorithms.SHA256Algorithm(patientResetPasswordDto.Password));
await _patientRepository.UpdateAsync(updatedPatient);
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = "Password successfully changed!",
Data = null
};
}
}
@@ -0,0 +1,40 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.Patients.ResetPassword;
public class PatientResetPasswordValidation : AbstractValidator<PatientResetPasswordDto>
{
private readonly IPatientRepository _patientRepository;
public PatientResetPasswordValidation(IPatientRepository patientRepository)
{
_patientRepository = patientRepository;
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeExistingPacient).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())
.MustAsync((dto, password, context, cancellationToken) =>
BeDifferentFromOldPassword(dto.Email, password, cancellationToken))
.WithMessage("New password cannot be the same as old password.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> BeExistingPacient(string email, CancellationToken cancellationToken)
{
var pacient = await _patientRepository.FindByEmailAsync(email);
return pacient != null;
}
private async Task<bool> BeDifferentFromOldPassword(string email, string newPassword,
CancellationToken cancellationToken)
{
var currentPatient = await _patientRepository.FindByEmailAsync(email);
return !newPassword.Equals(currentPatient?.Password, StringComparison.Ordinal);
}
}