blob: 3b9ec22fb4e91a19b8893cf5b6ac8e43aec951a5 [file] [log] [blame]
wuchimedesa1bf2782025-03-27 15:08:54 +08001package com.example.g8backend.controller;
2
3import com.example.g8backend.entity.User;
4import com.example.g8backend.service.IUserService;
5import org.springframework.beans.factory.annotation.Autowired;
wuchimedes223bfab2025-04-04 17:16:05 +08006import org.springframework.http.ResponseEntity;
7import org.springframework.security.core.Authentication;
8import org.springframework.security.core.context.SecurityContextHolder;
wuchimedesa1bf2782025-03-27 15:08:54 +08009import org.springframework.web.bind.annotation.*;
10
夜雨声烦7e6eb382025-04-22 01:18:00 +080011import java.util.Map;
12
wuchimedesa1bf2782025-03-27 15:08:54 +080013@RestController
wuchimedes223bfab2025-04-04 17:16:05 +080014@RequestMapping("/user")
wuchimedesa1bf2782025-03-27 15:08:54 +080015public class UserController {
16
17 @Autowired
18 private IUserService userService;
19
wuchimedes223bfab2025-04-04 17:16:05 +080020 // 获取已登录的用户信息
wuchimedesa1bf2782025-03-27 15:08:54 +080021 @GetMapping
wuchimedes223bfab2025-04-04 17:16:05 +080022 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);
wuchimedesa1bf2782025-03-27 15:08:54 +080028 }
夜雨声烦7e6eb382025-04-22 01:18:00 +080029 @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 }
wuchimedesa1bf2782025-03-27 15:08:54 +080046}