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
@@ -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);
}
}
}