refactor: 统一ID类型为Long并优化代码安全性和性能
修复用户删除接口的ID类型从Integer改为Long 移除未使用的Bouncy Castle依赖 添加dompurify依赖增强XSS防护 修复SQL表定义中的bigintBIGINT语法错误 优化图片预览接口的安全检查和错误处理 添加Vditor渲染引擎预加载和图片懒加载 统一分组和文件接口的ID类型为Long 增强前端用户状态管理,添加token过期检查 优化Markdown内容渲染流程和图片URL处理
This commit is contained in:
@@ -126,13 +126,6 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<!-- Bouncy Castle 加密库 -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.76</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -84,4 +84,16 @@ public class GlobalExceptionHandler {
|
||||
log.error("Unexpected error at {} - Error type: {}", request.getRequestURI(), e.getClass().getSimpleName());
|
||||
return R.fail(ResultCode.FAILED.getCode(), "系统繁忙,请稍后再试");
|
||||
}
|
||||
|
||||
// 修复:处理 IllegalStateException(getWriter() 已调用等问题)
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public R<Void> handleIllegalStateException(IllegalStateException e, HttpServletRequest request) {
|
||||
log.warn("Illegal state at {}: {}", request.getRequestURI(), e.getMessage());
|
||||
// 如果是图片预览相关请求,可能是响应已经提交
|
||||
if (request.getRequestURI().contains("/api/images/preview")) {
|
||||
// 响应可能已经提交,直接返回 null,避免再次写入响应
|
||||
return null;
|
||||
}
|
||||
return R.fail(ResultCode.FAILED.getCode(), "请求处理失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,11 +52,9 @@ public class GroupingController {
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@PutMapping("/{id}")
|
||||
public R<Grouping> updateGrouping(
|
||||
@PathVariable String id,
|
||||
@PathVariable Long id,
|
||||
@RequestBody Grouping grouping) {
|
||||
|
||||
long l = Long.parseLong(id);
|
||||
grouping.setId(l);
|
||||
grouping.setId(id);
|
||||
Grouping updated = groupingService.updateGrouping(grouping);
|
||||
return R.success(updated);
|
||||
}
|
||||
@@ -64,9 +62,8 @@ public class GroupingController {
|
||||
@Operation(summary = "删除分组")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@DeleteMapping("/{id}")
|
||||
public R<Void> deleteGrouping(@PathVariable String id) {
|
||||
Long idLong = Long.parseLong(id);
|
||||
groupingService.deleteGrouping(idLong);
|
||||
public R<Void> deleteGrouping(@PathVariable Long id) {
|
||||
groupingService.deleteGrouping(id);
|
||||
return R.success();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,43 +81,48 @@ public class ImageController {
|
||||
@Operation(summary = "在线预览", description = "浏览器直接打开文件流")
|
||||
@GetMapping("/preview/{url}")
|
||||
public void preview(@PathVariable String url, HttpServletResponse resp) throws IOException {
|
||||
// 修复:使用 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());
|
||||
}
|
||||
// 注意:不能同时调用 resp.getWriter() 和 resp.getOutputStream()
|
||||
|
||||
if (StrUtil.isBlank(url)) {
|
||||
resp.setStatus(404);
|
||||
resp.setContentType("application/json;charset=UTF-8");
|
||||
resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
String sanitizedUrl = sanitizeFileName(url);
|
||||
if (sanitizedUrl == null) {
|
||||
resp.setStatus(403);
|
||||
resp.setContentType("application/json;charset=UTF-8");
|
||||
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.setContentType("application/json;charset=UTF-8");
|
||||
resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
File file = filePath.toFile();
|
||||
if (!file.exists() || !file.isFile()) {
|
||||
resp.setStatus(404);
|
||||
resp.setContentType("application/json;charset=UTF-8");
|
||||
resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
String contentTypeFromFileExtension = getContentTypeFromFileExtension(url);
|
||||
resp.setContentType(contentTypeFromFileExtension);
|
||||
resp.setContentLengthLong(file.length());
|
||||
// 文件流直接输出,不使用 try-with-resources 包装整个方法
|
||||
try (FileInputStream in = new FileInputStream(file)) {
|
||||
StreamUtils.copy(in, resp.getOutputStream());
|
||||
resp.getOutputStream().flush();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +130,9 @@ public class ImageController {
|
||||
if (StrUtil.isBlank(fileName)) {
|
||||
return null;
|
||||
}
|
||||
if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\") || fileName.contains(":")) {
|
||||
// 修复:使用白名单验证文件名格式(只允许 UUID 格式)
|
||||
// 例如:550e8400-e29b-41d4-a716-446655440000.jpg
|
||||
if (!fileName.matches("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\\.[a-zA-Z0-9]+$")) {
|
||||
return null;
|
||||
}
|
||||
return fileName;
|
||||
@@ -162,6 +169,7 @@ public class ImageController {
|
||||
}
|
||||
|
||||
String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
|
||||
// 使用更安全的 MIME 类型映射,只允许图片类型
|
||||
switch (extension) {
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
@@ -177,8 +185,27 @@ public class ImageController {
|
||||
case "svg":
|
||||
return "image/svg+xml";
|
||||
default:
|
||||
// 对于未知的扩展名,返回通用的二进制流类型,避免执行风险
|
||||
return "application/octet-stream";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证文件是否为允许的图片类型
|
||||
* @param contentType 文件内容类型
|
||||
* @return 是否允许
|
||||
*/
|
||||
private boolean isAllowedImageType(String contentType) {
|
||||
if (StrUtil.isBlank(contentType)) {
|
||||
return false;
|
||||
}
|
||||
// 只允许标准的图片 MIME 类型
|
||||
return contentType.equals("image/jpeg") ||
|
||||
contentType.equals("image/png") ||
|
||||
contentType.equals("image/gif") ||
|
||||
contentType.equals("image/bmp") ||
|
||||
contentType.equals("image/webp") ||
|
||||
contentType.equals("image/svg+xml");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ public class MarkdownController {
|
||||
|
||||
@Operation(summary = "根据分组ID获取Markdown文件")
|
||||
@GetMapping("/grouping/{groupingId}")
|
||||
public R<List<MarkdownFileVO>> getFilesByGroupingId(@PathVariable String groupingId) {
|
||||
public R<List<MarkdownFileVO>> getFilesByGroupingId(@PathVariable Long groupingId) {
|
||||
List<MarkdownFileVO> files = markdownFileService.getFilesByGroupingId(groupingId);
|
||||
return R.success(files);
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ public class UserController {
|
||||
return R.fail("无法获取用户信息,删除失败");
|
||||
}
|
||||
|
||||
userService.deleteUser(user.getId().intValue());
|
||||
userService.deleteUser(user.getId());
|
||||
return R.success("用户删除成功");
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ public interface MarkdownFileMapper extends BaseMapper<MarkdownFile> {
|
||||
"LEFT JOIN `grouping` g ON mf.grouping_id = g.id " +
|
||||
"WHERE mf.grouping_id = #{groupingId} AND mf.is_deleted = 0 " +
|
||||
"ORDER BY mf.updated_at DESC")
|
||||
List<MarkdownFileVO> selectByGroupingIdWithGrouping(@Param("groupingId") String groupingId);
|
||||
List<MarkdownFileVO> selectByGroupingIdWithGrouping(@Param("groupingId") Long groupingId);
|
||||
|
||||
/**
|
||||
* 查询已删除的笔记(不包含content大字段)
|
||||
|
||||
@@ -28,7 +28,7 @@ public interface MarkdownFileService extends IService<MarkdownFile> {
|
||||
* @param groupingId 分组ID
|
||||
* @return 文件列表
|
||||
*/
|
||||
List<MarkdownFileVO> getFilesByGroupingId(String groupingId);
|
||||
List<MarkdownFileVO> getFilesByGroupingId(Long groupingId);
|
||||
|
||||
/**
|
||||
* 删除Markdown文件
|
||||
|
||||
@@ -27,7 +27,7 @@ public interface UserService extends IService<User> {
|
||||
* 用户删除
|
||||
* @param id 用户id
|
||||
*/
|
||||
void deleteUser(Integer id);
|
||||
void deleteUser(Long id);
|
||||
|
||||
/**
|
||||
* 查询用户token是否过期
|
||||
|
||||
@@ -40,11 +40,15 @@ public class GroupingServiceImpl
|
||||
|
||||
@Override
|
||||
public List<Grouping> getAllGroupings(Long parentId) {
|
||||
if (ObjectUtil.isNull(parentId)){
|
||||
return groupingMapper.selectList(null);
|
||||
LambdaQueryWrapper<Grouping> queryWrapper = new LambdaQueryWrapper<>();
|
||||
// 只查询未删除的分组
|
||||
queryWrapper.eq(Grouping::getIsDeleted, 0);
|
||||
if (ObjectUtil.isNotNull(parentId)){
|
||||
queryWrapper.eq(Grouping::getParentId, parentId);
|
||||
}
|
||||
return groupingMapper.selectList(new LambdaQueryWrapper<Grouping>()
|
||||
.eq(Grouping::getParentId, parentId));
|
||||
// 限制最大返回数量,防止内存溢出
|
||||
queryWrapper.last("LIMIT 1000");
|
||||
return groupingMapper.selectList(queryWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -103,6 +103,7 @@ public class ImageServiceImpl
|
||||
Image image = new Image();
|
||||
image.setOriginalName(originalFilename);
|
||||
image.setStoredName(storedName);
|
||||
// 返回相对路径,前端会根据环境自动拼接 baseURL
|
||||
image.setUrl("/api/images/preview/" + storedName);
|
||||
image.setSize(file.getSize());
|
||||
image.setContentType(contentType);
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.test.bijihoudaun.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
@@ -105,7 +106,7 @@ public class MarkdownFileServiceImpl
|
||||
|
||||
|
||||
@Override
|
||||
public List<MarkdownFileVO> getFilesByGroupingId(String groupingId) {
|
||||
public List<MarkdownFileVO> getFilesByGroupingId(Long groupingId) {
|
||||
return markdownFileMapper.selectByGroupingIdWithGrouping(groupingId);
|
||||
}
|
||||
|
||||
@@ -130,13 +131,12 @@ public class MarkdownFileServiceImpl
|
||||
|
||||
@Override
|
||||
public List<MarkdownFile> searchByTitle(String keyword) {
|
||||
// 修复:转义特殊字符防止 SQL 注入
|
||||
// 修复:使用 LambdaQueryWrapper 避免 SQL 注入风险
|
||||
if (keyword == null || keyword.trim().isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
String escapedKeyword = keyword.replace("%", "\\%").replace("_", "\\_");
|
||||
QueryWrapper<MarkdownFile> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.like("title", escapedKeyword);
|
||||
LambdaQueryWrapper<MarkdownFile> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.like(MarkdownFile::getTitle, keyword);
|
||||
return this.list(queryWrapper);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import com.test.bijihoudaun.service.UserService;
|
||||
import com.test.bijihoudaun.util.JwtTokenUtil;
|
||||
import com.test.bijihoudaun.util.LoginLockUtil;
|
||||
import com.test.bijihoudaun.util.PasswordUtils;
|
||||
import com.test.bijihoudaun.util.UuidV7;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
@@ -126,7 +125,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteUser(Integer id) {
|
||||
public void deleteUser(Long id) {
|
||||
userMapper.deleteById(id);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 服务器配置
|
||||
server:
|
||||
port: 8084
|
||||
forward-headers-strategy: framework
|
||||
|
||||
spring:
|
||||
web:
|
||||
@@ -12,13 +12,16 @@ spring:
|
||||
active: dev
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 10MB # ???????5MB
|
||||
max-request-size: 10MB # ???????5MB
|
||||
max-file-size: 10MB
|
||||
max-request-size: 10MB
|
||||
|
||||
# 文件上传路径
|
||||
file:
|
||||
upload-dir: uploads
|
||||
|
||||
|
||||
#??
|
||||
# 内存保护阈值 (MB)
|
||||
memory:
|
||||
threshold: 100
|
||||
|
||||
|
||||
## Snowflake ID?????
|
||||
@@ -29,11 +32,20 @@ worker:
|
||||
datacenter:
|
||||
id: 1
|
||||
|
||||
|
||||
|
||||
# JWT 配置
|
||||
jwt:
|
||||
secret: ${JWT_SECRET:V2VsbCwgSSBzdXBwb3NlIHRoYXQgaWYgeW91J3JlIHJlYWRpbmcgdGhpcywgeW91J3JlIHByZXR0eSBjdXJpb3VzLg==}
|
||||
expiration: 86400
|
||||
header: Authorization
|
||||
tokenHead: "Bearer "
|
||||
|
||||
# 管理员用户名配置
|
||||
admin:
|
||||
username: ${ADMIN_USERNAME:admin}
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
level:
|
||||
com.test.bijihoudaun: INFO
|
||||
pattern:
|
||||
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
|
||||
|
||||
Reference in New Issue
Block a user