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

683 lines
32 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-11-09 15:29:25 +08:00
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
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-08-16 18:33:47 +08:00
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
2024-11-09 15:29:25 +08:00
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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-11-09 15:29:25 +08:00
import com.zhgd.jeecg.common.util.SpringContextUtils;
2024-10-11 18:07:54 +08:00
import com.zhgd.xmgl.modules.baotou.entity.UserDevice;
2024-11-08 19:42:48 +08:00
import com.zhgd.xmgl.modules.baotou.service.IUserDevGroupService;
2024-10-11 18:07:54 +08:00
import com.zhgd.xmgl.modules.baotou.service.IUserDeviceService;
2024-08-16 18:33:47 +08:00
import com.zhgd.xmgl.modules.basicdata.entity.SystemUser;
2024-07-09 16:42:03 +08:00
import com.zhgd.xmgl.modules.basicdata.enums.SystemUserAccountTypeEnum;
2024-08-16 18:33:47 +08:00
import com.zhgd.xmgl.modules.basicdata.service.ISystemUserService;
2024-11-09 15:29:25 +08:00
import com.zhgd.xmgl.modules.car.mapper.CarCameraMapper;
2024-08-16 18:33:47 +08:00
import com.zhgd.xmgl.modules.project.entity.ProjectConfig;
import com.zhgd.xmgl.modules.project.service.IProjectConfigService;
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.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-11-09 15:29:25 +08:00
import com.zhgd.xmgl.util.MapBuilder;
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;
2024-11-09 15:29:25 +08:00
import org.apache.commons.collections.MapUtils;
2024-04-23 20:01:26 +08:00
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
2024-11-09 15:29:25 +08:00
import java.lang.reflect.Method;
2024-07-13 17:42:35 +08:00
import java.util.*;
2024-04-23 20:01:26 +08:00
import java.util.stream.Collectors;
@Slf4j
public class DataScopeHandler implements DataPermissionHandler {
2024-11-09 15:29:25 +08:00
public static final String DATA_FIELD = "dataField";
public static final String DEV_FIELD = "devField";
public static final String DEV_MAPPER = "dev_mapper";
public static final String ALIAS_NAME = "aliasName";
@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;
2024-08-16 18:33:47 +08:00
@Lazy
@Autowired
private IProjectConfigService projectConfigService;
@Lazy
@Autowired
private ISystemUserService systemUserService;
2024-10-11 18:07:54 +08:00
//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;
//}
@Lazy
@Autowired
private IUserDeviceService userDeviceService;
2024-11-08 19:42:48 +08:00
@Lazy
@Autowired
private IUserDevGroupService userDevGroupService;
2024-04-23 20:01:26 +08:00
@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() {
2024-07-03 16:11:21 +08:00
HashMap<String, String> tables = new HashMap<>(16);
2024-10-18 19:29:50 +08:00
tables.put("worker_admission", "certificate_issuing_unit");
2024-04-24 01:15:10 +08:00
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");
2024-06-05 21:47:58 +08:00
tables.put("dangerous_engineering_record", "responsibility_company_id");
2024-06-27 10:07:05 +08:00
tables.put("project_fine_record", "enterprise_id");
tables.put("car_info", "enterprise_id");
tables.put("enterprise_info", "id");
tables.put("quality_problem", "enterprise_id");
tables.put("civilize_construction", "enterprise_id");
2024-04-24 01:15:10 +08:00
return tables;
2024-04-23 20:01:26 +08:00
}
private HashMap<String, String> getFieldEnterpriseIdsTables() {
HashMap<String, String> tables = new HashMap<>(16);
tables.put("video_item", "enterprise_ids");
tables.put("ai_analyse_hard_ware_record", "enterprise_ids");
tables.put("car_camera", "enterprise_ids");
tables.put("hang_basket_dev", "enterprise_ids");
tables.put("deep_excavation_engineering", "enterprise_ids");
tables.put("high_formwork_plane_figure", "enterprise_ids");
tables.put("high_formwork_measure_point", "enterprise_ids");
tables.put("tower", "enterprise_ids");
tables.put("safety_hat_dev", "enterprise_ids");
tables.put("concrete_monitor_dev", "enterprise_ids");
tables.put("environment_dev", "enterprise_ids");
tables.put("poisonous_gas_dev", "enterprise_ids");
tables.put("uface_dev", "enterprise_ids");
// tables.put("anti_pressure_fold_dev", "enterprise_ids");
// tables.put("bridge_erect_machine_dev", "enterprise_ids");
// tables.put("car_wash_dev", "enterprise_ids");
// tables.put("concrete_mix_station_dev", "enterprise_ids");
// tables.put("discharging_platform_dev", "enterprise_ids");
// tables.put("double_carbon_dev", "enterprise_ids");
// tables.put("electrical_dev", "enterprise_ids");
// tables.put("frontier_protection_dev", "enterprise_ids");
// tables.put("frontier_protection_no_net_dev", "enterprise_ids");
// tables.put("gt_material_device", "enterprise_ids");
// tables.put("high_formwork_measure_device", "enterprise_ids");
// tables.put("mass_rebound_measure_dev", "enterprise_ids");
// tables.put("ms_mixed_soil_dev", "enterprise_ids");
// tables.put("pave_compaction_dev", "enterprise_ids");
// tables.put("pave_dev", "enterprise_ids");
// tables.put("photovoltaic_power_dev", "enterprise_ids");
// tables.put("pitch_mix_station_dev", "enterprise_ids");
// tables.put("pressure_test_machine_dev", "enterprise_ids");
// tables.put("sewage_dev", "enterprise_ids");
// tables.put("smart_grout_dev", "enterprise_ids");
// tables.put("smart_tension_dev", "enterprise_ids");
// tables.put("smoke_dev", "enterprise_ids");
// tables.put("spray_dev", "enterprise_ids");
// tables.put("spray_rt_dev", "enterprise_ids");
// tables.put("stable_water_mix_station_dev", "enterprise_ids");
// tables.put("standard_dev", "enterprise_ids");
// tables.put("universal_test_dev", "enterprise_ids");
// tables.put("vehicle_position_dev", "enterprise_ids");
return tables;
}
2024-04-28 21:51:06 +08:00
private HashMap<String, String> getFieldVideoTables() {
2024-07-03 16:11:21 +08:00
HashMap<String, String> tables = new HashMap<>(16);
2024-04-28 21:51:06 +08:00
tables.put("video_item", "item_id");
return tables;
}
2024-11-09 15:29:25 +08:00
private HashMap<String, Map<String, Object>> getFieldEnterpriseDataTables() {
HashMap<String, Map<String, Object>> tables = new HashMap<>(16);
2024-11-09 20:08:53 +08:00
tables.put("car_pass_record", new MapBuilder<String, Object>().put(DATA_FIELD, "camera_id").put(DEV_FIELD, "cameraId").put(DEV_MAPPER, CarCameraMapper.class).build());
2024-11-09 15:29:25 +08:00
return tables;
}
2024-11-08 19:42:48 +08:00
/**
* 项目组
*
* @return
*/
private HashMap<String, String> getFieldGroupsTables() {
HashMap<String, String> tables = new HashMap<>(16);
tables.put("danger_environment_evaluate", "project_group_id");
return tables;
}
/**
* 装置
*
* @return
*/
private HashMap<String, String> getFieldDevUnitTables() {
HashMap<String, String> tables = new HashMap<>(16);
tables.put("danger_environment_evaluate", "device_id");
return tables;
}
2024-05-06 18:43:30 +08:00
private HashMap<String, String> getFieldAiTables() {
2024-07-03 16:11:21 +08:00
HashMap<String, String> tables = new HashMap<>(16);
2024-08-16 18:33:47 +08:00
tables.put("ai_analyse_hard_ware_alarm_record", "hardware_id");
2024-05-06 18:43:30 +08:00
return tables;
}
2024-10-11 18:07:54 +08:00
private HashMap<String, String> getFieldSecurityTables() {
HashMap<String, String> tables = new HashMap<>(16);
tables.put("xz_security_quality_inspection_record", "device_unit_id");
tables.put("quality_problem", "device_id");
tables.put("civilize_construction", "device_id");
2024-10-11 18:07:54 +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)) {
2024-11-08 19:42:48 +08:00
//项目子账号
2024-07-13 17:42:35 +08:00
if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.PROJECT_SUB_ACCOUNT.getValue())) {
2024-05-05 22:34:36 +08:00
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-11-09 15:29:25 +08:00
//合作单位ids设备
2024-10-11 18:07:54 +08:00
//and (FIND_IN_SET(100,xxx.enterprise_ids) or FIND_IN_SET(102,xxx.enterprise_ids))
2024-11-09 15:29:25 +08:00
List<String> filterEnterpriseIds = getNeedFilterLeftExpression(plainSelect, this.getFieldEnterpriseIdsTables(), ds);
2024-10-11 18:07:54 +08:00
if (CollUtil.isNotEmpty(filterEnterpriseIds)) {
List<String> enterpriseIds = userEnterpriseService.getEnterpriseIdsIfSubProject();
2024-11-09 20:08:53 +08:00
// SystemUser su = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUserId, SecurityUtils.getUser().getUserId()));
2024-10-11 18:07:54 +08:00
for (String filterEnterpriseId : filterEnterpriseIds) {
List<String> list1 = enterpriseIds.stream().map(s -> "FIND_IN_SET(" + s + "," + filterEnterpriseId + ")").collect(Collectors.toList());
String s1 = StrUtil.join(" or ", list1);
2024-11-09 20:08:53 +08:00
String sql = " (" + s1 + ")";
2024-10-11 18:07:54 +08:00
Expression expression = null;
try {
expression = CCJSqlParserUtil.parseCondExpression(sql);
expressions.add(expression);
} catch (JSQLParserException e) {
log.error("", e);
}
}
}
2024-11-09 15:29:25 +08:00
//合作单位ids数据
2024-11-09 20:08:53 +08:00
List<Map<String, Object>> devIdNames = getNeedFilterLeftExpression(plainSelect, ds, this.getFieldEnterpriseDataTables());
if (CollUtil.isNotEmpty(devIdNames)) {
for (Map<String, Object> item : devIdNames) {
String aliasName = MapUtils.getString(item, ALIAS_NAME);
String fieldName = MapUtils.getString(item, DEV_FIELD);
Class clz = (Class) item.get(DEV_MAPPER);
Object mapperObj = SpringContextUtils.getBean(clz);
Method selectListMethod = ReflectUtil.getMethod(mapperObj.getClass(), "selectList", QueryWrapper.class);
Object queryResult = ReflectUtil.invoke(mapperObj, selectListMethod, Wrappers.query());
List<Object> list = (List) queryResult;
List<String> fieldVals = list.stream().map(o -> Convert.toStr(ReflectUtil.getFieldValue(o, fieldName))).collect(Collectors.toList());
if (CollUtil.isEmpty(fieldVals)) {
fieldVals.add("-1");
}
inExpression(aliasName, fieldVals, plainSelect);
}
}
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)) {
2024-08-16 18:33:47 +08:00
SystemUser su = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUserId, SecurityUtils.getUser().getUserId()));
ProjectConfig projectConfig = projectConfigService.getProjectConfigByProjectSn(su.getSn());
2024-11-08 19:42:48 +08:00
if (projectConfig != null && Objects.equals(projectConfig.getIsEnableRegionEnterprise(), 1)) {
2024-08-16 18:33:47 +08:00
List<String> videoItems = aiAnalyseHardWareRecordService.getAiAnalyseHardIdsByUserId();
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-11 01:58:58 +08:00
}
2024-05-06 18:43:30 +08:00
}
}
2024-10-11 18:07:54 +08:00
//安全管理的装置筛选
List<String> filterSecuritys = getNeedFilterLeftExpression(plainSelect, getFieldSecurityTables(), ds);
if (CollUtil.isNotEmpty(filterSecuritys)) {
List<String> deviceIds = userDeviceService.list(new LambdaQueryWrapper<UserDevice>()
.eq(UserDevice::getUserId, SecurityUtils.getUser().getUserId())).stream().map(userDevice -> {
return userDevice.getDeviceId() + "";
}).collect(Collectors.toList());
if (CollUtil.isEmpty(deviceIds)) {
deviceIds.add("-1");
2024-05-05 22:34:36 +08:00
}
2024-10-11 18:07:54 +08:00
for (String filterEnterprise : filterSecuritys) {
inExpression(filterEnterprise, deviceIds, plainSelect);
2024-06-17 19:13:42 +08:00
}
}
2024-11-08 19:42:48 +08:00
//项目组权限
List<String> groupNames = getNeedFilterLeftExpression(plainSelect, this.getFieldGroupsTables(), ds);
if (CollUtil.isNotEmpty(groupNames)) {
List<String> groupIds = userDevGroupService.getGroupIds();
for (String item : groupNames) {
inExpression(item, groupIds, plainSelect);
}
}
//装置权限
List<String> unitNames = getNeedFilterLeftExpression(plainSelect, this.getFieldDevUnitTables(), ds);
if (CollUtil.isNotEmpty(unitNames)) {
List<String> unitIds = userDevGroupService.getUnitIds();
for (String item : unitNames) {
inExpression(item, unitIds, plainSelect);
}
}
2024-05-11 01:58:58 +08:00
}
2024-10-11 18:07:54 +08:00
// else if (Objects.equals(user.getAccountType(), SystemUserAccountTypeEnum.SUPPLIER.getValue())) {
// 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();
// }
// 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);
// }
// }
//
// //解析ai预警
// List<String> filterAis = getNeedFilterLeftExpression(plainSelect, getFieldAiTables(), ds, true);
// if (CollUtil.isNotEmpty(filterAis)) {
// List<String> videoItems = aiAnalyseHardWareRecordService.getAiAnalyseHardIdsByEnterpriseId(id);
// 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-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));
2024-07-19 18:26:48 +08:00
int i1 = 2;
for (int i = i1; i < expressions.size(); i++) {
2024-05-05 22:34:36 +08:00
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
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) {
2024-07-03 16:11:21 +08:00
Map<String, String> nt = new HashMap<>(16);
2024-04-24 01:15:10 +08:00
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
}
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;
//}
2024-10-11 18:07:54 +08:00
private List<String> getNeedFilterLeftExpression(PlainSelect plainSelect, Map<String, String> tables, DataScope ds) {
return getNeedFilterLeftExpression(plainSelect, tables, ds, false);
}
2024-11-09 15:29:25 +08:00
private List<Map<String ,Object>> getNeedFilterLeftExpression(PlainSelect plainSelect, DataScope ds, Map<String, Map<String, Object>> param) {
ArrayList<Map<String ,Object>> rtList = new ArrayList<>();
String[] dsArr = ds.includeTable();
if (dsArr.length > 0) {
Map<String, Map<String ,Object>> nt = new HashMap<>(16);
for (String ds1 : dsArr) {
if (param.containsKey(ds1)) {
nt.put(ds1, param.get(ds1));
}
}
param = nt;
}
FromItem fromItem = plainSelect.getFromItem();
if (fromItem instanceof Table) {
Table table = (Table) fromItem;
String name = table.getName();
if (param.get(name) != null) {
String aliasName = null;
Alias alias = table.getAlias();
if (alias != null) {
aliasName = alias.getName();
}
Map<String, Object> map = param.get(name);
String e = (StringUtils.isEmpty(aliasName) ? name : aliasName) + "." + map.get(DATA_FIELD).toString();
map.put(ALIAS_NAME, e);
rtList.add(map);
}
}
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;
if (param.get(joinTable.getName()) != null) {
String aliasName = null;
Alias alias = joinTable.getAlias();
if (alias != null) {
aliasName = alias.getName();
}
Map<String, Object> map = param.get(aliasName);
String e = (StringUtils.isEmpty(aliasName) ? joinTable.getName() : aliasName) + "." + param.get(aliasName).get(DATA_FIELD).toString();
map.put(ALIAS_NAME, e);
rtList.add(map);
}
}
}
}
return rtList;
}
2024-04-23 20:01:26 +08:00
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();
}
//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");
// }
// }
// }
//}
2024-10-11 18:07:54 +08:00
private void init(PlainSelect plainSelect) {
Expression envCondition = null;
try {
envCondition = CCJSqlParserUtil.parseCondExpression("1 == 1");
} catch (JSQLParserException e) {
log.error(e.getMessage(), e);
}
Expression where = plainSelect.getWhere();
if (where == null) {
plainSelect.setWhere(envCondition);
}
}
2024-04-23 20:01:26 +08:00
}