diff --git a/src/main/java/com/example/nto/config/SecurityConfig.java b/src/main/java/com/example/nto/config/SecurityConfig.java new file mode 100644 index 0000000..65ec483 --- /dev/null +++ b/src/main/java/com/example/nto/config/SecurityConfig.java @@ -0,0 +1,57 @@ +package com.example.nto.config; + +import com.example.nto.entity.Employee; +import com.example.nto.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; // Для незашифрованных паролей +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; + +import java.util.Optional; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private EmployeeService employeeService; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .csrf().disable() // Отключ CSRF + .authorizeRequests() + .antMatchers("/api/auth").permitAll() // Разрешаем доступ к /auth + .anyRequest().authenticated() // Все запросы требуют аутентификации + .and() + .httpBasic(); // Включаем базу + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService()).passwordEncoder(NoOpPasswordEncoder.getInstance()); + } + + @Bean + public UserDetailsService userDetailsService() { + return username -> { + Optional employee = employeeService.findByLogin(username); + if (employee.isPresent()) { + Employee emp = employee.get(); + return org.springframework.security.core.userdetails.User.withUsername(emp.getLogin()) + .password(emp.getPassword()) + .roles(emp.getRole()) + .build(); + } else { + throw new UsernameNotFoundException("User not found with login: " + username); + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/nto/entity/Code.java b/src/main/java/com/example/nto/entity/Code.java index 1fc7891..9aef6b9 100644 --- a/src/main/java/com/example/nto/entity/Code.java +++ b/src/main/java/com/example/nto/entity/Code.java @@ -1,26 +1,42 @@ package com.example.nto.entity; import javax.persistence.*; -import java.io.Serializable; - - -import javax.persistence.*; -import lombok.*; - -@Data -@Builder -@NoArgsConstructor -@AllArgsConstructor @Entity -@Table(name = "code") public class Code { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - private long id; + private Long value; // Значение кода - private long value; -} -// made by truettwo \ No newline at end of file + @ManyToOne // Установите связь с Employee + @JoinColumn(name = "employee_id", nullable = false) + private Employee employee; + + // Геттеры и сеттеры + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getValue() { + return value; + } + + public void setValue(Long value) { + this.value = value; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/nto/entity/Employee.java b/src/main/java/com/example/nto/entity/Employee.java index a1be62f..ef9ef89 100644 --- a/src/main/java/com/example/nto/entity/Employee.java +++ b/src/main/java/com/example/nto/entity/Employee.java @@ -27,5 +27,27 @@ public class Employee { private String role; + public String getLogin() { + return login; // Возвращает логин + } + + public void setRole(String role) { + this.role = role; // Устанавливает роль + } + + public String getRole() { + return role; // Возвращает роль (например, 'admin' или 'user') + } + + public void setPassword(String password) { + this.password = password; // Устанавливает пароль + } + + public String getPassword() { + return password; // Возвращает пароль + } + + + } \ No newline at end of file diff --git a/src/main/java/com/example/nto/repository/CodeRepository.java b/src/main/java/com/example/nto/repository/CodeRepository.java index 499a363..0accbd9 100644 --- a/src/main/java/com/example/nto/repository/CodeRepository.java +++ b/src/main/java/com/example/nto/repository/CodeRepository.java @@ -2,7 +2,14 @@ package com.example.nto.repository; import com.example.nto.entity.Code; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; public interface CodeRepository extends JpaRepository { + // Метод для поиска кодов по логину + @Query("SELECT c.value FROM Code c WHERE c.employee.login = :login") + List findCodesByLogin(@Param("login") String login); } \ No newline at end of file diff --git a/src/main/java/com/example/nto/service/impl/EmployeeServiceImpl.java b/src/main/java/com/example/nto/service/impl/EmployeeServiceImpl.java index 5727c96..8f463c4 100644 --- a/src/main/java/com/example/nto/service/impl/EmployeeServiceImpl.java +++ b/src/main/java/com/example/nto/service/impl/EmployeeServiceImpl.java @@ -33,9 +33,16 @@ public class EmployeeServiceImpl implements EmployeeService { @Override public boolean validateCode(String login, long code) { - // Получаем все коды из репозитория - return codeRepository.findAll() - .stream() - .anyMatch(c -> c.getValue() == code); // Проверяем, есть ли код + // Получаем все коды для данного логина + List validCodes = codeRepository.findCodesByLogin(login); // Теперь вызывается из объекта + + // Проверяем, если переданный код присутствует в списке + boolean isValid = validCodes.contains(code); + + // Вывод отладочной информации + System.out.println("Valid codes: " + validCodes); + System.out.println("Input code: " + code); + + return isValid; } } \ No newline at end of file