2026-02-25 14:29:55 +03:00

58 lines
2.2 KiB
Java

package com.example.nto.service.impl;
import com.example.nto.controller.dto.EmployeeDto;
import com.example.nto.controller.dto.EmployeeRegisterDto;
import com.example.nto.entity.Employee;
import com.example.nto.exception.EmployeeAlreadyExistsException;
import com.example.nto.exception.EmployeeNotFoundException;
import com.example.nto.exception.PasswordNotCorrectException;
import com.example.nto.repository.EmployeeRepository;
import com.example.nto.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {
private final EmployeeRepository employeeRepository;
private PasswordEncoder passwordEncoder;
@Override
@Transactional(readOnly = true)
public EmployeeDto getByUsername(String username) {
return employeeRepository.findByUsername(username).map(EmployeeDto::toDto)
.orElseThrow(() -> new EmployeeNotFoundException("Employee with " + username + " code not found!"));
}
@Override
@Transactional(readOnly = true)
public void auth(String username) {
if (employeeRepository.findByUsername(username).isEmpty()) {
throw new EmployeeNotFoundException("Employee with " + username + " username not found!");
}
}
@Override
public void register(EmployeeRegisterDto employeeRegisterDto) {
if (employeeRepository.findByUsername(employeeRegisterDto.getUsername()).isPresent()){
throw new EmployeeAlreadyExistsException("Employee with " + employeeRegisterDto.getUsername() + " username already exist");
};
Employee employee = new Employee();
if (passwordEncoder.encode(employee.getPassword()).length() < 8) {
throw new PasswordNotCorrectException("The password is too short!!!");
}
employee.setName(employeeRegisterDto.getName());
employee.setUsername(employeeRegisterDto.getUsername());
employee.setPassword(passwordEncoder.encode(employeeRegisterDto.getPassword()));
employeeRepository.save(employee);
}
}