81 lines
2.6 KiB
Java
81 lines
2.6 KiB
Java
package com.bruce.sams.controller.sys;
|
||
|
||
import com.bruce.sams.common.utils.FileUploadUtil;
|
||
import com.bruce.sams.domain.entity.AjaxResult;
|
||
import com.bruce.sams.domain.sys.User;
|
||
import com.bruce.sams.service.UserService;
|
||
import org.springframework.beans.factory.annotation.Autowired;
|
||
import org.springframework.security.core.Authentication;
|
||
import org.springframework.security.core.context.SecurityContextHolder;
|
||
import org.springframework.web.bind.annotation.*;
|
||
import org.springframework.web.multipart.MultipartFile;
|
||
|
||
import java.util.Map;
|
||
|
||
|
||
/**
|
||
* 用户端 - 个人信息管理控制器
|
||
*/
|
||
@RestController
|
||
@RequestMapping("/api/user")
|
||
public class UserController {
|
||
|
||
@Autowired
|
||
private UserService userService;
|
||
|
||
/**
|
||
* 获取当前用户个人信息(前端调用 /user/profile,无需传 userId)
|
||
*/
|
||
@GetMapping("/profile")
|
||
public AjaxResult getUserProfile() {
|
||
System.out.println("运行中");
|
||
User user = getCurrentUser();
|
||
return AjaxResult.success(userService.getUserProfile(user.getUserId()));
|
||
}
|
||
|
||
/**
|
||
* 修改个人资料(昵称、邮箱、头像)=> PUT /user/update
|
||
*/
|
||
@PutMapping("/update")
|
||
public AjaxResult updateProfile(@RequestBody User updatedUser) {
|
||
User user = getCurrentUser();
|
||
userService.updateProfile(user.getUserId(), updatedUser);
|
||
return AjaxResult.success("个人信息更新成功");
|
||
}
|
||
|
||
/**
|
||
* 修改密码 => PUT /user/change-password
|
||
*/
|
||
@PutMapping("/change-password")
|
||
public AjaxResult changePassword(@RequestBody Map<String, String> body) {
|
||
User user = getCurrentUser();
|
||
String oldPassword = body.get("oldPassword");
|
||
String newPassword = body.get("newPassword");
|
||
userService.changePassword(user.getUserId(), oldPassword, newPassword);
|
||
return AjaxResult.success("密码修改成功");
|
||
}
|
||
|
||
/**
|
||
* 上传头像 => POST /user/avatar
|
||
*/
|
||
@PostMapping("/avatar")
|
||
public String uploadAvatar(@RequestParam("file") MultipartFile file) {
|
||
User user = getCurrentUser();
|
||
String avatarUrl = FileUploadUtil.uploadFile(file, "avatars/");
|
||
userService.updateUserAvatar(user.getUserId(), avatarUrl);
|
||
return avatarUrl;
|
||
}
|
||
|
||
/**
|
||
* 获取当前登录用户
|
||
*/
|
||
private User getCurrentUser() {
|
||
System.out.println("✔ Controller 已进入!");
|
||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||
if (authentication == null || !authentication.isAuthenticated()) {
|
||
throw new RuntimeException("用户未认证");
|
||
}
|
||
return (User) authentication.getPrincipal();
|
||
}
|
||
}
|