finalizare 1.0
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
using Application.Services.Database.PostgreSQL;
|
||||
using Application.Services.HashingAlgorithms;
|
||||
using Application.Services.Jwt;
|
||||
using Domain;
|
||||
|
||||
namespace Application.Endpoints.Authorization.UserLogin;
|
||||
|
||||
public class UserLoginHandler(
|
||||
IJwtService jwtService,
|
||||
IHashingAlgorithms hashingAlgorithms,
|
||||
IDoctorRepository doctorRepository,
|
||||
IPatientRepository patientRepository,
|
||||
IAdminRepository adminRepository)
|
||||
{
|
||||
public async Task<BaseResponse> Handle(UserLoginCommand request, CancellationToken token)
|
||||
{
|
||||
var validator = new UserLoginValidator();
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
var email = request.Email;
|
||||
var password = hashingAlgorithms.Sha256Algorithm(request.Password);
|
||||
|
||||
if (await doctorRepository.CredentialsMatch(email, password, token))
|
||||
{
|
||||
var doctor = await doctorRepository.FindByEmailAsync(email, token);
|
||||
var authToken = jwtService.GenerateJwtToken(doctor.Id, UserRoles.Doctor, doctor.Name);
|
||||
return new BaseResponse
|
||||
{
|
||||
StatusCode = HttpStatusCodes.OK,
|
||||
Message = "Doctor logged in successfully.",
|
||||
Data = authToken
|
||||
};
|
||||
}
|
||||
|
||||
if (await patientRepository.CredentialsMatch(email, password, token))
|
||||
{
|
||||
var patient = await patientRepository.FindByEmailAsync(email, token);
|
||||
var authToken = jwtService.GenerateJwtToken(patient.Id, UserRoles.Patient, patient.Name);
|
||||
return new BaseResponse
|
||||
{
|
||||
StatusCode = HttpStatusCodes.OK,
|
||||
Message = "Patient logged in successfully.",
|
||||
Data = authToken
|
||||
};
|
||||
}
|
||||
|
||||
if (await adminRepository.CredentialsMatch(email, password, token))
|
||||
{
|
||||
var admin = await adminRepository.FindByEmailAsync(email, token);
|
||||
var authToken = jwtService.GenerateJwtToken(admin.Id, UserRoles.Admin, admin.Name);
|
||||
return new BaseResponse
|
||||
{
|
||||
StatusCode = HttpStatusCodes.OK,
|
||||
Message = "Admin logged in successfully.",
|
||||
Data = authToken
|
||||
};
|
||||
}
|
||||
|
||||
return new BaseResponse
|
||||
{
|
||||
StatusCode = HttpStatusCodes.NotFound,
|
||||
Message = "User not registered in our system.",
|
||||
Data = null
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user