wuchimedes | e5722e3 | 2025-04-13 17:38:50 +0800 | [diff] [blame] | 1 | package com.example.g8backend.controller; |
| 2 | |
| 3 | import org.springframework.beans.factory.annotation.Autowired; |
| 4 | import org.springframework.http.ResponseEntity; |
| 5 | import org.springframework.security.core.Authentication; |
| 6 | import org.springframework.security.core.context.SecurityContextHolder; |
| 7 | import org.springframework.web.bind.annotation.*; |
| 8 | import com.example.g8backend.entity.Post; |
| 9 | import com.example.g8backend.service.IPostService; |
| 10 | |
| 11 | import java.util.List; |
| 12 | |
| 13 | @RestController |
| 14 | @RequestMapping("/post") |
| 15 | public class PostController { |
| 16 | @Autowired |
| 17 | private IPostService postService; |
| 18 | |
| 19 | @PostMapping("") |
| 20 | public ResponseEntity<?> createPost(@RequestBody Post post) { |
| 21 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| 22 | long userId = (long) authentication.getPrincipal(); |
| 23 | post.setUserId(userId); |
| 24 | postService.save(post); |
| 25 | return ResponseEntity.ok().build(); |
| 26 | } |
| 27 | |
| 28 | @GetMapping("/{postId}") |
| 29 | public Post getPost(@PathVariable("postId") Long postId) { |
| 30 | return postService.getById(postId); |
| 31 | } |
| 32 | |
| 33 | @DeleteMapping("/{postId}") |
| 34 | public ResponseEntity<?> deletePost(@PathVariable("postId") Long postId) { |
| 35 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| 36 | long userId = (long) authentication.getPrincipal(); |
| 37 | Post post = postService.getById(postId); |
| 38 | if (post == null) { |
| 39 | return ResponseEntity.status(500).body("Post not found."); |
| 40 | } |
| 41 | if (post.getUserId()!= userId) { |
| 42 | return ResponseEntity.status(403).body("You are not authorized to delete this post."); |
| 43 | } |
| 44 | postService.removeById(postId); |
| 45 | return ResponseEntity.ok().body("Post deleted successfully."); |
| 46 | } |
| 47 | |
| 48 | @GetMapping("/getAll") |
| 49 | public List<Post> getAllPosts() { |
| 50 | return postService.list(); |
| 51 | } |
| 52 | |
| 53 | @GetMapping("/getByUserId/{userId}") |
| 54 | public List<Post> getPostsByUserId(@PathVariable("userId") Long userId) { |
| 55 | return postService.getPostsByUserId(userId); |
| 56 | } |
| 57 | } |