UsersController.java

  1. package edu.ucsb.cs156.example.controllers;

  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;

  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.security.access.prepost.PreAuthorize;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;

  10. import edu.ucsb.cs156.example.entities.User;
  11. import edu.ucsb.cs156.example.repositories.UserRepository;
  12. import io.swagger.v3.oas.annotations.Operation;
  13. import io.swagger.v3.oas.annotations.tags.Tag;

  14. /**
  15.  * This is a REST controller for getting information about the users.
  16.  *
  17.  * These endpoints are only accessible to users with the role "ROLE_ADMIN".
  18.  */

  19. @Tag(name="User information (admin only)")
  20. @RequestMapping("/api/admin/users")
  21. @RestController
  22. public class UsersController extends ApiController {
  23.     @Autowired
  24.     UserRepository userRepository;

  25.     @Autowired
  26.     ObjectMapper mapper;

  27.     /**
  28.      * This method returns a list of all users.  Accessible only to users with the role "ROLE_ADMIN".
  29.      * @return a list of all users
  30.      * @throws JsonProcessingException if there is an error processing the JSON
  31.      */
  32.     @Operation(summary= "Get a list of all users")
  33.     @PreAuthorize("hasRole('ROLE_ADMIN')")
  34.     @GetMapping("")
  35.     public ResponseEntity<String> users()
  36.             throws JsonProcessingException {
  37.         Iterable<User> users = userRepository.findAll();
  38.         String body = mapper.writeValueAsString(users);
  39.         return ResponseEntity.ok().body(body);
  40.     }
  41. }