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,18 +81,20 @@ 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()) {
|
||||
// 注意:不能同时调用 resp.getWriter() 和 resp.getOutputStream()
|
||||
|
||||
if (StrUtil.isBlank(url)) {
|
||||
resp.setStatus(404);
|
||||
writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
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);
|
||||
writer.write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
resp.setContentType("application/json;charset=UTF-8");
|
||||
resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -101,23 +103,26 @@ public class ImageController {
|
||||
|
||||
if (!filePath.startsWith(basePath)) {
|
||||
resp.setStatus(403);
|
||||
writer.write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
|
||||
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);
|
||||
writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
|
||||
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"
|
||||
|
||||
28
biji-qianduan/package-lock.json
generated
28
biji-qianduan/package-lock.json
generated
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@kangc/v-md-editor": "^2.2.4",
|
||||
"codemirror": "^6.0.1",
|
||||
"dompurify": "^3.3.1",
|
||||
"element-plus": "^2.7.6",
|
||||
"highlight.js": "^11.11.1",
|
||||
"html2canvas": "^1.4.1",
|
||||
@@ -2585,10 +2586,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.1.6",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz",
|
||||
"integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)"
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.1.tgz",
|
||||
"integrity": "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/element-plus": {
|
||||
"version": "2.10.4",
|
||||
@@ -3414,16 +3418,6 @@
|
||||
"html2canvas": "^1.0.0-rc.5"
|
||||
}
|
||||
},
|
||||
"node_modules/jspdf/node_modules/dompurify": {
|
||||
"version": "3.2.6",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.6.tgz",
|
||||
"integrity": "sha512-/2GogDQlohXPZe6D6NOgQvXLPSYBqIWMnZ8zzOhn09REE4eyAzb+Hed3jhoM9OkuaJ8P6ZGTTVWQKAi8ieIzfQ==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optional": true,
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/katex": {
|
||||
"version": "0.13.24",
|
||||
"resolved": "https://registry.npmjs.org/katex/-/katex-0.13.24.tgz",
|
||||
@@ -3705,6 +3699,12 @@
|
||||
"web-worker": "^1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mermaid/node_modules/dompurify": {
|
||||
"version": "3.1.6",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz",
|
||||
"integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)"
|
||||
},
|
||||
"node_modules/mermaid/node_modules/katex": {
|
||||
"version": "0.16.22",
|
||||
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.22.tgz",
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"dependencies": {
|
||||
"@kangc/v-md-editor": "^2.2.4",
|
||||
"codemirror": "^6.0.1",
|
||||
"dompurify": "^3.3.1",
|
||||
"element-plus": "^2.7.6",
|
||||
"highlight.js": "^11.11.1",
|
||||
"html2canvas": "^1.4.1",
|
||||
@@ -24,7 +25,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.0.5",
|
||||
"vite": "^5.3.1",
|
||||
"terser": "^5.31.3"
|
||||
"terser": "^5.31.3",
|
||||
"vite": "^5.3.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ import axiosApi from '@/utils/axios.js'
|
||||
|
||||
|
||||
|
||||
// 修复:使用 encodeURIComponent 编码 URL 参数,防止注入
|
||||
export const groupingId = (data) => axiosApi.get(`/api/markdown/grouping/${encodeURIComponent(data)}`)
|
||||
// 根据分组ID获取Markdown文件列表
|
||||
export const groupingId = (groupingId) => axiosApi.get(`/api/markdown/grouping/${encodeURIComponent(groupingId)}`)
|
||||
// 获取所有分组
|
||||
export const groupingAll = (data) => {
|
||||
if (data) {
|
||||
@@ -71,16 +71,17 @@ export const register = (data) => {
|
||||
const formData = new FormData()
|
||||
formData.append('username', data.username)
|
||||
formData.append('password', data.password)
|
||||
formData.append('email', data.email || '') // 修复:添加 email 参数
|
||||
formData.append('registrationCode', data.registrationCode)
|
||||
return axiosApi.post('/api/user/register', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
// 更新分组名称
|
||||
// 修复:使用与后端 Grouping 实体类匹配的字段名
|
||||
export const updateGroupingName = (id, newName) => {
|
||||
return axiosApi.put(`/api/groupings/${id}`, { grouping: newName });
|
||||
}
|
||||
@@ -106,20 +107,6 @@ export const getRecentFiles = (limit = 16) => axiosApi.get(`/api/markdown/recent
|
||||
|
||||
|
||||
|
||||
// MD5哈希
|
||||
export const MD5 = (data, file) => {
|
||||
const formData = new FormData()
|
||||
if (data) formData.append('input', data)
|
||||
if (file) formData.append('file', file)
|
||||
return axiosApi.post('/api/common/md5', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -130,11 +130,12 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref, nextTick, watch, computed, onBeforeUnmount } from 'vue';
|
||||
import { onMounted, ref, nextTick, watch, computed, onBeforeUnmount, watchEffect, provide } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import Vditor from 'vditor';
|
||||
import 'vditor/dist/index.css';
|
||||
import { escapeHtml } from '@/utils/security';
|
||||
import DOMPurify from 'dompurify';
|
||||
import {
|
||||
groupingAll,
|
||||
markdownList,
|
||||
@@ -197,6 +198,11 @@ const showSystemSettingsDialog = ref(false);
|
||||
const showUpdatePasswordDialog = ref(false);
|
||||
const showPrivacyDialog = ref(false);
|
||||
|
||||
// Vditor 渲染引擎就绪状态
|
||||
const vditorReady = ref(false);
|
||||
// 提供给子组件使用
|
||||
provide('vditorReady', vditorReady);
|
||||
|
||||
// Data for dialogs
|
||||
const itemToRename = ref(null);
|
||||
const fileToImport = ref(null);
|
||||
@@ -369,8 +375,10 @@ const previewFile = async (file) => {
|
||||
selectedFile.value = null;
|
||||
return;
|
||||
}
|
||||
// 重置渲染缓存,确保每次打开笔记都重新渲染
|
||||
lastRenderedKey = null;
|
||||
// 先立即显示预览页(加载状态),让用户感知到响应
|
||||
selectedFile.value = { ...file, content: '', isLoading: true };
|
||||
selectedFile.value = { ...file, content: '', isLoading: true, isRendering: false };
|
||||
showEditor.value = false;
|
||||
|
||||
// 异步加载内容
|
||||
@@ -378,7 +386,9 @@ const previewFile = async (file) => {
|
||||
const content = await Preview(file.id) || '';
|
||||
// 内容加载完成后更新
|
||||
if (selectedFile.value && selectedFile.value.id === file.id) {
|
||||
selectedFile.value = { ...file, content, isLoading: false };
|
||||
// 如果 Vditor 渲染引擎未就绪,显示渲染中状态
|
||||
const isRendering = !vditorReady.value;
|
||||
selectedFile.value = { ...file, content, isLoading: false, isRendering };
|
||||
}
|
||||
} catch (error) {
|
||||
// 错误已在 axios 拦截器中显示,这里不再重复显示
|
||||
@@ -507,9 +517,13 @@ const handleExport = async (format) => {
|
||||
const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
|
||||
downloadBlob(blob, `${title}.md`);
|
||||
} else if (format === 'html') {
|
||||
// 修复:对title进行HTML转义,防止XSS
|
||||
// 修复:对title进行HTML转义,使用DOMPurify清理内容防止XSS
|
||||
const escapedTitle = escapeHtml(title);
|
||||
const fullHtml = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${escapedTitle}</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.1.0/github-markdown.min.css"><style>body{box-sizing:border-box;min-width:200px;max-width:980px;margin:0 auto;padding:45px;}</style></head><body class="markdown-body"><h1>${escapedTitle}</h1>${previewElement.innerHTML}</body></html>`;
|
||||
const sanitizedContent = DOMPurify.sanitize(previewElement.innerHTML, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'code', 'pre', 'ul', 'ol', 'li', 'blockquote', 'img', 'br', 'hr', 'table', 'thead', 'tbody', 'tr', 'th', 'td'],
|
||||
ALLOWED_ATTR: ['href', 'title', 'class', 'src', 'alt', 'width', 'height']
|
||||
});
|
||||
const fullHtml = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${escapedTitle}</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.1.0/github-markdown.min.css"><style>body{box-sizing:border-box;min-width:200px;max-width:980px;margin:0 auto;padding:45px;}</style></head><body class="markdown-body"><h1>${escapedTitle}</h1>${sanitizedContent}</body></html>`;
|
||||
const blob = new Blob([fullHtml], { type: 'text/html;charset=utf-8' });
|
||||
downloadBlob(blob, `${escapedTitle}.html`);
|
||||
} else if (format === 'pdf') {
|
||||
@@ -555,8 +569,33 @@ onMounted(async () => {
|
||||
await fetchGroupings();
|
||||
await resetToHomeView();
|
||||
window.addEventListener('resize', handleResize);
|
||||
|
||||
// 预加载 Vditor 渲染引擎(lute.min.js),避免第一次点击笔记时等待下载
|
||||
preloadVditor();
|
||||
});
|
||||
|
||||
// 预加载 Vditor 渲染引擎
|
||||
const preloadVditor = () => {
|
||||
// 创建一个隐藏的容器用于预加载
|
||||
const preloadContainer = document.createElement('div');
|
||||
preloadContainer.style.cssText = 'position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;';
|
||||
document.body.appendChild(preloadContainer);
|
||||
|
||||
// 调用 Vditor.preview 会触发 lute.min.js 的下载
|
||||
Vditor.preview(preloadContainer, '# 预加载', {
|
||||
mode: 'light',
|
||||
after: () => {
|
||||
// 渲染引擎加载完成
|
||||
vditorReady.value = true;
|
||||
// 清理预加载容器
|
||||
if (preloadContainer.parentNode) {
|
||||
preloadContainer.parentNode.removeChild(preloadContainer);
|
||||
}
|
||||
console.log('Vditor 渲染引擎已就绪');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('resize', handleResize);
|
||||
});
|
||||
@@ -571,26 +610,91 @@ const handleResize = () => {
|
||||
// Vditor 渲染优化
|
||||
let lastRenderedKey = null;
|
||||
|
||||
watch([selectedFile, showEditor], ([newFile, newShowEditor]) => {
|
||||
if (newFile && !newShowEditor) {
|
||||
// 处理 Markdown 内容中的图片 URL,将相对路径转换为完整路径
|
||||
const processImageUrls = (content) => {
|
||||
if (!content) return '';
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
|
||||
if (!baseUrl) return content;
|
||||
|
||||
// 匹配 Markdown 图片语法 
|
||||
return content.replace(
|
||||
/!\[([^\]]*)\]\((\/api\/images\/preview\/[^)]+)\)/g,
|
||||
(_match, alt, relativeUrl) => {
|
||||
// 确保 URL 格式正确
|
||||
const fullUrl = baseUrl.endsWith('/') && relativeUrl.startsWith('/')
|
||||
? baseUrl + relativeUrl.substring(1)
|
||||
: baseUrl + relativeUrl;
|
||||
return ``;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
// 渲染 Markdown 内容的函数
|
||||
const renderMarkdown = async (file) => {
|
||||
if (!file || showEditor.value) return;
|
||||
|
||||
// 使用文件ID+内容长度作为渲染标识,内容变化时重新渲染
|
||||
const renderKey = `${newFile.id}-${newFile.content?.length || 0}`;
|
||||
const renderKey = `${file.id}-${file.content?.length || 0}`;
|
||||
if (lastRenderedKey === renderKey) return;
|
||||
|
||||
// 使用 requestAnimationFrame 确保流畅渲染
|
||||
// 如果正在加载中,等待加载完成再渲染
|
||||
if (file.isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 等待 DOM 更新完成
|
||||
await nextTick();
|
||||
|
||||
// 使用 requestAnimationFrame 确保浏览器已完成布局和绘制
|
||||
requestAnimationFrame(() => {
|
||||
const previewElement = document.querySelector('.markdown-preview');
|
||||
if (previewElement) {
|
||||
const contentToRender = (newFile.isPrivate === 1 && !userStore.isLoggedIn) ? privateNoteContent : newFile.content;
|
||||
let contentToRender = (file.isPrivate === 1 && !userStore.isLoggedIn) ? privateNoteContent : file.content;
|
||||
// 处理图片 URL
|
||||
contentToRender = processImageUrls(contentToRender);
|
||||
// 先清空内容,避免闪烁
|
||||
previewElement.innerHTML = '';
|
||||
Vditor.preview(previewElement, contentToRender || '', {
|
||||
mode: 'light',
|
||||
hljs: { enable: true, style: 'github' }
|
||||
hljs: { enable: true, style: 'github' },
|
||||
after: () => {
|
||||
// 渲染完成后,如果文件有 isRendering 标记,移除它
|
||||
if (selectedFile.value && selectedFile.value.isRendering) {
|
||||
selectedFile.value = { ...selectedFile.value, isRendering: false };
|
||||
}
|
||||
// 为图片添加懒加载属性
|
||||
const images = previewElement.querySelectorAll('img');
|
||||
images.forEach(img => {
|
||||
if (!img.hasAttribute('loading')) {
|
||||
img.setAttribute('loading', 'lazy');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
lastRenderedKey = renderKey;
|
||||
} else {
|
||||
// 如果元素不存在,100ms 后重试
|
||||
setTimeout(() => renderMarkdown(file), 100);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 监听选中文件变化,自动渲染
|
||||
watch(() => selectedFile.value, (newFile) => {
|
||||
if (newFile && !showEditor.value) {
|
||||
renderMarkdown(newFile);
|
||||
} else if (!newFile) {
|
||||
// 用户返回列表页,重置渲染缓存
|
||||
lastRenderedKey = null;
|
||||
}
|
||||
}, { deep: true });
|
||||
}, { deep: true, immediate: true });
|
||||
|
||||
// 监听编辑器状态变化
|
||||
watch(showEditor, (isEditor) => {
|
||||
if (!isEditor && selectedFile.value) {
|
||||
renderMarkdown(selectedFile.value);
|
||||
}
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
@@ -32,9 +32,9 @@ const vditor = ref(null);
|
||||
const currentId = ref(null);
|
||||
const isInitialized = ref(false);
|
||||
const saveStatus = ref('');
|
||||
let saveTimeout = null;
|
||||
let lastSavedContent = ref('');
|
||||
let isSaving = ref(false);
|
||||
const saveTimeout = ref(null); // 修复:使用 ref 替代 let,确保响应式追踪
|
||||
const lastSavedContent = ref('');
|
||||
const isSaving = ref(false);
|
||||
// 维护当前最新的笔记数据
|
||||
const currentData = ref({ ...props.editData });
|
||||
|
||||
@@ -63,9 +63,9 @@ const initVditor = () => {
|
||||
input: (value) => {
|
||||
if (!isInitialized.value) return;
|
||||
|
||||
clearTimeout(saveTimeout);
|
||||
clearTimeout(saveTimeout.value);
|
||||
saveStatus.value = '正在输入...';
|
||||
saveTimeout = setTimeout(() => {
|
||||
saveTimeout.value = setTimeout(() => {
|
||||
if (!isSaving.value && value !== lastSavedContent.value) {
|
||||
save(value);
|
||||
}
|
||||
@@ -78,9 +78,14 @@ const initVditor = () => {
|
||||
if (!file) return;
|
||||
|
||||
uploadImage(file).then(res => {
|
||||
const url = res.url;
|
||||
// 后端返回相对路径,拼接成完整 URL
|
||||
const relativeUrl = res.url;
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
|
||||
vditor.value.insertValue(``);
|
||||
// 确保 URL 格式正确,避免双斜杠
|
||||
const fullUrl = baseUrl.endsWith('/') && relativeUrl.startsWith('/')
|
||||
? baseUrl + relativeUrl.substring(1)
|
||||
: baseUrl + relativeUrl;
|
||||
vditor.value.insertValue(``);
|
||||
}).catch((error) => {
|
||||
// 错误已在 axios 拦截器中显示,这里不再重复显示
|
||||
console.error('图片上传失败:', error);
|
||||
@@ -185,7 +190,11 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearTimeout(saveTimeout);
|
||||
// 修复:确保清理定时器
|
||||
if (saveTimeout.value) {
|
||||
clearTimeout(saveTimeout.value);
|
||||
saveTimeout.value = null;
|
||||
}
|
||||
if (vditor.value) {
|
||||
vditor.value.destroy();
|
||||
vditor.value = null;
|
||||
|
||||
@@ -46,6 +46,11 @@
|
||||
<el-icon class="loading-icon is-loading"><Loading /></el-icon>
|
||||
<span class="loading-text">内容加载中...</span>
|
||||
</div>
|
||||
<!-- 渲染状态遮罩 -->
|
||||
<div v-else-if="file.isRendering" class="content-loading">
|
||||
<el-icon class="loading-icon is-loading"><Loading /></el-icon>
|
||||
<span class="loading-text">正在渲染...</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ export const useUserStore = defineStore('user', {
|
||||
state: () => ({
|
||||
token: '',
|
||||
userInfo: null,
|
||||
tokenExpiry: null, // 添加 Token 过期时间
|
||||
}),
|
||||
actions: {
|
||||
async login(username, password) {
|
||||
@@ -12,6 +13,9 @@ export const useUserStore = defineStore('user', {
|
||||
const response = await loginApi({ username, password });
|
||||
if (response && response.token) {
|
||||
this.token = response.token;
|
||||
// 解析 JWT 获取过期时间
|
||||
const payload = JSON.parse(atob(response.token.split('.')[1]));
|
||||
this.tokenExpiry = payload.exp * 1000; // 转换为毫秒
|
||||
if (response.userInfo) {
|
||||
this.userInfo = response.userInfo;
|
||||
}
|
||||
@@ -26,10 +30,16 @@ export const useUserStore = defineStore('user', {
|
||||
logout() {
|
||||
this.token = '';
|
||||
this.userInfo = null;
|
||||
this.tokenExpiry = null;
|
||||
},
|
||||
// 检查 Token 是否过期
|
||||
isTokenExpired() {
|
||||
if (!this.tokenExpiry) return true;
|
||||
return Date.now() >= this.tokenExpiry;
|
||||
},
|
||||
},
|
||||
getters: {
|
||||
isLoggedIn: (state) => !!state.token,
|
||||
isLoggedIn: (state) => !!state.token && Date.now() < (state.tokenExpiry || 0),
|
||||
// 添加:判断是否为管理员
|
||||
isAdmin: (state) => state.userInfo?.role === 'ADMIN',
|
||||
},
|
||||
@@ -38,7 +48,7 @@ export const useUserStore = defineStore('user', {
|
||||
strategies: [
|
||||
{
|
||||
key: 'user-store',
|
||||
storage: sessionStorage,
|
||||
storage: sessionStorage, // 使用 sessionStorage,比 localStorage 更安全
|
||||
}
|
||||
],
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@ SET FOREIGN_KEY_CHECKS = 0;
|
||||
-- 1. 分组表
|
||||
DROP TABLE IF EXISTS `grouping`;
|
||||
CREATE TABLE `grouping` (
|
||||
`id` bigintBIGINT(20) NOT NULL AUTO_INCREMENT,
|
||||
`id` bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
`grouping` VARCHAR(255) NOT NULL,
|
||||
`parentId` BIGINT(20) DEFAULT NULL,
|
||||
`is_deleted` TINYINT(1) DEFAULT 0,
|
||||
|
||||
BIN
uploads/8357c5d3-eaa4-4aed-8306-ae91da62340b.png
Normal file
BIN
uploads/8357c5d3-eaa4-4aed-8306-ae91da62340b.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
Reference in New Issue
Block a user