wuchimedes | a1bf278 | 2025-03-27 15:08:54 +0800 | [diff] [blame] | 1 | package com.example.g8backend.controller; |
| 2 | |
| 3 | import com.example.g8backend.entity.User; |
| 4 | import com.example.g8backend.service.IUserService; |
| 5 | import org.springframework.beans.factory.annotation.Autowired; |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 6 | import org.springframework.http.ResponseEntity; |
| 7 | import org.springframework.security.core.Authentication; |
| 8 | import org.springframework.security.core.context.SecurityContextHolder; |
wuchimedes | a1bf278 | 2025-03-27 15:08:54 +0800 | [diff] [blame] | 9 | import org.springframework.web.bind.annotation.*; |
| 10 | |
夜雨声烦 | 7e6eb38 | 2025-04-22 01:18:00 +0800 | [diff] [blame^] | 11 | import java.util.Map; |
| 12 | |
wuchimedes | a1bf278 | 2025-03-27 15:08:54 +0800 | [diff] [blame] | 13 | @RestController |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 14 | @RequestMapping("/user") |
wuchimedes | a1bf278 | 2025-03-27 15:08:54 +0800 | [diff] [blame] | 15 | public class UserController { |
| 16 | |
| 17 | @Autowired |
| 18 | private IUserService userService; |
| 19 | |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 20 | // 获取已登录的用户信息 |
wuchimedes | a1bf278 | 2025-03-27 15:08:54 +0800 | [diff] [blame] | 21 | @GetMapping |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 22 | public ResponseEntity<?> getUserInfo(){ |
| 23 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| 24 | long userId = (long) authentication.getPrincipal(); |
| 25 | User user = userService.getById(userId); |
| 26 | user.setPassword(null); |
| 27 | return ResponseEntity.ok(user); |
wuchimedes | a1bf278 | 2025-03-27 15:08:54 +0800 | [diff] [blame] | 28 | } |
夜雨声烦 | 7e6eb38 | 2025-04-22 01:18:00 +0800 | [diff] [blame^] | 29 | @PostMapping("/follow/{userId}") |
| 30 | public ResponseEntity<?> followUser(@PathVariable Long userId) { |
| 31 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); |
| 32 | Long followerId = (Long) auth.getPrincipal(); // 确保Security返回Long |
| 33 | return ResponseEntity.ok(userService.followUser(followerId, userId)); |
| 34 | } |
| 35 | |
| 36 | @PostMapping("/message/{receiverId}") |
| 37 | public ResponseEntity<?> sendMessage( |
| 38 | @PathVariable Long receiverId, |
| 39 | @RequestBody String content |
| 40 | ) { |
| 41 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); |
| 42 | Long senderId = (Long) auth.getPrincipal(); |
| 43 | Long messageId = userService.sendMessage(senderId, receiverId, content); |
| 44 | return ResponseEntity.ok(Map.of("messageId", messageId)); |
| 45 | } |
wuchimedes | a1bf278 | 2025-03-27 15:08:54 +0800 | [diff] [blame] | 46 | } |