feat(user): 添加更新用户名功能并优化安全配置

- 在 ErrorCode 中新增 USER_UPDATE_USERNAME_FAILED 错误码
- JwtAuthenticationTokenFilter 中增加当前用户名属性设置
- RestAuthenticationEntryPoint 返回状态码改为 403 并更新错误信息
- 新增 UpdateUsernameRequest DTO 用于接收用户名更新请求
- UserController 添加 updateUsername 接口支持修改用户名
- UserInfoService 和其实现类中增加 updateUsername 方法逻辑
- 引入 tokenHead 配置项以支持 JWT 相关操作
This commit is contained in:
Chaos
2025-11-18 22:32:51 +08:00
parent 7e754b19d4
commit 7dc0d26d9b
7 changed files with 56 additions and 8 deletions

View File

@@ -59,7 +59,7 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
log.info("authorities: {}", authorities);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(username, null, authorities);
request.setAttribute("currentUsername", username);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}

View File

@@ -18,7 +18,7 @@ public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
ApiResult<Object> result = ApiResult.failed("未授权");
ApiResult<Object> result = ApiResult.failed(403,"权限不足");
String string = JSONObject.toJSONString(result);
response.getWriter().print(string);

View File

@@ -2,16 +2,15 @@ package cn.nopj.chaos_api.controller;
import cn.nopj.chaos_api.dto.request.SetUserPasswordRequest;
import cn.nopj.chaos_api.dto.request.UpdateUsernameRequest;
import cn.nopj.chaos_api.dto.response.UserinfoResponse;
import cn.nopj.chaos_api.model.ApiResult;
import cn.nopj.chaos_api.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -26,7 +25,8 @@ import java.util.List;
public class UserController {
@Autowired
UserInfoService userInfoService;
@Value("${jwt.tokenHead}")
private String tokenHead;
/**
* 获取所有用户信息
@@ -49,4 +49,15 @@ public class UserController {
userInfoService.setUserPassword(request.getUserId(), request.getPassword());
return ApiResult.success("用户密码修改成功");
}
/**
* 更新用户名
* @return 更新后用户名
* @deprecated 废弃 修改用户名之后token会失效
*/
@PostMapping("/updateUsername")
ApiResult<String> updateUsername(@RequestAttribute("currentUsername") String username,@RequestBody UpdateUsernameRequest request){
userInfoService.updateUsername(username, request.getUsername());
return ApiResult.success("用户名更新成功");
}
}