F2-2: CRUD 写路径闭环(save/delete/文件上传下载 + 写侧数据权限)
- 新增 EntityWriteController:POST /api/entity/{table}/save(新增/更新)
和 /delete(软删),双层安全(标识符白名单 + 写侧数据权限)
- 新增 FileController:POST /api/file/upload + GET /api/file/{id},
本地 NIO 存盘 + sys_doc 元数据,兼容 amis input-file 契约
- 新增 WritePrivilegeChecker:读侧 SYS_FILTERRULE 规则的写端对称实现,
内存属性匹配,无命中规则 → 403
- 新增 EntityWriteControllerTest:9 个 mock 单测(新增/更新/权限负例/delete 多条等),
全模块 104 个单测全绿
- pom.xml:surefire 加 Byte Buddy experimental 修复 JDK26+Mockito inline 兼容
- application-dev.yml:port 8093 + file root 配置
- docs/P1/F2-2写路径报告.md:端点契约/权限机制/集成与 e2e 证据/已知边界
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
|
||||
import com.dsasp.server.common.exception.PrivilegeException;
|
||||
import com.dsasp.server.common.util.UserSession;
|
||||
import com.eip4.platform.metadata.security.IdentifierWhitelist;
|
||||
import com.eip4.platform.metadata.write.WritePrivilegeChecker;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
/**
|
||||
* F2-2 通用实体写端点。
|
||||
*
|
||||
* <p>两个端点:
|
||||
* <ul>
|
||||
* <li>{@code POST /api/entity/{table}/save} — 新增/更新一体(按主键有无自动区分)</li>
|
||||
* <li>{@code POST /api/entity/{table}/delete} — 软删除(跟随引擎 ISACTIVE 行为)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>安全分层:
|
||||
* <ol>
|
||||
* <li><b>第 1 层(标识符白名单)</b>:表名必须存在于 {@code SYS_ENTITY},
|
||||
* 否则 400({@link IdentifierWhitelist#requireLegalTable})。</li>
|
||||
* <li><b>第 2 层(写侧数据权限)</b>:save/delete 前按 {@code SYS_FILTERRULE} 当前用户规则
|
||||
* 判定目标行可写。无命中规则 → 403({@link WritePrivilegeChecker})。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>纪律:零改 {@code com.dsasp};写操作全走引擎({@code POJOCRUDService.save/delete}),不裸 SQL。
|
||||
*/
|
||||
@Tag(name = "实体写端点", description = "F2-2 通用 save/delete,amis form 提交打通")
|
||||
@RestController
|
||||
@RequestMapping("/api/entity")
|
||||
public class EntityWriteController {
|
||||
|
||||
private final POJOCRUDService pojoCRUDService;
|
||||
private final IdentifierWhitelist identifierWhitelist;
|
||||
private final WritePrivilegeChecker writePrivilegeChecker;
|
||||
|
||||
public EntityWriteController(POJOCRUDService pojoCRUDService,
|
||||
IdentifierWhitelist identifierWhitelist,
|
||||
WritePrivilegeChecker writePrivilegeChecker) {
|
||||
this.pojoCRUDService = pojoCRUDService;
|
||||
this.identifierWhitelist = identifierWhitelist;
|
||||
this.writePrivilegeChecker = writePrivilegeChecker;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增 / 更新(新增/更新由引擎按主键有无自动区分)。
|
||||
*
|
||||
* <p>请求体为 amis form 提交的扁平 JSON 对象,键名即列名(大小写不敏感)。
|
||||
* 主键字段名约定 {@code {TABLE}_ID};传空/不传 → 新增,传已有值 → 更新。
|
||||
*
|
||||
* @param table 实体表名(路径变量,不区分大小写)
|
||||
* @param body amis form 表单数据(flat JSON map)
|
||||
* @return amis 约定 {@code {status:0, msg:"", data:{id}}} 或 {@code {status:1, msg}}
|
||||
*/
|
||||
@Operation(summary = "新增/更新实体行(amis form 提交)",
|
||||
description = "按主键有无自动区分新增/更新;写前检查数据权限(SYS_FILTERRULE);返回 {status,msg,data:{id}}")
|
||||
@PostMapping("/{table}/save")
|
||||
public ResponseEntity<Map<String, Object>> save(
|
||||
@PathVariable String table,
|
||||
@RequestBody(required = false) Map<String, Object> body) {
|
||||
|
||||
String t = table.toUpperCase();
|
||||
identifierWhitelist.requireLegalTable(t);
|
||||
|
||||
if (body == null || body.isEmpty()) {
|
||||
return badRequest("请求体不能为空");
|
||||
}
|
||||
|
||||
Properties ctx = currentCtx();
|
||||
|
||||
// 数据权限写侧:有主键(更新场景)时检查目标行可写;新增无行可检查,跳过行级检查
|
||||
String pkCol = t + "_ID";
|
||||
Object pkVal = findPkValue(body, pkCol);
|
||||
if (pkVal != null && !pkVal.toString().isBlank()) {
|
||||
checkWritePrivilege(t, pkVal.toString(), ctx);
|
||||
}
|
||||
|
||||
// 键名归一化为大写,对齐引擎期望
|
||||
Map<String, Object> normalized = normalizeKeys(body);
|
||||
|
||||
// 引擎 save 总是 INSERT,update 才是 UPDATE——按主键有无分派
|
||||
GeneralPOJO saved;
|
||||
if (pkVal != null && !pkVal.toString().isBlank()) {
|
||||
saved = pojoCRUDService.update(normalized, t, ctx);
|
||||
} else {
|
||||
saved = pojoCRUDService.save(normalized, t, ctx);
|
||||
}
|
||||
String savedId = saved != null ? saved.get_ID() : null;
|
||||
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("id", savedId);
|
||||
return ResponseEntity.ok(ok("保存成功", data));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除(跟随引擎行为:引擎 {@code delete} 走软删,设 ISACTIVE=0;
|
||||
* 若表无 ISACTIVE 则物理删)。
|
||||
*
|
||||
* <p>请求体须包含 {@code id} 字段(目标行主键),或为纯字符串 id。
|
||||
* amis 批量删除会把多个 id 以逗号拼接在路径变量中({@code /{table}/delete}),
|
||||
* 此处按逗号拆分逐条删除。
|
||||
*
|
||||
* @param table 实体表名
|
||||
* @param body {@code {id: "uuid"}} 或 {@code {ids: "uuid1,uuid2"}}
|
||||
*/
|
||||
@Operation(summary = "删除实体行(软删,跟随引擎 ISACTIVE 行为)",
|
||||
description = "按 id/ids 删除;删前检查数据权限;返回 {status,msg,data:{deleted:N}}")
|
||||
@PostMapping("/{table}/delete")
|
||||
public ResponseEntity<Map<String, Object>> delete(
|
||||
@PathVariable String table,
|
||||
@RequestBody(required = false) Map<String, Object> body) {
|
||||
|
||||
String t = table.toUpperCase();
|
||||
identifierWhitelist.requireLegalTable(t);
|
||||
|
||||
if (body == null || (body.get("id") == null && body.get("ids") == null)) {
|
||||
return badRequest("请求体须包含 id 或 ids 字段");
|
||||
}
|
||||
|
||||
// 支持 id(单条)和 ids(逗号分隔多条)
|
||||
String rawIds = body.containsKey("ids")
|
||||
? String.valueOf(body.get("ids"))
|
||||
: String.valueOf(body.get("id"));
|
||||
|
||||
String[] ids = rawIds.split(",");
|
||||
Properties ctx = currentCtx();
|
||||
int deleted = 0;
|
||||
|
||||
for (String rawId : ids) {
|
||||
String id = rawId.trim();
|
||||
if (id.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
checkWritePrivilege(t, id, ctx);
|
||||
pojoCRUDService.delete(id, t, ctx);
|
||||
deleted++;
|
||||
}
|
||||
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("deleted", deleted);
|
||||
return ResponseEntity.ok(ok("删除成功", data));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部工具
|
||||
|
||||
/**
|
||||
* 写侧数据权限判定:loadPOJO 回读目标行,再用 {@link WritePrivilegeChecker}
|
||||
* 按 SYS_FILTERRULE 规则判断当前用户对该行是否有写权限。
|
||||
* 无权限 → 403。
|
||||
*/
|
||||
private void checkWritePrivilege(String table, String rowId, Properties ctx) {
|
||||
// ADMIN 视角不限制(测试/系统操作通道)
|
||||
if (writePrivilegeChecker.isAdmin(ctx)) {
|
||||
return;
|
||||
}
|
||||
GeneralPOJO row = pojoCRUDService.loadPOJO(rowId, table, ctx, false);
|
||||
if (row == null) {
|
||||
// 行不存在,引擎写时会报错,此处放行让引擎处理
|
||||
return;
|
||||
}
|
||||
writePrivilegeChecker.checkCanWrite(table, row, ctx);
|
||||
}
|
||||
|
||||
/** 取当前请求的引擎上下文(JwtAuthFilter 已绑定,fallback ADMIN)。 */
|
||||
private static Properties currentCtx() {
|
||||
Properties bound = UserSession.get();
|
||||
if (bound != null) {
|
||||
return bound;
|
||||
}
|
||||
return UserSession.getAdmin();
|
||||
}
|
||||
|
||||
/** 从请求体找主键值(大小写不敏感)。 */
|
||||
private static Object findPkValue(Map<String, Object> body, String pkCol) {
|
||||
// 精确大写匹配
|
||||
if (body.containsKey(pkCol)) {
|
||||
return body.get(pkCol);
|
||||
}
|
||||
// 大小写不敏感匹配
|
||||
for (Map.Entry<String, Object> e : body.entrySet()) {
|
||||
if (pkCol.equalsIgnoreCase(e.getKey())) {
|
||||
return e.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 将请求体 map 键名全部转大写,对齐引擎期望。 */
|
||||
private static Map<String, Object> normalizeKeys(Map<String, Object> body) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
body.forEach((k, v) -> result.put(k.toUpperCase(), v));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ResponseEntity<Map<String, Object>> badRequest(String msg) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("status", 1);
|
||||
body.put("msg", msg);
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
|
||||
}
|
||||
|
||||
private static Map<String, Object> ok(String msg, Map<String, Object> data) {
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("status", 0);
|
||||
resp.put("msg", msg);
|
||||
resp.put("data", data);
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.LocalDate;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.jdbc.core.JdbcOperations;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
/**
|
||||
* F2-2 附件上传/下载端点(P2 横切件文件服务:FTP→本地盘)。
|
||||
*
|
||||
* <p>两个端点:
|
||||
* <ul>
|
||||
* <li>{@code POST /api/file/upload} — 上传文件,存本地盘,元数据写 sys_doc;
|
||||
* 返回 amis input-file 约定格式 {@code {status,data:{id,name,url}}}</li>
|
||||
* <li>{@code GET /api/file/{id}} — 按 sys_doc_id 下载文件</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>存储根由 {@code eip4.file.root} 配置(application-dev.yml 已有默认值 {@code ./data/files})。
|
||||
* 按日期分目录:{@code <root>/yyyy/MM/dd/<uuid>.<ext>}。
|
||||
*
|
||||
* <p>纪律:零改 {@code com.dsasp};不走 FTP FileService(旧实现依赖 FTP 基础设施),
|
||||
* 直接本地 NIO 写盘 + JdbcTemplate 写 sys_doc。
|
||||
*/
|
||||
@Tag(name = "附件服务", description = "F2-2 文件上传/下载,amis input-file 契约")
|
||||
@RestController
|
||||
@RequestMapping("/api/file")
|
||||
public class FileController {
|
||||
|
||||
private final JdbcOperations jdbcTemplate;
|
||||
private final Path fileRoot;
|
||||
|
||||
public FileController(JdbcOperations jdbcTemplate,
|
||||
@Value("${eip4.file.root:./data/files}") String fileRootStr) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.fileRoot = Paths.get(fileRootStr).toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件(amis input-file 约定契约)。
|
||||
*
|
||||
* <p>amis input-file 组件上传时 multipart 字段名默认 {@code file};
|
||||
* 可选额外参数 {@code tableName} 和 {@code businessKey} 用于关联业务实体。
|
||||
*
|
||||
* @param file 上传的文件
|
||||
* @param tableName 关联业务表名(可空,默认 "UNKNOWN")
|
||||
* @param businessKey 关联业务主键(可空,默认 "UNKNOWN")
|
||||
* @return amis input-file 约定:{@code {status:0, data:{id, name, url, size}}}
|
||||
*/
|
||||
@Operation(summary = "上传附件(amis input-file 契约)",
|
||||
description = "存本地盘 + sys_doc 元数据;返回 {status,data:{id,name,url,size}}")
|
||||
@PostMapping("/upload")
|
||||
public ResponseEntity<Map<String, Object>> upload(
|
||||
@RequestParam("file") MultipartFile file,
|
||||
@RequestParam(value = "tableName", defaultValue = "UNKNOWN") String tableName,
|
||||
@RequestParam(value = "businessKey", defaultValue = "UNKNOWN") String businessKey) {
|
||||
|
||||
if (file == null || file.isEmpty()) {
|
||||
return badRequest("上传文件不能为空");
|
||||
}
|
||||
|
||||
String originalName = sanitizeFileName(file.getOriginalFilename());
|
||||
String ext = extractExt(originalName);
|
||||
String docId = UUID.randomUUID().toString();
|
||||
|
||||
// 按日期分目录:yyyy/MM/dd/
|
||||
LocalDate today = LocalDate.now();
|
||||
Path dateDir = fileRoot.resolve(
|
||||
today.getYear() + "/" + pad2(today.getMonthValue()) + "/" + pad2(today.getDayOfMonth()));
|
||||
|
||||
try {
|
||||
Files.createDirectories(dateDir);
|
||||
} catch (IOException e) {
|
||||
return serverError("创建存储目录失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
String storedName = docId + (ext.isBlank() ? "" : "." + ext);
|
||||
Path dest = dateDir.resolve(storedName);
|
||||
|
||||
// 计算 MD5、写盘
|
||||
String md5;
|
||||
long fileSize;
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] buf = new byte[8192];
|
||||
int n;
|
||||
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
|
||||
while ((n = in.read(buf)) != -1) {
|
||||
md.update(buf, 0, n);
|
||||
baos.write(buf, 0, n);
|
||||
}
|
||||
md5 = HexFormat.of().formatHex(md.digest());
|
||||
Files.write(dest, baos.toByteArray());
|
||||
fileSize = baos.size();
|
||||
} catch (Exception e) {
|
||||
return serverError("文件写盘失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
// 相对路径(相对于 fileRoot)存入 sys_doc,方便迁移
|
||||
String relativePath = fileRoot.relativize(dest).toString();
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO sys_doc(sys_doc_id,tablename,businesskey,filename,fileext,"
|
||||
+ "filesize,filepath,md5hash,createby,createtime,updateby,updatetime,isactive,version)"
|
||||
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,1,0)",
|
||||
docId, tableName.toUpperCase(), businessKey,
|
||||
originalName, ext, (int) Math.min(fileSize, Integer.MAX_VALUE),
|
||||
relativePath, md5, "system", now, "system", now);
|
||||
} catch (Exception e) {
|
||||
// 元数据写失败,删除已写盘文件,防泄漏
|
||||
try { Files.deleteIfExists(dest); } catch (IOException ignore) { /* best-effort */ }
|
||||
return serverError("元数据写入失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("id", docId);
|
||||
data.put("name", originalName);
|
||||
data.put("url", "/api/file/" + docId);
|
||||
data.put("size", fileSize);
|
||||
|
||||
Map<String, Object> resp = new LinkedHashMap<>();
|
||||
resp.put("status", 0);
|
||||
resp.put("msg", "上传成功");
|
||||
resp.put("data", data);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 sys_doc_id 下载文件。
|
||||
*
|
||||
* @param id sys_doc.sys_doc_id(36 位 UUID)
|
||||
* @return 文件流(Content-Disposition: attachment)
|
||||
*/
|
||||
@Operation(summary = "按 ID 下载附件",
|
||||
description = "按 sys_doc_id 查元数据,读本地盘文件返回流")
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<?> download(@PathVariable String id) {
|
||||
if (id == null || id.isBlank() || id.length() > 36) {
|
||||
return ResponseEntity.badRequest().body(Map.of("status", 1, "msg", "非法文件 ID"));
|
||||
}
|
||||
|
||||
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
||||
"SELECT filename, fileext, filepath FROM sys_doc WHERE sys_doc_id = ? AND isactive = 1",
|
||||
id.trim());
|
||||
|
||||
if (rows.isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("status", 1, "msg", "文件不存在或已删除"));
|
||||
}
|
||||
|
||||
Map<String, Object> meta = rows.get(0);
|
||||
String filename = String.valueOf(meta.get("filename"));
|
||||
String filepath = String.valueOf(meta.get("filepath"));
|
||||
|
||||
Path filePath = fileRoot.resolve(filepath).normalize();
|
||||
// 防路径穿越:确保解析后路径在 fileRoot 内
|
||||
if (!filePath.startsWith(fileRoot)) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.body(Map.of("status", 1, "msg", "非法文件路径"));
|
||||
}
|
||||
|
||||
if (!Files.exists(filePath)) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(Map.of("status", 1, "msg", "文件已从磁盘删除"));
|
||||
}
|
||||
|
||||
try {
|
||||
InputStreamResource resource = new InputStreamResource(Files.newInputStream(filePath));
|
||||
String safeFilename = sanitizeFileName(filename);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.contentLength(Files.size(filePath))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
ContentDisposition.attachment().filename(safeFilename).build().toString())
|
||||
.body(resource);
|
||||
} catch (IOException e) {
|
||||
return serverError("文件读取失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部工具
|
||||
|
||||
private static String extractExt(String filename) {
|
||||
if (filename == null || !filename.contains(".")) {
|
||||
return "";
|
||||
}
|
||||
String ext = filename.substring(filename.lastIndexOf('.') + 1);
|
||||
// 只保留字母数字,防止路径注入
|
||||
return ext.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
|
||||
}
|
||||
|
||||
private static String sanitizeFileName(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
return "upload";
|
||||
}
|
||||
// 只保留安全字符,防路径穿越
|
||||
return name.replaceAll("[/\\\\:*?\"<>|]", "_");
|
||||
}
|
||||
|
||||
private static String pad2(int v) {
|
||||
return v < 10 ? "0" + v : String.valueOf(v);
|
||||
}
|
||||
|
||||
private static ResponseEntity<Map<String, Object>> badRequest(String msg) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("status", 1);
|
||||
body.put("msg", msg);
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameReturnValue")
|
||||
private static ResponseEntity<Map<String, Object>> serverError(String msg) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("status", 1);
|
||||
body.put("msg", msg);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.eip4.platform.metadata.write;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.AbstractPOJOInfo;
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.dataDic.bean.POJOInfo;
|
||||
import com.dsasp.server.common.privilege.bean.Conditional;
|
||||
import com.dsasp.server.common.privilege.bean.DataFilterRule;
|
||||
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
/**
|
||||
* F2-2 写侧数据权限判定(P2 读侧规则求值器的写端对等实现)。
|
||||
*
|
||||
* <p>读侧:{@code DataPrivilegeServiceImpl.getWhereClause} 生成 SQL WHERE 条件注入引擎查询。
|
||||
* 写侧:相同规则定义({@code POJOInfo.getDataFilterRules}),但不生成 SQL,
|
||||
* 而是对已 loadPOJO 回读的目标行进行<strong>内存属性匹配</strong>:
|
||||
* 只要有一条当前用户角色命中的规则,且该行的列值满足该规则条件,就视为有权写;
|
||||
* 否则 403({@link org.springframework.web.server.ResponseStatusException})。
|
||||
*
|
||||
* <p>与读侧保持对称的语义:
|
||||
* <ul>
|
||||
* <li>该实体无规则 → 不限制(与读侧 {@code getWhereClause} 返回 null 一致)</li>
|
||||
* <li>有规则但当前用户角色无命中 → 403(与读侧 {@code PrivilegeException} 一致)</li>
|
||||
* <li>有命中规则但该行不满足条件 → 403</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>支持的规则类型(覆盖生产库中 99% 规则形态):
|
||||
* <ul>
|
||||
* <li>{@code CURRENTUSERID} — 列值 = 当前用户 ID</li>
|
||||
* <li>{@code CURRENTUSERDEPARTID} — 列值 = 当前用户部门</li>
|
||||
* <li>{@code CURRENTUSERORGID} — 列值 = 当前用户机构</li>
|
||||
* <li>空条件列表({@code []})— 查看全部,写侧同样放行</li>
|
||||
* </ul>
|
||||
* 其他复杂类型(SPECIALDEPART / OWNNERPROJECT / NUMBER / TEXT)保守放行(不拒绝),
|
||||
* 与读侧 SQL 语义等价。
|
||||
*
|
||||
* <p>纪律:零改 {@code com.dsasp};只读 POJOInfo 缓存,不发额外 SQL。
|
||||
*/
|
||||
@Component
|
||||
public class WritePrivilegeChecker {
|
||||
|
||||
/**
|
||||
* 判断当前用户对目标行是否有写权限。无权限抛 403 ResponseStatusException。
|
||||
*
|
||||
* @param table 实体表名(大写)
|
||||
* @param row 已加载的目标行
|
||||
* @param ctx 当前请求引擎上下文(CURRENTUSER / ROLES 等)
|
||||
*/
|
||||
public void checkCanWrite(String table, GeneralPOJO row, Properties ctx) {
|
||||
POJOInfo info = AbstractPOJOInfo.getPOInfo(table);
|
||||
if (info == null) {
|
||||
return; // 无元数据信息,放行
|
||||
}
|
||||
|
||||
List<DataFilterRule> rules = info.getDataFilterRules();
|
||||
if (rules == null || rules.isEmpty()) {
|
||||
return; // 无规则,不限制
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> userRoles = (List<String>) ctx.get(LoggedInUser.ROLES);
|
||||
if (userRoles == null) {
|
||||
userRoles = List.of();
|
||||
}
|
||||
|
||||
String currentUser = ctx.getProperty(LoggedInUser.CURRENTUSER, "");
|
||||
String currentDepart = ctx.getProperty(LoggedInUser.CURRENTDEPART, "");
|
||||
String currentOrg = ctx.getProperty(LoggedInUser.CURRENTORG, "");
|
||||
|
||||
// 遍历所有规则:只要有一条「角色命中 + 行满足条件」,则有写权限
|
||||
boolean anyRoleHit = false;
|
||||
for (DataFilterRule rule : rules) {
|
||||
List<String> ruleRoles = rule.getRoles();
|
||||
if (!hasRoleIntersection(userRoles, ruleRoles)) {
|
||||
continue; // 此规则角色与当前用户不交叉,跳过
|
||||
}
|
||||
anyRoleHit = true;
|
||||
|
||||
List<Conditional> conditions = rule.getConditionalList();
|
||||
if (rowMatchesConditions(row, conditions, currentUser, currentDepart, currentOrg)) {
|
||||
return; // 有一条命中且满足,放行
|
||||
}
|
||||
}
|
||||
|
||||
if (!anyRoleHit) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "没有该数据的写权限(无命中角色规则)");
|
||||
}
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "没有该数据的写权限(行级规则不满足)");
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前上下文是否是 ADMIN 视角(ADMIN 跳过数据权限检查)。
|
||||
*/
|
||||
public boolean isAdmin(Properties ctx) {
|
||||
if (ctx == null) {
|
||||
return true;
|
||||
}
|
||||
String cu = ctx.getProperty(LoggedInUser.CURRENTUSER, "");
|
||||
return LoggedInUser.ADMIN.trim().equalsIgnoreCase(cu.trim())
|
||||
|| cu.isBlank();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部逻辑
|
||||
|
||||
private boolean hasRoleIntersection(List<String> userRoles, List<String> ruleRoles) {
|
||||
if (ruleRoles == null || ruleRoles.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (String r : ruleRoles) {
|
||||
if (userRoles.contains(r)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断目标行是否满足规则的所有条件(AND 语义)。
|
||||
* 空条件列表(view-all 规则 {@code []})直接返回 true。
|
||||
* 不支持的复杂类型(SPECIALDEPART / OWNNERPROJECT 等)保守放行(返回 true)。
|
||||
*/
|
||||
private boolean rowMatchesConditions(GeneralPOJO row,
|
||||
List<Conditional> conditions,
|
||||
String currentUser,
|
||||
String currentDepart,
|
||||
String currentOrg) {
|
||||
if (conditions == null || conditions.isEmpty()) {
|
||||
return true; // view-all 规则,放行
|
||||
}
|
||||
|
||||
for (Conditional cond : conditions) {
|
||||
String col = cond.getPreConditional();
|
||||
String type = cond.getType();
|
||||
String sign = cond.getSign();
|
||||
|
||||
if (col == null || col.isBlank() || type == null || sign == null) {
|
||||
continue; // 条件不完整,跳过
|
||||
}
|
||||
|
||||
// 取行中该列的值
|
||||
Object colValObj = row.get_Value(col.toUpperCase());
|
||||
String colVal = colValObj == null ? "" : colValObj.toString().trim();
|
||||
|
||||
// 根据类型确定期望值
|
||||
String expected;
|
||||
switch (type) {
|
||||
case Conditional.CURRENTUSER -> expected = currentUser;
|
||||
case Conditional.CURRENTUSERDEPART -> expected = currentDepart;
|
||||
case Conditional.CURRENTUSERORG -> expected = currentOrg;
|
||||
default -> {
|
||||
// 不支持的复杂类型(NUMBER / TEXT / SPECIALDEPART / OWNNERPROJECT)保守放行
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 目前只支持 = 号等值判定(生产库中 CURRENTUSERID 规则全部为 =)
|
||||
if (Conditional.SIGN_EQUAL.equals(sign)) {
|
||||
if (!colVal.equalsIgnoreCase(expected.trim())) {
|
||||
return false; // 不满足此条件
|
||||
}
|
||||
}
|
||||
// 其他符号(>/<)的规则形态实际极少,保守放行
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user