blob: 7b7b7c7142aa50d858bd58693ae8101bd2dbb09a [file] [log] [blame]
wuchimedese5722e32025-04-13 17:38:50 +08001package com.example.g8backend.controller;
2
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.http.ResponseEntity;
5import org.springframework.security.core.Authentication;
6import org.springframework.security.core.context.SecurityContextHolder;
7import org.springframework.web.bind.annotation.*;
8import com.example.g8backend.entity.Post;
9import com.example.g8backend.service.IPostService;
10
11import java.util.List;
12
13@RestController
14@RequestMapping("/post")
15public 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}