package com.example.medweb.service.impl; import com.example.medweb.model.Pacient; import com.example.medweb.model.exceptions.InvalidArgumentsException; import com.example.medweb.model.exceptions.InvalidUserCredentialsException; import com.example.medweb.repository.PacientRepository; import com.example.medweb.service.PacientService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.Random; @Service public class PacientServiceImpl implements PacientService { private final PacientRepository pacientRepository; public PacientServiceImpl(PacientRepository pacientRepository) { this.pacientRepository = pacientRepository; } @Override public List listAll() { return this.pacientRepository.findAll(); } @Override public Optional findById(Integer id){ return this.pacientRepository.findById(id); } @Override public Optional findPacientByEmailAndPass(String email, String password) { return this.pacientRepository.findPacientByEmailAndPass(email, password); } @Override public Optional findPacientByEmail(String email) { return this.pacientRepository.findPacientByEmail(email); } @Override public void save(Pacient pacient){ BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String plainPass = pacient.getPass(); String cypherPass = encoder.encode(plainPass); pacient.setPass(cypherPass); Random random = new Random(); Integer pacient_id = random.nextInt(); pacient.setPacient_id(pacient_id); this.pacientRepository.save(pacient); } @Override public Pacient login(String email, String pass) { if (email == null || email.isEmpty() || pass == null || pass.isEmpty()) { throw new InvalidArgumentsException(); } Pacient pacient = this.pacientRepository.findPacientByEmail(email).get(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); if (encoder.matches(pass, pacient.getPass())) { pass = pacient.getPass(); } return pacientRepository.findPacientByEmailAndPass(email, pass) .orElseThrow(InvalidUserCredentialsException::new); } }