1. 附件加密上传下载

This commit is contained in:
chenbowen
2025-07-22 19:36:46 +08:00
parent d17fa356ba
commit 8ab6cb4bae
26 changed files with 411 additions and 94 deletions

View File

@@ -1,3 +1,8 @@
ALTER TABLE infra_file ADD hash VARCHAR(64);
COMMENT ON COLUMN infra_file.hash IS '文件哈希值SHA-256';
CREATE INDEX idx_infra_file_hash ON infra_file(hash);
CREATE INDEX idx_infra_file_hash ON infra_file(hash);
-- 2. 附件信息表新增 AES 加密时存储的随机 IV 字段
ALTER TABLE infra_file ADD aes_iv VARCHAR(128);
COMMENT ON COLUMN infra_file.aes_iv IS 'AES加密时的随机IVBase64编码';

View File

@@ -1,3 +1,6 @@
-- 1. 附件信息表新增上传文件 Hash 字段,如果上传文件 hash 重复直接复用不进行重复上传
ALTER TABLE infra_file ADD COLUMN hash VARCHAR(64) COMMENT '文件哈希值SHA-256';
CREATE INDEX idx_infra_file_hash ON infra_file(hash);
CREATE INDEX idx_infra_file_hash ON infra_file(hash);
-- 2. 附件信息表新增 AES 加密时存储的随机 IV 字段
ALTER TABLE infra_file ADD COLUMN aes_iv VARCHAR(128) NULL COMMENT 'AES加密时的随机IVBase64编码';

View File

@@ -40,5 +40,5 @@ public interface GlobalErrorCodeConstants {
// ========== 业务错误段 ==========
// 用户未设置公司信息,无法办理当前业务
ErrorCode USER_NOT_SET_DEPT = new ErrorCode(1000, "用户未设置有效的公司或部门信息,无法办理当前业务");
ErrorCode USER_NOT_SET_DEPT = new ErrorCode(1000, "用户未设置有效的公司或部门信息,无法办理当前业务,请确认已实现 BusinessControllerMarker 业务接口标记");
}

View File

@@ -0,0 +1,64 @@
package cn.iocoder.yudao.framework.business.core.util;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CompanyDeptInfo;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.singleton;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
/**
* @author chenbowen
*/
public class BusinessDeptHandleUtil {
public static Set<CompanyDeptInfo> getBelongCompanyAndDept(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=UTF-8");
String companyId = request.getHeader("visit-company-id");
String deptId = request.getHeader("visit-dept-id");
LoginUser loginUser = Optional.ofNullable(getLoginUser()).orElse(new LoginUser().setInfo(new HashMap<>()));
Set<CompanyDeptInfo> companyDeptSet = JSONUtil.parseArray(loginUser.getInfo().getOrDefault(LoginUser.INFO_KEY_COMPANY_DEPT_SET, "[]")).stream()
.map(obj -> JSONUtil.toBean((JSONObject) obj, CompanyDeptInfo.class))
.collect(Collectors.toSet());
// 1. 有 companyId
if (companyId != null && !companyId.isBlank()) {
// 根据请求头中的公司 ID 过滤出当前用户的公司部门信息
Set<CompanyDeptInfo> companyDeptSetByCompanyId = companyDeptSet.stream().filter(companyDeptInfo -> companyDeptInfo.getCompanyId().toString().equals(companyId)).collect(Collectors.toSet());
if (companyDeptSetByCompanyId.isEmpty()) {
// 当前公司下没有部门
CompanyDeptInfo data = new CompanyDeptInfo();
data.setCompanyId(Long.valueOf(companyId));
data.setDeptId(0L);
return new HashSet<>(singleton(data));
}
// 如果有 deptId校验其是否属于该 companyId
if (deptId != null) {
boolean valid = companyDeptSetByCompanyId.stream().anyMatch(info -> String.valueOf(info.getDeptId()).equals(deptId));
if (!valid) {
return null;
}else{
// 部门存在,放行
return new HashSet<>();
}
}
return companyDeptSetByCompanyId;
}
// 2. 没有公司信息,尝试唯一性自动推断
// 如果当前用户下只有一个公司和部门的对于关系
if (companyDeptSet.size() == 1) {
CompanyDeptInfo companyDeptInfo = companyDeptSet.iterator().next();
return new HashSet<>(singleton(companyDeptInfo));
} else {
return companyDeptSet;
}
}
}

View File

@@ -1,11 +1,8 @@
package cn.iocoder.yudao.framework.business.interceptor;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResultCodeEnum;
import cn.iocoder.yudao.framework.common.pojo.CompanyDeptInfo;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@@ -15,14 +12,9 @@ import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.singleton;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.framework.business.core.util.BusinessDeptHandleUtil.getBelongCompanyAndDept;
/**
* @author chenbowen
@@ -39,54 +31,18 @@ public class BusinessHeaderInterceptor implements HandlerInterceptor {
if (!(bean instanceof BusinessControllerMarker)) {
return true;
}
response.setContentType("application/json;charset=UTF-8");
String companyId = request.getHeader("visit-company-id");
String deptId = request.getHeader("visit-dept-id");
LoginUser loginUser = Optional.ofNullable(getLoginUser()).orElse(new LoginUser().setInfo(new HashMap<>()));
ObjectMapper objectMapper = new ObjectMapper();
Set<CompanyDeptInfo> companyDeptSet = JSONUtil.parseArray(loginUser.getInfo().getOrDefault(LoginUser.INFO_KEY_COMPANY_DEPT_SET, "[]")).stream()
.map(obj -> JSONUtil.toBean((JSONObject) obj, CompanyDeptInfo.class))
.collect(Collectors.toSet());
// 1. 有 companyId
if (companyId != null && !companyId.isBlank()) {
Set<CompanyDeptInfo> companyDeptSetByCompanyId = companyDeptSet.stream().filter(companyDeptInfo -> companyDeptInfo.getCompanyId().toString().equals(companyId)).collect(Collectors.toSet());
List<CompanyDeptInfo> filtered = companyDeptSetByCompanyId.stream()
.filter(info -> String.valueOf(info.getCompanyId()).equals(companyId)).toList();
if (filtered.isEmpty()) {
// 当前公司下没有部门
CompanyDeptInfo data = new CompanyDeptInfo();
data.setCompanyId(Long.valueOf(companyId));
data.setDeptId(0L);
return writeResponse(response, HttpStatus.OK.value(), CommonResult.customize(singleton(data), CommonResultCodeEnum.NEED_ADJUST), objectMapper);
}
// 如果有 deptId校验其是否属于该 companyId
if (deptId != null) {
boolean valid = filtered.stream().anyMatch(info -> String.valueOf(info.getDeptId()).equals(deptId));
if (!valid) {
return writeResponse(response, HttpStatus.BAD_REQUEST.value(), CommonResult.customize(null, CommonResultCodeEnum.ERROR.getCode(),"当前用户匹配部门不属于此公司"), objectMapper);
}else{
// 部门存在,放行
return true;
}
}
if (filtered.size() == 1) {
// 唯一部门
return writeResponse(response, HttpStatus.OK.value(), CommonResult.customize(filtered,CommonResultCodeEnum.NEED_ADJUST), objectMapper);
} else {
// 多个部门
return writeResponse(response, HttpStatus.OK.value(), CommonResult.customize(filtered,CommonResultCodeEnum.NEED_ADJUST), objectMapper);
}
Set<CompanyDeptInfo> companyDeptInfos = getBelongCompanyAndDept(request, response);
// 无法获取到有效的用户归属公司与部门信息,提示错误
if (companyDeptInfos == null) {
return writeResponse(response, HttpStatus.BAD_REQUEST.value(), CommonResult.customize(null, CommonResultCodeEnum.ERROR.getCode(), "当前用户匹配部门不属于此公司"), objectMapper);
}
// 2. 没有公司信息,尝试唯一性自动推断
// 如果当前用户下只有一个公司和部门的对于关系
if (companyDeptSet.size() == 1) {
CompanyDeptInfo companyDeptInfo = companyDeptSet.iterator().next();
return writeResponse(response, HttpStatus.OK.value(), CommonResult.customize(singleton(companyDeptInfo),CommonResultCodeEnum.NEED_ADJUST), objectMapper);
} else {
return writeResponse(response, HttpStatus.OK.value(), CommonResult.customize(companyDeptSet,CommonResultCodeEnum.NEED_ADJUST), objectMapper);
// 获取到了有效的一组或多组公司与部门信息,需要返回前端进行补充请求头后的二次请求
if (!companyDeptInfos.isEmpty()) {
return writeResponse(response, HttpStatus.OK.value(), CommonResult.customize(companyDeptInfos, CommonResultCodeEnum.NEED_ADJUST), objectMapper);
}
else{
return true;
}
}

View File

@@ -33,6 +33,16 @@ public interface ErrorCodeConstants {
ErrorCode FILE_PATH_EXISTS = new ErrorCode(1_001_003_000, "文件路径已存在");
ErrorCode FILE_NOT_EXISTS = new ErrorCode(1_001_003_001, "文件不存在");
ErrorCode FILE_IS_EMPTY = new ErrorCode(1_001_003_002, "文件为空");
// 文件验证码生成失败
ErrorCode FILE_CAPTCHA_GENERATE_FAIL = new ErrorCode(1_001_003_003, "生成验证码失败,请稍后再试!");
// 文件验证码有误
ErrorCode FILE_CAPTCHA_ERROR = new ErrorCode(1_001_003_004, "验证码错误");
// 文件解密失败
ErrorCode FILE_DECRYPT_FAIL = new ErrorCode(1_001_003_005, "文件解密失败,请检查文件是否有效");
// 同一附件60秒内只能获取一次验证码
ErrorCode FILE_CAPTCHA_EXISTS = new ErrorCode(1_001_003_006, "同一附件60秒内只能获取一次验证码");
// 同一用户最多同时只能有10个有效验证码
ErrorCode FILE_CAPTCHA_MAX = new ErrorCode(1_001_003_007, "同一用户最多只能有10个有效验证码");
// ========== 代码生成器 1-001-004-000 ==========
ErrorCode CODEGEN_TABLE_EXISTS = new ErrorCode(1_001_004_002, "表定义已经存在");

View File

@@ -3,11 +3,10 @@ package cn.iocoder.yudao.module.infra.api.file;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.infra.api.file.dto.FileCreateReqDTO;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import jakarta.annotation.Resource;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
@RestController // 提供 RESTful API 接口,给 Feign 调用
@@ -20,7 +19,7 @@ public class FileApiImpl implements FileApi {
@Override
public CommonResult<String> createFile(FileCreateReqDTO createReqDTO) {
return success(fileService.createFile(createReqDTO.getContent(), createReqDTO.getName(),
createReqDTO.getDirectory(), createReqDTO.getType()));
createReqDTO.getDirectory(), createReqDTO.getType(), false));
}
}

View File

@@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.infra.controller.admin.file;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
@@ -29,8 +30,12 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.infra.framework.file.core.utils.FileTypeUtils.writeAttachment;
/**
* @author chenbowen
*/
@Tag(name = "管理后台 - 文件存储")
@RestController
@RequestMapping("/infra/file")
@@ -46,8 +51,7 @@ public class FileController {
public CommonResult<String> uploadFile(FileUploadReqVO uploadReqVO) throws Exception {
MultipartFile file = uploadReqVO.getFile();
byte[] content = IoUtil.readBytes(file.getInputStream());
return success(fileService.createFile(content, file.getOriginalFilename(),
uploadReqVO.getDirectory(), file.getContentType()));
return success(fileService.createFile(content, file.getOriginalFilename(), uploadReqVO.getDirectory(), file.getContentType(), uploadReqVO.getEncrypt()));
}
@PostMapping("/upload-with-return")
@@ -55,8 +59,7 @@ public class FileController {
public CommonResult<FileRespVO> uploadWithReturn(FileUploadReqVO uploadReqVO) throws IOException {
MultipartFile file = uploadReqVO.getFile();
byte[] content = IoUtil.readBytes(file.getInputStream());
return success(fileService.createFileWhitReturn(content, file.getOriginalFilename(),
uploadReqVO.getDirectory(), file.getContentType()));
return success(fileService.createFileWhitReturn(content, file.getOriginalFilename(), uploadReqVO.getDirectory(), file.getContentType(), uploadReqVO.getEncrypt()));
}
@GetMapping("/presigned-url")
@@ -120,4 +123,36 @@ public class FileController {
return success(BeanUtils.toBean(pageResult, FileRespVO.class));
}
@GetMapping("/verification-code")
@Operation(summary = "获取加密文件下载验证码 ")
public CommonResult<String> getVerificationCode(@RequestParam("fileId") Long fileId) {
Long userId = getLoginUserId();
String code = fileService.generateFileVerificationCode(fileId, userId);
return success(code);
}
@GetMapping("/verify-and-download")
@Operation(summary = "校验验证码并下载解密文件")
public void verifyAndDownload(@Valid @RequestParam Long fileId, @RequestParam String code, HttpServletResponse response) throws Exception {
Long userId = getLoginUserId();
byte[] content = fileService.verifyCodeAndGetFile(fileId, userId, code);
FileDO fileDO = fileService.getActiveFileById(fileId);
if (fileDO == null) {
response.setStatus(HttpStatus.NOT_FOUND.value());
return;
}
writeAttachment(response, fileDO.getName(), content);
}
@GetMapping("/generate-download-code")
@Operation(summary = "获取下载验证码")
public CommonResult<String> preDownloadEncrypt(@RequestParam("fileId") Long fileId) {
Long userId = getLoginUserId();
try {
fileService.generateFileVerificationCode(fileId, userId);
FileDO activeFileById = fileService.getActiveFileById(fileId);
return CommonResult.customize(activeFileById.getName(), HttpStatus.OK.value(), "验证码已生成,请使用验证码下载文件");
} catch (ServiceException e) {
return CommonResult.customize("生成验证码失败", HttpStatus.OK.value(), e.getMessage());
}
}
}

View File

@@ -1,11 +1,13 @@
package cn.iocoder.yudao.module.infra.controller.admin.file.vo.file;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import jakarta.validation.constraints.NotNull;
/**
* @author chenbowen
*/
@Schema(description = "管理后台 - 上传文件 Request VO")
@Data
public class FileUploadReqVO {
@@ -17,4 +19,7 @@ public class FileUploadReqVO {
@Schema(description = "文件目录", example = "XXX/YYY")
private String directory;
@Schema(description = "是否加密", example = "")
private Boolean encrypt = false;
}

View File

@@ -0,0 +1,16 @@
package cn.iocoder.yudao.module.infra.controller.admin.file.vo.file;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
* @author chenbowen
*/
@Data
public class FileVerificationCodeCheckReqVO {
@NotNull(message = "附件ID不能为空")
private Long fileId;
@NotBlank(message = "验证码不能为空")
private String code;
}

Some files were not shown because too many files have changed in this diff Show More