73 lines
2.6 KiB
C#
73 lines
2.6 KiB
C#
using Application.Services.Database.PostgreSQL;
|
|
using Application.Services.Email;
|
|
using Application.Services.HashingAlgorithms;
|
|
using Domain;
|
|
using Domain.Entities;
|
|
|
|
namespace Application.Endpoints.Authorization.UserRegister;
|
|
|
|
public class UserRegisterHandler(
|
|
IEmailService emailService,
|
|
IHashingAlgorithms hashingAlgorithms,
|
|
IDoctorRepository doctorRepository,
|
|
IPatientRepository patientRepository,
|
|
IAdminRepository adminRepository)
|
|
{
|
|
public async Task<BaseResponse> Handle(UserRegisterCommand request, CancellationToken token)
|
|
{
|
|
var validator = new UserRegisterValidator(
|
|
patientRepository, doctorRepository, adminRepository);
|
|
var result = await validator.ValidateAsync(request, token);
|
|
if (!result.IsValid)
|
|
{
|
|
var firstError = result.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
|
|
};
|
|
}
|
|
|
|
switch (request.Role)
|
|
{
|
|
case UserRoles.Admin:
|
|
var admin = new Admin();
|
|
admin.SetName(request.Name);
|
|
admin.SetEmail(request.Email);
|
|
admin.SetPassword(hashingAlgorithms.Sha256Algorithm(request.Password));
|
|
|
|
await adminRepository.AddAsync(admin, token);
|
|
break;
|
|
case UserRoles.Doctor:
|
|
var doctor = new Doctor();
|
|
doctor.SetName(request.Name);
|
|
doctor.SetEmail(request.Email);
|
|
doctor.SetPassword(hashingAlgorithms.Sha256Algorithm(request.Password));
|
|
|
|
await doctorRepository.AddAsync(doctor, token);
|
|
break;
|
|
case UserRoles.Patient:
|
|
var patient = new Patient();
|
|
patient.SetName(request.Name);
|
|
patient.SetEmail(request.Email);
|
|
patient.SetPassword(hashingAlgorithms.Sha256Algorithm(request.Password));
|
|
|
|
await patientRepository.AddAsync(patient, token);
|
|
break;
|
|
}
|
|
|
|
var emailBody = emailService.GenerateCredentialsEmailBody(request.Name, request.Email, request.Password);
|
|
await emailService.SendEmailAsync(request.Email, emailService.GetSuccessfulRegistrationSubject(), emailBody);
|
|
|
|
return new BaseResponse
|
|
{
|
|
StatusCode = HttpStatusCodes.Created,
|
|
Message = "User created successfully",
|
|
Data = null
|
|
};
|
|
}
|
|
} |