wisdomisite-java/src/main/java/com/zhgd/mybatis/DataScopeHandler.java

439 lines
19 KiB
Java
Raw Normal View History

2024-04-23 20:01:26 +08:00
package com.zhgd.mybatis;
2024-04-28 21:51:06 +08:00
import cn.hutool.core.collection.CollUtil;
2024-04-23 20:01:26 +08:00
import cn.hutool.core.util.StrUtil;
2024-05-05 22:34:36 +08:00
import com.alibaba.fastjson.JSONObject;
2024-04-23 20:01:26 +08:00
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
2024-04-24 01:15:10 +08:00
import com.zhgd.annotation.DataScope;
2024-05-06 18:43:30 +08:00
import com.zhgd.xmgl.modules.video.service.IAiAnalyseHardWareRecordService;
2024-04-23 20:01:26 +08:00
import com.zhgd.xmgl.modules.worker.entity.EnterpriseInfo;
import com.zhgd.xmgl.modules.worker.mapper.EnterpriseInfoMapper;
2024-04-28 21:51:06 +08:00
import com.zhgd.xmgl.modules.worker.service.impl.UserDevAuthorityServiceImpl;
2024-04-23 20:01:26 +08:00
import com.zhgd.xmgl.modules.worker.service.impl.UserEnterpriseServiceImpl;
import com.zhgd.xmgl.modules.xz.service.impl.XzSupplierQualificationApplyServiceImpl;
import com.zhgd.xmgl.security.entity.UserInfo;
import com.zhgd.xmgl.security.util.SecurityUtils;
import com.zhgd.xmgl.util.EnvironmentUtil;
2024-04-23 20:01:26 +08:00
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import java.util.ArrayList;
2024-04-24 01:15:10 +08:00
import java.util.HashMap;
2024-04-23 20:01:26 +08:00
import java.util.List;
2024-04-24 01:15:10 +08:00
import java.util.Map;
2024-04-23 20:01:26 +08:00
import java.util.stream.Collectors;
@Slf4j
public class DataScopeHandler implements DataPermissionHandler {
@Lazy
@Autowired
EnvironmentUtil environmentUtil;
2024-05-07 00:00:47 +08:00
@Lazy
@Autowired
IAiAnalyseHardWareRecordService aiAnalyseHardWareRecordService;
2024-04-23 20:01:26 +08:00
@Lazy
@Autowired
private XzSupplierQualificationApplyServiceImpl xzSupplierQualificationApplyService;
@Lazy
@Autowired
private EnterpriseInfoMapper enterpriseInfoMapper;
2024-04-28 21:51:06 +08:00
@Lazy
@Autowired
private UserDevAuthorityServiceImpl userDevAuthorityService;
2024-04-23 20:01:26 +08:00
@Lazy
@Autowired
private UserEnterpriseServiceImpl userEnterpriseService;
@Override
public Expression getSqlSegment(Expression where, String mappedStatementId) {
return null;
}
protected String getEngineeringSn() {
return "engineering_sn";
}
protected String getProjectSn() {
return "project_sn";
}
2024-05-11 01:58:58 +08:00
/**
* 获取设置的过滤的表名和字段名
*
* @return
*/
2024-04-24 01:15:10 +08:00
private HashMap<String, String> getFieldEnterpriseTables() {
HashMap<String, String> tables = new HashMap<>();
tables.put("worker_info", "enterprise_id");
tables.put("team_info", "enterprise_id");
2024-04-24 01:15:10 +08:00
tables.put("department_info", "enterprise_id");
2024-04-24 21:50:28 +08:00
tables.put("xz_task_progress_content", "enterprise_id");
tables.put("xz_task_progress_alarm", "enterprise_id");
tables.put("xz_task_progress", "enterprise_id");
2024-04-25 23:56:07 +08:00
tables.put("quality_inspection_record", "enterprise_id");
2024-04-26 19:45:39 +08:00
tables.put("worker_info_audit_record", "enterprise_id");
tables.put("xz_material", "enterprise_id");
2024-04-29 23:07:31 +08:00
tables.put("inspect_task_record", "enterprise_id");
tables.put("xz_security_inspect_task_record", "enterprise_id");
2024-04-30 16:32:57 +08:00
tables.put("xz_security_quality_inspection_record", "enterprise_id");
2024-05-24 17:24:36 +08:00
tables.put("exam_notice", "enterprise_id");
tables.put("exam_train_record", "enterprise_id");
tables.put("exam_course_record", "enterprise_id");
2024-05-24 19:58:31 +08:00
tables.put("xz_worker_safe_watch_alarm", "enterprise_id");
if (!environmentUtil.isBaise()) {
tables.put("car_info", "enterprise_id");
tables.put("enterprise_info", "id");
}
2024-04-24 01:15:10 +08:00
return tables;
2024-04-23 20:01:26 +08:00
}
2024-04-28 21:51:06 +08:00
private HashMap<String, String> getFieldVideoTables() {
HashMap<String, String> tables = new HashMap<>();
tables.put("video_item", "item_id");
return tables;
}
2024-05-06 18:43:30 +08:00
private HashMap<String, String> getFieldAiTables() {
HashMap<String, String> tables = new HashMap<>();
if (!environmentUtil.isBaise()) {
tables.put("ai_analyse_hard_ware_alarm_record", "hardware_id");
}
2024-05-06 18:43:30 +08:00
return tables;
}
2024-04-23 20:01:26 +08:00
public PlainSelect getSqlSegment(PlainSelect plainSelect, Object obj) {
UserInfo user = SecurityUtils.getUser();
if (user == null) {
return plainSelect;
}
2024-04-24 01:15:10 +08:00
return dataScopeFilterByProject(plainSelect, user, obj);
2024-04-23 20:01:26 +08:00
// else if (type == 2 && user.getAccountType() == 4) {
// return dataScopeFilterByProject(plainSelect, user);
//} else if (type == 2) {
// return dataScopeFilterByEnt(plainSelect, user);
//}
}
2024-04-24 01:15:10 +08:00
private PlainSelect dataScopeFilterByProject(PlainSelect plainSelect, UserInfo user, Object obj) {
2024-05-05 22:34:36 +08:00
JSONObject jo = (JSONObject) obj;
Object parameter = jo.get("parameter");
DataScope ds = jo.getObject("ds", DataScope.class);
2024-04-23 20:01:26 +08:00
init(plainSelect);
2024-05-11 01:58:58 +08:00
//expressions
2024-04-23 20:01:26 +08:00
List<Expression> expressions = new ArrayList<>();
2024-05-05 22:34:36 +08:00
if (!DataScopeInterceptor.findIgnoreDataScope(parameter, ds)) {
if (user.getAccountType() == 6) {
List<String> filterEnterprises = getNeedFilterLeftExpression(plainSelect, getFieldEnterpriseTables(), ds);
if (CollUtil.isNotEmpty(filterEnterprises)) {
List<String> enterpriseIds = userEnterpriseService.getEnterpriseIdsIfSubProject();
for (String filterEnterprise : filterEnterprises) {
inExpression(filterEnterprise, enterpriseIds, plainSelect);
}
2024-04-28 21:51:06 +08:00
}
2024-05-05 22:34:36 +08:00
List<String> filterItems = getNeedFilterLeftExpression(plainSelect, getFieldVideoTables(), ds);
if (CollUtil.isNotEmpty(filterItems)) {
List<String> videoItems = userDevAuthorityService.getVideoItemsIfSubProject();
for (String item : filterItems) {
inExpression(item, videoItems, plainSelect);
}
2024-04-28 21:51:06 +08:00
}
2024-05-11 01:58:58 +08:00
List<String> filterAis = getNeedFilterLeftExpression(plainSelect, getFieldAiTables(), ds, true);
2024-05-06 18:43:30 +08:00
if (CollUtil.isNotEmpty(filterAis)) {
List<String> videoItems = aiAnalyseHardWareRecordService.getAiAnalyseHardIdsByUserId();
2024-05-11 01:58:58 +08:00
if (CollUtil.isEmpty(videoItems)) {
videoItems.add("0");
}
videoItems = videoItems.stream().map(s -> "'" + s + "'").collect(Collectors.toList());
for (String filterAi : filterAis) {
String sql = StrUtil.format(" ({}.hardware_id in ({}) OR ({}.quality_region_id in (select distinct quality_region_id from quality_region_to_user where user_id = {}))) ",
filterAi, StrUtil.join(",", videoItems), filterAi, SecurityUtils.getUser().getUserId());
Expression expression = null;
try {
expression = CCJSqlParserUtil.parseCondExpression(sql);
expressions.add(expression);
} catch (JSQLParserException e) {
log.error(e.getMessage(), e);
}
2024-05-06 18:43:30 +08:00
}
}
2024-05-05 22:34:36 +08:00
} else if (user.getAccountType() == 11) {
List<String> filterEnterprises = getNeedFilterLeftExpression(plainSelect, getFieldEnterpriseTables(), ds);
EnterpriseInfo ei = enterpriseInfoMapper.getXzSupplierByUserId(SecurityUtils.getUser().getUserId());
Long id;
if (ei == null) {
id = -1L;
} else {
id = ei.getId();
2024-04-23 20:01:26 +08:00
}
2024-05-05 22:34:36 +08:00
for (String filterEnterprise : filterEnterprises) {
String sql = StrUtil.format(" ({} = {} OR {} IN ( SELECT DISTINCT t.enterprise_id FROM " +
"(SELECT t.id FROM project_enterprise t WHERE t.enterprise_id = {}) t2 join project_enterprise t on find_in_set( t2.id, ancestors ) )) ",
filterEnterprise, id, filterEnterprise, id);
Expression expression = null;
try {
expression = CCJSqlParserUtil.parseCondExpression(sql);
expressions.add(expression);
} catch (JSQLParserException e) {
log.error(e.getMessage(), e);
}
2024-04-23 20:01:26 +08:00
}
2024-05-11 01:58:58 +08:00
}
if (expressions.size() > 0) {
2024-05-05 22:34:36 +08:00
Expression dataExpression;
if (expressions.size() > 1) {
//数据权限大于1个之间用或
OrExpression orExpression = new OrExpression(expressions.get(0), expressions.get(1));
for (int i = 2; i < expressions.size(); i++) {
orExpression = new OrExpression(orExpression, expressions.get(i));
}
// 数据权限使用单独的括号 防止与其他条件冲突
dataExpression = new Parenthesis(orExpression);
} else {
dataExpression = expressions.get(0);
}
Expression where = plainSelect.getWhere();
if (where != null) {
where = new AndExpression(where, dataExpression);
} else {
where = dataExpression;
}
plainSelect.setWhere(where);
2024-04-23 20:01:26 +08:00
}
2024-05-05 22:34:36 +08:00
}
2024-04-23 20:01:26 +08:00
2024-05-24 14:58:41 +08:00
if (!DataScopeInterceptor.isNotSqlTest()) {
String sql = " ('1qqq')";
try {
Expression expression = CCJSqlParserUtil.parseCondExpression(sql);
Expression where = plainSelect.getWhere();
if (where != null) {
where = new AndExpression(where, expression);
} else {
where = expression;
}
plainSelect.setWhere(where);
} catch (JSQLParserException e) {
throw new RuntimeException(e);
}
}
2024-04-23 20:01:26 +08:00
//List<String> scopeIds = systemUserDataScopeService.list(Wrappers.<SystemUserDataScope>lambdaQuery().eq(SystemUserDataScope::getUserId, user.getUserId()))
// .stream().map(u -> u.getRelevanceId()).collect(Collectors.toList());
//if (user.getAccountType() == 4) {
// if (scopeIds.size() > 0) {
// inExpression(getAliasColumn(plainSelect, getEngineeringSn()), scopeIds, plainSelect);
// } else {
// equalsTo(getAliasColumn(plainSelect, getProjectSn()), user.getSn(), plainSelect);
// }
//}
//if (user.getAccountType() == 3) {
// List<String> engineeringSns = scopeIds.size() > 0 ? scopeIds : engineeringService.getSnListByEnterprise(user.getSn());
// if (engineeringSns.size() == 0) {
// engineeringSns.add("0");
// }
// inExpression(getAliasColumn(plainSelect, getEngineeringSn()), engineeringSns, plainSelect);
//}
//if (user.getAccountType() == 2) {
// List<String> projectSns = projectService.getSnListForGov(user.getSn());
// if (projectSns.size() == 0) {
// projectSns.add("0");
// }
// inExpression(getAliasColumn(plainSelect, getProjectSn()), projectSns, plainSelect);
//}
return plainSelect;
}
2024-05-11 01:58:58 +08:00
/**
* 获取需要过滤的表别名或加字段
*
* @param plainSelect
* @param tables
* @param ds
* @param onlyAlas false表别名.字段 true表别名
* @return
*/
private List<String> getNeedFilterLeftExpression(PlainSelect plainSelect, Map<String, String> tables, DataScope ds, boolean onlyAlas) {
2024-04-23 20:01:26 +08:00
ArrayList<String> rtList = new ArrayList<>();
2024-04-24 01:15:10 +08:00
String[] dsArr = ds.includeTable();
if (dsArr.length > 0) {
Map<String, String> nt = new HashMap<>();
for (String ds1 : dsArr) {
if (tables.containsKey(ds1)) {
nt.put(ds1, tables.get(ds1));
}
}
tables = nt;
}
2024-04-23 20:01:26 +08:00
FromItem fromItem = plainSelect.getFromItem();
if (fromItem instanceof Table) {
Table table = (Table) fromItem;
String name = table.getName();
2024-04-24 01:15:10 +08:00
if (tables.get(name) != null) {
2024-04-23 21:48:10 +08:00
String aliasName = null;
Alias alias = table.getAlias();
if (alias != null) {
aliasName = alias.getName();
}
2024-05-11 01:58:58 +08:00
String e;
if (onlyAlas) {
e = (StringUtils.isEmpty(aliasName) ? name : aliasName);
} else {
e = (StringUtils.isEmpty(aliasName) ? name : aliasName) + "." + tables.get(name);
}
rtList.add(e);
2024-04-23 20:01:26 +08:00
}
}
List<Join> joins = plainSelect.getJoins();
//主表不是user表
if (!CollectionUtils.isEmpty(joins)) {
//判断join的表里有没有user表
for (Join join : joins) {
// 判断join里面是否存在user表不存在则新增
FromItem rightItem = join.getRightItem();
if (rightItem instanceof Table) {
Table joinTable = (Table) rightItem;
2024-04-24 01:15:10 +08:00
if (tables.get(joinTable.getName()) != null) {
2024-04-23 21:48:10 +08:00
String aliasName = null;
Alias alias = joinTable.getAlias();
if (alias != null) {
aliasName = alias.getName();
}
2024-05-11 01:58:58 +08:00
String e;
if (onlyAlas) {
e = (StringUtils.isEmpty(aliasName) ? joinTable.getName() : aliasName);
} else {
e = (StringUtils.isEmpty(aliasName) ? joinTable.getName() : aliasName) + "." + tables.get(joinTable.getName());
}
rtList.add(e);
2024-04-23 20:01:26 +08:00
}
}
}
}
return rtList;
2024-05-11 01:58:58 +08:00
}
private List<String> getNeedFilterLeftExpression(PlainSelect plainSelect, Map<String, String> tables, DataScope ds) {
return getNeedFilterLeftExpression(plainSelect, tables, ds, false);
2024-04-23 20:01:26 +08:00
}
//private PlainSelect dataScopeFilterByEnt(PlainSelect plainSelect, SecurityUser user) {
// init(plainSelect);
// if (user.getAccountType() == 3) {
// equalsTo(getAliasColumn(plainSelect, getEnterpriseSn()), user.getSn(), plainSelect);
// }
// if (user.getAccountType() == 2) {
// List<String> entSns = enterpriseService.getSnListForGov(user.getSn());
// if (entSns.size() == 0) {
// entSns.add("0");
// }
// inExpression(getAliasColumn(plainSelect, getEnterpriseSn()), entSns, plainSelect);
// }
// return plainSelect;
//}
private void equalsTo(String leftExpression, String rightExpression, PlainSelect plainSelect) {
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(new Column(leftExpression));
equalsTo.setRightExpression(new StringValue(rightExpression));
AndExpression andExpression = new AndExpression(plainSelect.getWhere(), equalsTo);
plainSelect.setWhere(andExpression);
}
private void inExpression(String leftExpression, List<String> rightExpression, PlainSelect plainSelect) {
InExpression inExpression = new InExpression();
ItemsList itemsList = new ExpressionList(rightExpression.stream().map(StringValue::new).collect(Collectors.toList()));
inExpression.setLeftExpression(new Column(leftExpression));
inExpression.setRightItemsList(itemsList);
AndExpression andExpression = new AndExpression(plainSelect.getWhere(), inExpression);
plainSelect.setWhere(andExpression);
}
private String getAliasColumn(PlainSelect plainSelect, String sn) {
FromItem fromItem = plainSelect.getFromItem();
Alias alias = fromItem.getAlias();
StringBuilder prefix = new StringBuilder();
if (alias != null) {
prefix.append(alias).append(".");
}
return prefix.append(sn).toString();
}
private void init(PlainSelect plainSelect) {
Expression envCondition = null;
try {
envCondition = CCJSqlParserUtil.parseCondExpression("1 == 1");
} catch (JSQLParserException e) {
2024-04-24 01:15:10 +08:00
log.error(e.getMessage(), e);
2024-04-23 20:01:26 +08:00
}
Expression where = plainSelect.getWhere();
if (where == null) {
plainSelect.setWhere(envCondition);
}
}
//protected void addParam(Insert insert, Object obj){
// SecurityUser user = SecurityUtil.getUser();
// if (user == null) {
// return;
// }
// List<Column> columns = insert.getColumns();
// if (CollectionUtils.isEmpty(columns)) {
// // 针对不给列名的insert 不处理
// return;
// }
// if (user.getAccountType() == 4 || user.getAccountType() == 3) {
// if (!columns.stream().anyMatch(c -> c.toString().equals(getProjectSn()))) {
// columns.add(new Column(getProjectSn()));
// if (insert.getItemsList() != null) {
// ItemsList itemsList = insert.getItemsList();
// if (itemsList instanceof MultiExpressionList) {
// ((MultiExpressionList) itemsList).getExprList().forEach(el -> el.getExpressions().add(getProjectSn(obj)));
// } else {
// ((ExpressionList) itemsList).getExpressions().add(getProjectSn(obj));
// }
// } else {
// throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId");
// }
// }
// }
//}
//protected Expression getProjectSn(Object engineeringSn){
// SecurityUser user = SecurityUtil.getUser();
// if (user.getAccountType() == 4) {
// return new StringValue(user.getSn());
// }
// if (user.getAccountType() == 3) {
// return new StringValue(engineeringService.getOne(Wrappers.<Engineering>lambdaQuery().eq(Engineering::getEngineeringSn, engineeringSn)).getProjectSn());
// }
// return null;
//}
}