| package com.example.g8backend.controller; |
| |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.http.ResponseEntity; |
| import org.springframework.security.core.Authentication; |
| import org.springframework.security.core.context.SecurityContextHolder; |
| import org.springframework.web.bind.annotation.*; |
| import com.example.g8backend.entity.Post; |
| import com.example.g8backend.service.IPostService; |
| |
| import java.util.List; |
| |
| @RestController |
| @RequestMapping("/post") |
| public class PostController { |
| @Autowired |
| private IPostService postService; |
| |
| @PostMapping("") |
| public ResponseEntity<?> createPost(@RequestBody Post post) { |
| Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| long userId = (long) authentication.getPrincipal(); |
| post.setUserId(userId); |
| postService.save(post); |
| return ResponseEntity.ok().build(); |
| } |
| |
| @GetMapping("/{postId}") |
| public Post getPost(@PathVariable("postId") Long postId) { |
| return postService.getById(postId); |
| } |
| |
| @DeleteMapping("/{postId}") |
| public ResponseEntity<?> deletePost(@PathVariable("postId") Long postId) { |
| Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| long userId = (long) authentication.getPrincipal(); |
| Post post = postService.getById(postId); |
| if (post == null) { |
| return ResponseEntity.status(500).body("Post not found."); |
| } |
| if (post.getUserId()!= userId) { |
| return ResponseEntity.status(403).body("You are not authorized to delete this post."); |
| } |
| postService.removeById(postId); |
| return ResponseEntity.ok().body("Post deleted successfully."); |
| } |
| |
| @GetMapping("/getAll") |
| public List<Post> getAllPosts() { |
| return postService.list(); |
| } |
| |
| @GetMapping("/getByUserId/{userId}") |
| public List<Post> getPostsByUserId(@PathVariable("userId") Long userId) { |
| return postService.getPostsByUserId(userId); |
| } |
| } |