BlogRestController.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package es.uv.garcosda.endpoints;
  2. import java.util.Optional;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.domain.Page;
  7. import org.springframework.http.HttpStatus;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.security.access.prepost.PostAuthorize;
  10. import org.springframework.security.access.prepost.PreAuthorize;
  11. import org.springframework.web.bind.annotation.DeleteMapping;
  12. import org.springframework.web.bind.annotation.GetMapping;
  13. import org.springframework.web.bind.annotation.PathVariable;
  14. import org.springframework.web.bind.annotation.PostMapping;
  15. import org.springframework.web.bind.annotation.RequestBody;
  16. import org.springframework.web.bind.annotation.RequestMapping;
  17. import org.springframework.web.bind.annotation.RestController;
  18. import es.uv.garcosda.domain.Post;
  19. import es.uv.garcosda.models.PostsRequestDTO;
  20. import es.uv.garcosda.models.PostsResponseDTO;
  21. import es.uv.garcosda.services.BlogService;
  22. @RestController
  23. @RequestMapping("/api/v1")
  24. public class BlogRestController {
  25. private final static Logger LOGGER = LoggerFactory.getLogger(BlogRestController.class);
  26. @Autowired private BlogService blogService;
  27. @GetMapping("posts")
  28. @PreAuthorize("permitAll")
  29. public PostsResponseDTO findPosts(@RequestBody PostsRequestDTO request) {
  30. LOGGER.debug("View all posts");
  31. Page<Post> pageData = blogService.findPosts(request);
  32. PostsResponseDTO postsResponse = new PostsResponseDTO(pageData);
  33. return postsResponse;
  34. }
  35. @GetMapping("posts/{id}")
  36. @PreAuthorize("isAuthenticated() and #postId < 10")
  37. @PostAuthorize("returnObject.isPresent() and returnObject.get().id >= 1")
  38. public Optional<Post> findPostById(@PathVariable("id") Integer id) {
  39. LOGGER.debug("View Post id: "+id);
  40. Optional<Post> post = blogService.findPostById(id);
  41. return post;
  42. }
  43. @PostMapping("posts")
  44. @PreAuthorize("hasRole('ADMIN') OR hasRole('USER')")
  45. public ResponseEntity<Post> createPost(@RequestBody Post post) {
  46. LOGGER.debug("Create post");
  47. Post createdPost = blogService.createPost(post);
  48. return new ResponseEntity<>(createdPost, HttpStatus.OK);
  49. }
  50. @DeleteMapping("posts/{id}")
  51. @PreAuthorize("hasRole('ADMIN')")
  52. public void deletePostById(@PathVariable("id") Integer id) {
  53. LOGGER.debug("Delete Post id: "+id);
  54. blogService.deletePost(id);
  55. }
  56. }