This commit is contained in:
Justiks 2025-02-20 16:08:18 +03:00
parent 6fe46ab346
commit a62b4fc966
5 changed files with 67 additions and 47 deletions

27
.idea/workspace.xml generated
View File

@ -4,11 +4,12 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="067ac1f0-be04-4fe4-85c6-f870334053b8" name="Changes" comment="add endpoints"> <list default="true" id="067ac1f0-be04-4fe4-85c6-f870334053b8" name="Changes" comment="basic auth :pig:">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pom.xml" beforeDir="false" afterPath="$PROJECT_DIR$/pom.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/AdminController.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/AdminController.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/AuthController.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/AuthController.java" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/AuthController.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/AuthController.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/com/example/nto/websecurity/WebSecurityConfig.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/com/example/nto/websecurity/WebSecurityConfig.java" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/EmployeeController.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/com/example/nto/controller/EmployeeController.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/com/example/nto/entity/Entry.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/com/example/nto/entity/Entry.java" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -39,6 +40,7 @@
"keyToString": { "keyToString": {
"Application.App.executor": "Run", "Application.App.executor": "Run",
"Maven.NTO-2024 [org.apache.maven.plugins:maven-clean-plugin:3.1.0:clean].executor": "Run", "Maven.NTO-2024 [org.apache.maven.plugins:maven-clean-plugin:3.1.0:clean].executor": "Run",
"Maven.NTO-2024 [org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile].executor": "Run",
"RunOnceActivity.ShowReadmeOnStart": "true", "RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.git.unshallow": "true", "RunOnceActivity.git.unshallow": "true",
"git-widget-placeholder": "main", "git-widget-placeholder": "main",
@ -191,7 +193,15 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1740049179417</updated> <updated>1740049179417</updated>
</task> </task>
<option name="localTasksCounter" value="13" /> <task id="LOCAL-00013" summary="basic auth :pig:">
<option name="closed" value="true" />
<created>1740052413527</created>
<option name="number" value="00013" />
<option name="presentableId" value="LOCAL-00013" />
<option name="project" value="LOCAL" />
<updated>1740052413527</updated>
</task>
<option name="localTasksCounter" value="14" />
<servers /> <servers />
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
@ -207,7 +217,8 @@
<MESSAGE value="add Entiries table and bugfix" /> <MESSAGE value="add Entiries table and bugfix" />
<MESSAGE value="bugfix" /> <MESSAGE value="bugfix" />
<MESSAGE value="add endpoints" /> <MESSAGE value="add endpoints" />
<option name="LAST_COMMIT_MESSAGE" value="add endpoints" /> <MESSAGE value="basic auth :pig:" />
<option name="LAST_COMMIT_MESSAGE" value="basic auth :pig:" />
</component> </component>
<component name="XDebuggerManager"> <component name="XDebuggerManager">
<breakpoint-manager> <breakpoint-manager>
@ -219,17 +230,17 @@
</line-breakpoint> </line-breakpoint>
<line-breakpoint enabled="true" type="java-line"> <line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/com/example/nto/controller/AdminController.java</url> <url>file://$PROJECT_DIR$/src/main/java/com/example/nto/controller/AdminController.java</url>
<line>128</line> <line>124</line>
<option name="timeStamp" value="42" /> <option name="timeStamp" value="42" />
</line-breakpoint> </line-breakpoint>
<line-breakpoint enabled="true" type="java-line"> <line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/com/example/nto/controller/EmployeeController.java</url> <url>file://$PROJECT_DIR$/src/main/java/com/example/nto/controller/EmployeeController.java</url>
<line>95</line> <line>96</line>
<option name="timeStamp" value="43" /> <option name="timeStamp" value="43" />
</line-breakpoint> </line-breakpoint>
<line-breakpoint enabled="true" type="java-line"> <line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/com/example/nto/controller/EmployeeController.java</url> <url>file://$PROJECT_DIR$/src/main/java/com/example/nto/controller/EmployeeController.java</url>
<line>82</line> <line>83</line>
<option name="timeStamp" value="44" /> <option name="timeStamp" value="44" />
</line-breakpoint> </line-breakpoint>
</breakpoints> </breakpoints>

View File

@ -7,13 +7,12 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed; import javax.annotation.security.RolesAllowed;
import java.util.List; import java.util.List;
@Controller @RestController
@RequestMapping("/api/admin/") @RequestMapping("/api/admin/")
public class AdminController { public class AdminController {
@ -107,20 +106,17 @@ public class AdminController {
* Такой же метод, как и getEmployeeInfo, только для админов по логину * Такой же метод, как и getEmployeeInfo, только для админов по логину
* @return * @return
*/ */
@RolesAllowed("ADMIN")
@GetMapping("/{value}/info") @GetMapping("/{value}/info")
public Employee getEmployeeInfoAdmin(@PathVariable String value) { public Employee getEmployeeInfoAdmin(@PathVariable String value) {
return employeeService.getEmployeeInfoById(Long.parseLong(value)); return employeeService.getEmployeeInfoById(Long.parseLong(value));
} }
@RolesAllowed("ADMIN")
@DeleteMapping("/employee/delete/") @DeleteMapping("/employee/delete/")
public ResponseEntity<String> deleteEmployee(@RequestBody DeleteEmployeeRequest deleteEmployeeRequest) { public ResponseEntity<String> deleteEmployee(@RequestBody DeleteEmployeeRequest deleteEmployeeRequest) {
employeeService.deleteEmployee(deleteEmployeeRequest.id); employeeService.deleteEmployee(deleteEmployeeRequest.id);
return ResponseEntity.status(HttpStatus.OK).build(); return ResponseEntity.status(HttpStatus.OK).build();
} }
@RolesAllowed("ADMIN")
@PutMapping("/employee/update/login/") @PutMapping("/employee/update/login/")
public ResponseEntity<String> updateEmployeeLogin(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) { public ResponseEntity<String> updateEmployeeLogin(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) {
@ -130,27 +126,23 @@ public class AdminController {
return ResponseEntity.status(HttpStatus.OK).build(); return ResponseEntity.status(HttpStatus.OK).build();
} }
@RolesAllowed("ADMIN")
@PutMapping("/employee/update/avatar/") @PutMapping("/employee/update/avatar/")
public ResponseEntity<String> updateEmployeeAvatar(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) { public ResponseEntity<String> updateEmployeeAvatar(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) {
employeeService.updateEmployeeAvatar(updateEmployeeRequest.id, updateEmployeeRequest.field); employeeService.updateEmployeeAvatar(updateEmployeeRequest.id, updateEmployeeRequest.field);
return ResponseEntity.status(HttpStatus.OK).build(); return ResponseEntity.status(HttpStatus.OK).build();
} }
@RolesAllowed("ADMIN")
@PutMapping("/employee/update/position/") @PutMapping("/employee/update/position/")
public ResponseEntity<String> updatePosition(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) { public ResponseEntity<String> updatePosition(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) {
employeeService.updateEmployeePosition(updateEmployeeRequest.id, updateEmployeeRequest.field); employeeService.updateEmployeePosition(updateEmployeeRequest.id, updateEmployeeRequest.field);
return ResponseEntity.status(HttpStatus.OK).build(); return ResponseEntity.status(HttpStatus.OK).build();
} }
@RolesAllowed("ADMIN")
@GetMapping("/employee/info/{id}/") @GetMapping("/employee/info/{id}/")
public Employee getInfo(@PathVariable Long id) { public Employee getInfo(@PathVariable Long id) {
return employeeService.getEmployeeInfoById(id); return employeeService.getEmployeeInfoById(id);
} }
@RolesAllowed("ADMIN")
@GetMapping("/employee/info/all/") @GetMapping("/employee/info/all/")
public List<Employee> getEmployees() { public List<Employee> getEmployees() {
return employeeService.getEmployees(); return employeeService.getEmployees();

View File

@ -3,7 +3,10 @@ package com.example.nto.controller;
import com.example.nto.entity.Employee; import com.example.nto.entity.Employee;
import com.example.nto.repository.EmployeeRepository; import com.example.nto.repository.EmployeeRepository;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@ -11,6 +14,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -21,15 +25,18 @@ import java.util.List;
@RestController @RestController
public class AuthController { public class AuthController {
class RoleResponse { @Autowired
private String role; private PasswordEncoder passwordEncoder;
public String getRole() { class RoleResponse {
return role; private boolean isAdmin;
public boolean isAdmin() {
return isAdmin;
} }
public void setRole(String role) { public void setAdmin(boolean admin) {
this.role = role; isAdmin = admin;
} }
} }
@ -39,6 +46,7 @@ public class AuthController {
@AllArgsConstructor @AllArgsConstructor
private static class LoginBody { private static class LoginBody {
private String login; private String login;
private String password;
public String getLogin() { public String getLogin() {
return login; return login;
@ -47,6 +55,14 @@ public class AuthController {
public void setLogin(String login) { public void setLogin(String login) {
this.login = login; this.login = login;
} }
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} }
@ -57,11 +73,11 @@ public class AuthController {
Эндпоинт авторизации, кинь сюда логин и пароль, и возможно я дам тебе возможность авторизоваться. Эндпоинт авторизации, кинь сюда логин и пароль, и возможно я дам тебе возможность авторизоваться.
*/ */
@PostMapping("/api/login/") @PostMapping("/api/login/")
private RoleResponse login(HttpServletRequest request, @RequestBody LoginBody loginBody) { //, @RequestParam String login, @RequestParam String password) { private ResponseEntity<?> login(HttpServletRequest request, @RequestBody LoginBody loginBody) { //, @RequestParam String login, @RequestParam String password) {
Employee employee = employeeRepository.getByLogin(loginBody.login).get(); Employee employee = employeeRepository.getByLogin(loginBody.login).get();
RoleResponse response = new RoleResponse(); RoleResponse response = new RoleResponse();
response.setRole(employee.getRole()); response.setAdmin(employee.getRole().equals("ADMIN"));
return response; return new ResponseEntity<>(response, HttpStatus.OK);
} }
} }

View File

@ -31,25 +31,26 @@ public class EmployeeController {
this.entryRepository = entryRepository; this.entryRepository = entryRepository;
} }
/** // Был вырезан коллективным решением
* Эндпоинт для проверки присутствия логина в емплоеееее таблице // /**
* // * Эндпоинт для проверки присутствия логина в емплоеееее таблице
* @return статус код, смотри документацию к тз // *
*/ // * @return статус код, смотри документацию к тз
@GetMapping("/api/{login}/auth") // */
public ResponseEntity<String> authAttempt(@PathVariable String login) { // @GetMapping("/api/{login}/auth")
try { // public ResponseEntity<String> authAttempt(@PathVariable String login) {
if (employeeService.checkEmployeeExists(login)) { // try {
return ResponseEntity.status(HttpStatus.ACCEPTED).build(); // Логин найден ДВЕСТИ // if (employeeService.checkEmployeeExists(login)) {
} // return ResponseEntity.status(HttpStatus.OK).build(); // Логин найден ДВЕСТИ
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // Логин не найден 401 неавторизован // }
// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // Логин не найден 401 неавторизован
} catch ( //
Exception e) // Я понял статус "что-то пошло не так", как то, что произошла какая-то ошибка. Вообще по идее должен быть статус 500, но допустим // } catch (
{ // Exception e) // Я понял статус "что-то пошло не так", как то, что произошла какая-то ошибка. Вообще по идее должен быть статус 500, но допустим
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); // {
} // return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
} // }
// }
/** /**
* Получить информацию по емплоеееее * Получить информацию по емплоеееее
@ -90,7 +91,7 @@ public class EmployeeController {
entry.setTime(LocalDateTime.now()); entry.setTime(LocalDateTime.now());
entry.setPlace(codeRepository.findByValue(value)); entry.setPlace(codeRepository.findByValue(value));
entryRepository.save(entry); entryRepository.save(entry);
return ResponseEntity.status(HttpStatus.ACCEPTED).build(); return ResponseEntity.status(HttpStatus.OK).build();
} catch (Exception e) { } catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();

View File

@ -19,7 +19,7 @@ public class Entry {
@JsonIdentityReference(alwaysAsId = true) @JsonIdentityReference(alwaysAsId = true)
private Employee employee; private Employee employee;
private LocalDateTime time; private LocalDateTime time ;
@ManyToOne @ManyToOne