open door working+fixes

This commit is contained in:
truettwo 2025-02-19 16:44:12 +03:00
parent a4e6862c3b
commit d541a44d96
4 changed files with 43 additions and 14 deletions

View File

@ -4,6 +4,7 @@ import com.example.nto.entity.Employee;
import com.example.nto.service.EmployeeService; import com.example.nto.service.EmployeeService;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -21,12 +22,28 @@ public class EmployeeController {
} }
@GetMapping("/auth") // Проверка аутентификации @GetMapping("/auth") // Проверка аутентификации
public ResponseEntity<?> authenticate() { public ResponseEntity<?> authenticate(@RequestHeader("Authorization") String authHeader) {
// Проверяем заголовок
if (authHeader == null || !authHeader.startsWith("Basic ")) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Missing or invalid Authorization header");
}
return ResponseEntity.ok("Authenticated successfully"); // Получение логина и пароля
String[] credentials = new String(java.util.Base64.getDecoder().decode(authHeader.substring(6))).split(":");
String login = credentials[0];
String password = credentials.length > 1 ? credentials[1] : "";
Optional<Employee> employee = employeeService.findByLogin(login);
if (employee.isPresent() && employee.get().getPassword().equals(password)) {
return ResponseEntity.ok("Authenticated successfully");
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid login or password");
} }
@PreAuthorize("isAuthenticated()") // Убедитесь, что пользователь аутентифицирован
@GetMapping("/{login}/info") // Получение информации о сотруднике @GetMapping("/{login}/info") // Получение информации о сотруднике
public ResponseEntity<?> getInfo(@PathVariable String login) { public ResponseEntity<?> getInfo(@PathVariable String login) {
Optional<Employee> employee = employeeService.findByLogin(login); Optional<Employee> employee = employeeService.findByLogin(login);
@ -37,6 +54,7 @@ public class EmployeeController {
} }
} }
@PreAuthorize("isAuthenticated()") // Убедитесь, что пользователь аутентифицирован
@PatchMapping("/{login}/open") // Открыть дверь @PatchMapping("/{login}/open") // Открыть дверь
public ResponseEntity<?> openDoor(@PathVariable String login, @RequestBody Map<String, Long> payload) { public ResponseEntity<?> openDoor(@PathVariable String login, @RequestBody Map<String, Long> payload) {
Long code = payload.get("value"); Long code = payload.get("value");
@ -56,7 +74,8 @@ public class EmployeeController {
} }
} }
@GetMapping("/workers") // Получить всех сотрудников @PreAuthorize("hasRole('admin')") // Проверьте, что пользователь имеет роль admin
@GetMapping("/workers")
public ResponseEntity<List<Employee>> getAllWorkers() { public ResponseEntity<List<Employee>> getAllWorkers() {
List<Employee> allEmployees = employeeService.findAll(); // Получить всех сотрудников List<Employee> allEmployees = employeeService.findAll(); // Получить всех сотрудников
return ResponseEntity.ok(allEmployees); return ResponseEntity.ok(allEmployees);

View File

@ -1,5 +1,10 @@
package com.example.nto.entity; package com.example.nto.entity;
import javax.persistence.*;
import java.io.Serializable;
import javax.persistence.*; import javax.persistence.*;
import lombok.*; import lombok.*;
@ -13,9 +18,9 @@ public class Code {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
private long value; private long value;
}
// made by truettwo
}

View File

@ -4,4 +4,5 @@ import com.example.nto.entity.Code;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
public interface CodeRepository extends JpaRepository<Code, Long> { public interface CodeRepository extends JpaRepository<Code, Long> {
}
}

View File

@ -1,6 +1,7 @@
package com.example.nto.service.impl; package com.example.nto.service.impl;
import com.example.nto.entity.Employee; import com.example.nto.entity.Employee;
import com.example.nto.repository.CodeRepository; // Импортируйте нужный репозиторий
import com.example.nto.repository.EmployeeRepository; import com.example.nto.repository.EmployeeRepository;
import com.example.nto.service.EmployeeService; import com.example.nto.service.EmployeeService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -8,15 +9,16 @@ import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.stereotype.Service;
import java.util.List;
@Service @Service
public class EmployeeServiceImpl implements EmployeeService { public class EmployeeServiceImpl implements EmployeeService {
private final EmployeeRepository employeeRepository;
public EmployeeServiceImpl(EmployeeRepository employeeRepository) { private final EmployeeRepository employeeRepository;
private final CodeRepository codeRepository; // Добавьте CodeRepository как зависимость
// Конструктор с внедрением
public EmployeeServiceImpl(EmployeeRepository employeeRepository, CodeRepository codeRepository) {
this.employeeRepository = employeeRepository; this.employeeRepository = employeeRepository;
this.codeRepository = codeRepository; // Инициируем код репозиторий
} }
@Override @Override
@ -31,7 +33,9 @@ public class EmployeeServiceImpl implements EmployeeService {
@Override @Override
public boolean validateCode(String login, long code) { public boolean validateCode(String login, long code) {
// Реализация проверки кода // Получаем все коды из репозитория
return false; return codeRepository.findAll()
.stream()
.anyMatch(c -> c.getValue() == code); // Проверяем, есть ли код
} }
} }