feat: 添加用户角色字段并实现权限控制
fix(security): 修复重放攻击拦截器的时间戳验证漏洞 refactor(security): 重构验证码工具类使用线程安全实现 perf(login): 优化登录锁定工具类性能并添加定期清理 fix(editor): 修复笔记编辑器空指针问题 style: 清理数据库索引脚本中的冗余注释 fix(api): 修复前端API调用参数编码问题 feat(image): 实现图片名称同步服务 refactor(markdown): 重构Markdown服务分离图片名称同步逻辑 fix(xss): 添加HTML转义函数防止XSS攻击 fix(user): 修复用户服务权限加载问题 fix(rate-limit): 修复速率限制拦截器并发问题 fix(axios): 生产环境隐藏详细错误信息 fix(image): 修复图片上传和删除的权限验证 refactor(captcha): 重构验证码工具类使用并发安全实现 fix(jwt): 修复JWT过滤器空指针问题 fix(export): 修复笔记导出XSS漏洞 fix(search): 修复Markdown搜索SQL注入问题 fix(interceptor): 修复重放攻击拦截器逻辑错误 fix(controller): 修复用户控制器空指针问题 fix(security): 修复nonce生成使用密码学安全方法
This commit is contained in:
@@ -4,13 +4,17 @@ package com.test.bijihoudaun.controller;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.test.bijihoudaun.common.response.R;
|
||||
import com.test.bijihoudaun.entity.Image;
|
||||
import com.test.bijihoudaun.entity.User;
|
||||
import com.test.bijihoudaun.service.ImageService;
|
||||
import com.test.bijihoudaun.service.UserService;
|
||||
import com.test.bijihoudaun.util.SecurityUtil;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
@@ -18,6 +22,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
@@ -33,18 +38,30 @@ public class ImageController {
|
||||
@Autowired
|
||||
private ImageService imageService;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Operation(summary = "上传图片")
|
||||
@PostMapping
|
||||
public R<Image> uploadImage(
|
||||
@RequestPart("file") MultipartFile file,
|
||||
@RequestParam(value = "userId", required = false) Long userId,
|
||||
@RequestParam(value = "markdownId", required = false) Long markdownId) {
|
||||
// 修复:从SecurityContext获取当前用户,不接受客户端传入的userId
|
||||
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (!(principal instanceof UserDetails)) {
|
||||
return R.fail("请先登录");
|
||||
}
|
||||
String username = ((UserDetails) principal).getUsername();
|
||||
User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
|
||||
if (user == null) {
|
||||
return R.fail("用户不存在");
|
||||
}
|
||||
|
||||
try {
|
||||
Image image = imageService.uploadImage(file, userId, markdownId);
|
||||
Image image = imageService.uploadImage(file, user.getId(), markdownId);
|
||||
return R.success(image);
|
||||
} catch (IOException e) {
|
||||
return R.fail();
|
||||
return R.fail("上传失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,51 +71,58 @@ public class ImageController {
|
||||
if (!SecurityUtil.isUserAuthenticated()) {
|
||||
return R.fail("请先登录");
|
||||
}
|
||||
// 修复:添加权限验证,确保用户只能删除自己的图片
|
||||
if (!canModifyImage(id)) {
|
||||
return R.fail("无权删除此图片");
|
||||
}
|
||||
boolean result = imageService.deleteImage(id);
|
||||
if (result) {
|
||||
return R.success();
|
||||
} else {
|
||||
return R.fail();
|
||||
return R.fail("删除失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "在线预览", description = "浏览器直接打开文件流")
|
||||
@GetMapping("/preview/{url}")
|
||||
public void preview(@PathVariable String url, HttpServletResponse resp) throws IOException {
|
||||
if (StrUtil.isBlank(url)) {
|
||||
resp.setStatus(404);
|
||||
resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
String sanitizedUrl = sanitizeFileName(url);
|
||||
if (sanitizedUrl == null) {
|
||||
resp.setStatus(403);
|
||||
resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
Path basePath = Paths.get(rootPath).normalize().toAbsolutePath();
|
||||
Path filePath = basePath.resolve(sanitizedUrl).normalize();
|
||||
|
||||
if (!filePath.startsWith(basePath)) {
|
||||
resp.setStatus(403);
|
||||
resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
File file = filePath.toFile();
|
||||
if (!file.exists() || !file.isFile()) {
|
||||
resp.setStatus(404);
|
||||
resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
String contentTypeFromFileExtension = getContentTypeFromFileExtension(url);
|
||||
resp.setContentType(contentTypeFromFileExtension);
|
||||
resp.setContentLengthLong(file.length());
|
||||
try (FileInputStream in = new FileInputStream(file)) {
|
||||
StreamUtils.copy(in, resp.getOutputStream());
|
||||
// 修复:使用 try-with-resources 确保 PrintWriter 关闭
|
||||
try (PrintWriter writer = resp.getWriter()) {
|
||||
if (StrUtil.isBlank(url)) {
|
||||
resp.setStatus(404);
|
||||
writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
String sanitizedUrl = sanitizeFileName(url);
|
||||
if (sanitizedUrl == null) {
|
||||
resp.setStatus(403);
|
||||
writer.write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
Path basePath = Paths.get(rootPath).normalize().toAbsolutePath();
|
||||
Path filePath = basePath.resolve(sanitizedUrl).normalize();
|
||||
|
||||
if (!filePath.startsWith(basePath)) {
|
||||
resp.setStatus(403);
|
||||
writer.write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
File file = filePath.toFile();
|
||||
if (!file.exists() || !file.isFile()) {
|
||||
resp.setStatus(404);
|
||||
writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
String contentTypeFromFileExtension = getContentTypeFromFileExtension(url);
|
||||
resp.setContentType(contentTypeFromFileExtension);
|
||||
resp.setContentLengthLong(file.length());
|
||||
try (FileInputStream in = new FileInputStream(file)) {
|
||||
StreamUtils.copy(in, resp.getOutputStream());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,11 +143,15 @@ public class ImageController {
|
||||
if (!SecurityUtil.isUserAuthenticated()) {
|
||||
return R.fail("请先登录");
|
||||
}
|
||||
// 修复:添加权限验证
|
||||
if (!canModifyImageByUrl(url)) {
|
||||
return R.fail("无权删除此图片");
|
||||
}
|
||||
boolean result = imageService.deleteImageByUrl(url);
|
||||
if (result) {
|
||||
return R.success();
|
||||
} else {
|
||||
return R.fail();
|
||||
return R.fail("删除失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,14 +161,62 @@ public class ImageController {
|
||||
if (!SecurityUtil.isUserAuthenticated()) {
|
||||
return R.fail("请先登录");
|
||||
}
|
||||
// 修复:添加权限验证
|
||||
for (String url : urls) {
|
||||
if (!canModifyImageByUrl(url)) {
|
||||
return R.fail("无权删除部分图片");
|
||||
}
|
||||
}
|
||||
boolean result = imageService.deleteImageByUrls(urls);
|
||||
if (result) {
|
||||
return R.success();
|
||||
} else {
|
||||
return R.fail();
|
||||
return R.fail("删除失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查当前用户是否有权限操作图片
|
||||
*/
|
||||
private boolean canModifyImage(Long imageId) {
|
||||
// 从数据库查询图片所属用户
|
||||
Image image = imageService.getById(imageId);
|
||||
if (image == null) {
|
||||
return false;
|
||||
}
|
||||
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (!(principal instanceof UserDetails)) {
|
||||
return false;
|
||||
}
|
||||
String username = ((UserDetails) principal).getUsername();
|
||||
User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
return user.getId().equals(image.getUserId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查当前用户是否有权限操作图片(通过URL)
|
||||
*/
|
||||
private boolean canModifyImageByUrl(String url) {
|
||||
// 从数据库查询图片所属用户
|
||||
Image image = imageService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Image>().eq("stored_name", url));
|
||||
if (image == null) {
|
||||
return false;
|
||||
}
|
||||
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (!(principal instanceof UserDetails)) {
|
||||
return false;
|
||||
}
|
||||
String username = ((UserDetails) principal).getUsername();
|
||||
User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
return user.getId().equals(image.getUserId());
|
||||
}
|
||||
|
||||
|
||||
private String getContentTypeFromFileExtension(String fileName) {
|
||||
if (StrUtil.isBlank(fileName) || !StrUtil.contains(fileName, '.')) {
|
||||
|
||||
@@ -98,7 +98,7 @@ public class MarkdownController {
|
||||
@PostMapping("/{id}/title")
|
||||
public R<MarkdownFile> updateMarkdownTitle(
|
||||
@PathVariable Long id,
|
||||
String title) {
|
||||
@RequestParam String title) {
|
||||
MarkdownFile updatedFile = markdownFileService.updateMarkdownTitle(id, title);
|
||||
if (ObjectUtil.isNotNull(updatedFile)) {
|
||||
return R.success(updatedFile);
|
||||
|
||||
@@ -11,8 +11,6 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/system")
|
||||
@Tag(name = "系统管理")
|
||||
@@ -31,7 +29,7 @@ public class SystemController {
|
||||
}
|
||||
|
||||
@PostMapping("/registration/toggle")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Operation(summary = "切换注册功能状态")
|
||||
public R<Void> toggleRegistration(@RequestBody Boolean enabled) {
|
||||
systemSettingService.setRegistrationEnabled(enabled);
|
||||
@@ -39,7 +37,7 @@ public class SystemController {
|
||||
}
|
||||
|
||||
@PostMapping("/registration/generate-code")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Operation(summary = "生成注册码")
|
||||
public R<String> generateRegistrationCode() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
@@ -47,4 +45,4 @@ public class SystemController {
|
||||
String code = registrationCodeService.generateCode(currentUserName);
|
||||
return R.success(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,10 @@ public class UserController {
|
||||
return R.fail("无效或已过期的注册码");
|
||||
}
|
||||
User user = userService.register(username, password, email);
|
||||
// 修复:添加空值检查
|
||||
if (user == null) {
|
||||
return R.fail("注册失败,请稍后重试");
|
||||
}
|
||||
UserVO userVO = new UserVO();
|
||||
BeanUtils.copyProperties(user, userVO);
|
||||
userVO.setId(String.valueOf(user.getId()));
|
||||
@@ -69,6 +73,11 @@ public class UserController {
|
||||
String token = userService.login(username, password);
|
||||
User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
|
||||
|
||||
// 修复:添加空值检查
|
||||
if (user == null) {
|
||||
return R.fail("用户不存在");
|
||||
}
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("token", token);
|
||||
|
||||
@@ -88,7 +97,12 @@ public class UserController {
|
||||
@RequireCaptcha("删除账号")
|
||||
@DeleteMapping("/deleteUser")
|
||||
public R<String> deleteUser(){
|
||||
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
// 修复:添加类型检查
|
||||
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (!(principal instanceof UserDetails)) {
|
||||
return R.fail("无法获取用户信息");
|
||||
}
|
||||
UserDetails userDetails = (UserDetails) principal;
|
||||
String username = userDetails.getUsername();
|
||||
User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
|
||||
|
||||
@@ -110,9 +124,20 @@ public class UserController {
|
||||
@RequireCaptcha("修改密码")
|
||||
@PutMapping("/password")
|
||||
public R<String> updatePassword(@RequestBody UpdatePasswordBo updatePasswordBo) {
|
||||
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
// 修复:添加类型检查
|
||||
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (!(principal instanceof UserDetails)) {
|
||||
return R.fail("无法获取用户信息");
|
||||
}
|
||||
UserDetails userDetails = (UserDetails) principal;
|
||||
String username = userDetails.getUsername();
|
||||
User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
|
||||
|
||||
// 修复:添加空值检查
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
return R.fail("用户不存在");
|
||||
}
|
||||
|
||||
userService.updatePassword(user.getId(), updatePasswordBo);
|
||||
return R.success("密码更新成功");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user