blob: 3b9ec22fb4e91a19b8893cf5b6ac8e43aec951a5 [file] [log] [blame]
package com.example.g8backend.controller;
import com.example.g8backend.entity.User;
import com.example.g8backend.service.IUserService;
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 java.util.Map;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
// 获取已登录的用户信息
@GetMapping
public ResponseEntity<?> getUserInfo(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
long userId = (long) authentication.getPrincipal();
User user = userService.getById(userId);
user.setPassword(null);
return ResponseEntity.ok(user);
}
@PostMapping("/follow/{userId}")
public ResponseEntity<?> followUser(@PathVariable Long userId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Long followerId = (Long) auth.getPrincipal(); // 确保Security返回Long
return ResponseEntity.ok(userService.followUser(followerId, userId));
}
@PostMapping("/message/{receiverId}")
public ResponseEntity<?> sendMessage(
@PathVariable Long receiverId,
@RequestBody String content
) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Long senderId = (Long) auth.getPrincipal();
Long messageId = userService.sendMessage(senderId, receiverId, content);
return ResponseEntity.ok(Map.of("messageId", messageId));
}
}