package es.uv.garcosda.endpoints; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import es.uv.garcosda.domain.Post; import es.uv.garcosda.models.PostsRequestDTO; import es.uv.garcosda.models.PostsResponseDTO; import es.uv.garcosda.services.BlogService; @RestController @RequestMapping("/api/v1") public class BlogRestController { private final static Logger LOGGER = LoggerFactory.getLogger(BlogRestController.class); @Autowired private BlogService blogService; @GetMapping("posts") @PreAuthorize("permitAll") public PostsResponseDTO findPosts(@RequestBody PostsRequestDTO request) { LOGGER.debug("View all posts"); Page pageData = blogService.findPosts(request); PostsResponseDTO postsResponse = new PostsResponseDTO(pageData); return postsResponse; } @GetMapping("posts/{id}") @PreAuthorize("isAuthenticated() and #postId < 10") @PostAuthorize("returnObject.isPresent() and returnObject.get().id >= 1") public Optional findPostById(@PathVariable("id") Integer id) { LOGGER.debug("View Post id: "+id); Optional post = blogService.findPostById(id); return post; } @PostMapping("posts") @PreAuthorize("hasRole('ADMIN') OR hasRole('USER')") public ResponseEntity createPost(@RequestBody Post post) { LOGGER.debug("Create post"); Post createdPost = blogService.createPost(post); return new ResponseEntity<>(createdPost, HttpStatus.OK); } @DeleteMapping("posts/{id}") @PreAuthorize("hasRole('ADMIN')") public void deletePostById(@PathVariable("id") Integer id) { LOGGER.debug("Delete Post id: "+id); blogService.deletePost(id); } }