employeecontroller: < /p>
Код: Выделить всё
@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@PatchMapping
public ResponseEntity updateEmployee(@Valid @RequestBody UpdateEmployeeRequest updateEmployeeRequest) {
Employee employee = employeeService.updateEmployee(
updateEmployeeRequest.email(),
updateEmployeeRequest.password()
);
return ResponseEntity.ok(new EmployeeResponse(
employee.getId(),
employee.getUsername(),
employee.getRole().name()
));
}
}
< /code>
effectervice (код комментируется только на данный момент): < /p>
@Service
public class EmployeeService implements UserDetailsService {
private final PasswordEncoder passwordEncoder;
private final EmployeeRepository employeeRepository;
public EmployeeService(PasswordEncoder passwordEncoder, EmployeeRepository employeeRepository) {
this.passwordEncoder = passwordEncoder;
this.employeeRepository = employeeRepository;
}
public Employee updateEmployee(String email, String password) {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
String currentEmail = authentication.getName();
Optional optionalEmployee = employeeRepository.findByEmail(currentEmail);
if (optionalEmployee.isEmpty()) {
throw new EntityNotFoundException("Employee not found");
}
Employee employee = optionalEmployee.get();
//employee.setEmail(email);
//employee.setPassword(passwordEncoder.encode(password));
//return employeeRepository.save(employee);
return employee;
}
@Override
public UserDetails loadUserByUsername(String username) throws EntityNotFoundException {
return employeeRepository.findByEmail(username)
.orElseThrow(() -> new EntityNotFoundException("Employee with email " + username + " does not exist"));
}
}
< /code>
Сотрудник: < /p>
@Entity
@Table(name = "employees")
public class Employee extends User {
@NotNull
private EmployeeRole role;
public Employee() {
// new employee has the EMPLOYEE role by default
role = EmployeeRole.EMPLOYEE;
}
public EmployeeRole getRole() {
return role;
}
public void setRole(EmployeeRole role) {
this.role = role;
}
@Override
@Transient
public Collection
Подробнее здесь: [url]https://stackoverflow.com/questions/79445465/spring-boot-security-always-return-401[/url]