| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package it.bgates.remotebe.controller;
- import it.bgates.remotebe.config.BGatesUserDetails;
- import it.bgates.remotebe.controller.auth.beans.NewUserBean;
- import it.bgates.remotebe.entities.User;
- import it.bgates.remotebe.exception.PermissionDeniedException;
- import it.bgates.remotebe.exception.UserNotFoundException;
- import it.bgates.remotebe.service.UserService;
- import it.bgates.remotebe.service.auth.AuthService;
- import jakarta.validation.Valid;
- import lombok.RequiredArgsConstructor;
- import org.springframework.http.ResponseEntity;
- import org.springframework.web.bind.annotation.*;
- import java.security.Principal;
- import java.util.List;
- import static org.springframework.http.HttpStatus.*;
- @RestController
- @RequiredArgsConstructor
- @RequestMapping("/users")
- public class UserController {
- private final AuthService authService;
- private final UserService userService;
- /***
- *
- * @param principal
- * @return return the user information for the currently logged user
- */
- @GetMapping("/current-user")
- public ResponseEntity<BGatesUserDetails> getCurrentUser(Principal principal) {
- BGatesUserDetails user = authService.getCurrentUser();
- return ResponseEntity
- .status(OK)
- .body(user);
- }
- @GetMapping("")
- public ResponseEntity<List<User>> getUsers(Principal principal) {
- try {
- List<User> users = userService.getUsers(principal);
- return ResponseEntity
- .status(OK)
- .body(users);
- } catch (UserNotFoundException e) {
- return ResponseEntity.status(PRECONDITION_FAILED).build();
- }
- }
- @PostMapping("")
- public ResponseEntity<User> saveUser(@Valid @RequestBody NewUserBean newUser, Principal principal) {
- if (newUser.getId() == null && !userService.canCreateUsers(principal)) {
- return ResponseEntity.status(FORBIDDEN).build();
- }
- try {
- User savedUser = userService.save(newUser, principal);
- return ResponseEntity
- .status(OK)
- .body(savedUser);
- } catch (PermissionDeniedException e) {
- return ResponseEntity.status(FORBIDDEN).build();
- } catch (UserNotFoundException e) {
- return ResponseEntity.status(PRECONDITION_FAILED).build();
- }
- }
- @PostMapping("disable/{id}")
- public ResponseEntity<Boolean> disableUser(@PathVariable() Integer id, Principal principal) {
- Boolean result = null;
- try {
- result = userService.disableUser(id, principal);
- return ResponseEntity
- .status(OK)
- .body(result);
- } catch (UserNotFoundException e) {
- return ResponseEntity.status(PRECONDITION_FAILED).build();
- } catch (PermissionDeniedException e) {
- return ResponseEntity.status(FORBIDDEN).build();
- }
- }
- }
|