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" />
</component>
<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$/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/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>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -39,6 +40,7 @@
"keyToString": {
"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-compiler-plugin:3.8.1:compile].executor": "Run",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.git.unshallow": "true",
"git-widget-placeholder": "main",
@ -191,7 +193,15 @@
<option name="project" value="LOCAL" />
<updated>1740049179417</updated>
</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 />
</component>
<component name="VcsManagerConfiguration">
@ -207,7 +217,8 @@
<MESSAGE value="add Entiries table and bugfix" />
<MESSAGE value="bugfix" />
<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 name="XDebuggerManager">
<breakpoint-manager>
@ -219,17 +230,17 @@
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<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" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<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" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<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" />
</line-breakpoint>
</breakpoints>

View File

@ -7,13 +7,12 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import java.util.List;
@Controller
@RestController
@RequestMapping("/api/admin/")
public class AdminController {
@ -107,20 +106,17 @@ public class AdminController {
* Такой же метод, как и getEmployeeInfo, только для админов по логину
* @return
*/
@RolesAllowed("ADMIN")
@GetMapping("/{value}/info")
public Employee getEmployeeInfoAdmin(@PathVariable String value) {
return employeeService.getEmployeeInfoById(Long.parseLong(value));
}
@RolesAllowed("ADMIN")
@DeleteMapping("/employee/delete/")
public ResponseEntity<String> deleteEmployee(@RequestBody DeleteEmployeeRequest deleteEmployeeRequest) {
employeeService.deleteEmployee(deleteEmployeeRequest.id);
return ResponseEntity.status(HttpStatus.OK).build();
}
@RolesAllowed("ADMIN")
@PutMapping("/employee/update/login/")
public ResponseEntity<String> updateEmployeeLogin(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) {
@ -130,27 +126,23 @@ public class AdminController {
return ResponseEntity.status(HttpStatus.OK).build();
}
@RolesAllowed("ADMIN")
@PutMapping("/employee/update/avatar/")
public ResponseEntity<String> updateEmployeeAvatar(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) {
employeeService.updateEmployeeAvatar(updateEmployeeRequest.id, updateEmployeeRequest.field);
return ResponseEntity.status(HttpStatus.OK).build();
}
@RolesAllowed("ADMIN")
@PutMapping("/employee/update/position/")
public ResponseEntity<String> updatePosition(@RequestBody UpdateEmployeeRequest updateEmployeeRequest) {
employeeService.updateEmployeePosition(updateEmployeeRequest.id, updateEmployeeRequest.field);
return ResponseEntity.status(HttpStatus.OK).build();
}
@RolesAllowed("ADMIN")
@GetMapping("/employee/info/{id}/")
public Employee getInfo(@PathVariable Long id) {
return employeeService.getEmployeeInfoById(id);
}
@RolesAllowed("ADMIN")
@GetMapping("/employee/info/all/")
public List<Employee> 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.repository.EmployeeRepository;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
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.UsernamePasswordAuthenticationToken;
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.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@ -21,15 +25,18 @@ import java.util.List;
@RestController
public class AuthController {
class RoleResponse {
private String role;
@Autowired
private PasswordEncoder passwordEncoder;
public String getRole() {
return role;
class RoleResponse {
private boolean isAdmin;
public boolean isAdmin() {
return isAdmin;
}
public void setRole(String role) {
this.role = role;
public void setAdmin(boolean admin) {
isAdmin = admin;
}
}
@ -39,6 +46,7 @@ public class AuthController {
@AllArgsConstructor
private static class LoginBody {
private String login;
private String password;
public String getLogin() {
return login;
@ -47,6 +55,14 @@ public class AuthController {
public void setLogin(String 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/")
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();
RoleResponse response = new RoleResponse();
response.setRole(employee.getRole());
return response;
response.setAdmin(employee.getRole().equals("ADMIN"));
return new ResponseEntity<>(response, HttpStatus.OK);
}
}

View File

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

View File

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