1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
| import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.toolkit.PluginUtils; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.lyc.admin.oauth.service.SysUser; import com.lyc.admin.oauth.utils.SecurityUtils; import com.lyc.common.base.exception.HasNotAuthException; import com.lyc.common.base.utils.CurrentEntIdSearchContextHolder; import com.lyc.common.base.vo.EntierVO; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Alias; import net.sf.jsqlparser.expression.LongValue; import net.sf.jsqlparser.expression.operators.conditional.AndExpression; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SelectBody; import net.sf.jsqlparser.statement.select.SetOperationList; import net.sf.jsqlparser.statement.update.Update; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component;
import java.io.StringReader; import java.sql.Connection; import java.util.*; import java.util.stream.Collectors;
@Aspect @Slf4j @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) @Component public class UnitDataPermissionInterceptor implements Interceptor {
@Override public Object intercept(Invocation invocation) throws Throwable { SysUser sysUser = SecurityUtils.getUser(); if (sysUser == null) { return invocation.proceed(); }
DataScopeParam dataScopeParam = DataScopeParamContentHolder.get();
if (dataScopeParam != null) { dataScopeParam.setEntIdList(Optional.ofNullable(sysUser.getTierVos()).orElse(new ArrayList<>()).stream().map(EntierVO::getUnitIdList).flatMap(Collection::stream).collect(Collectors.toSet())); }
Set<Long> entIdList = CurrentEntIdSearchContextHolder.getEntIdList(); if (entIdList != null) { if (dataScopeParam == null) { dataScopeParam = new DataScopeParam("ent_id", entIdList, true, CollUtil.newArrayList("sys_file")); } else { Set<Long> permissionEntList = dataScopeParam.getEntIdList(); dataScopeParam.setFilterField(true); dataScopeParam.setEntIdList(entIdList.stream().filter(permissionEntList::contains).collect(Collectors.toSet())); } }
if (dataScopeParam == null) { return invocation.proceed(); }
if (!dataScopeParam.isFilterField()) { return invocation.proceed(); }
StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget()); MetaObject metaObject = SystemMetaObject.forObject(statementHandler); MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); if (SqlCommandType.FLUSH.equals(mappedStatement.getSqlCommandType()) || SqlCommandType.UNKNOWN.equals(mappedStatement.getSqlCommandType())) { return invocation.proceed(); }
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql"); String originalSql = boundSql.getSql(); Object parameterObject = boundSql.getParameterObject(); if (SqlCommandType.INSERT.equals(mappedStatement.getSqlCommandType())) { if (parameterObject != null) { Long entId = Convert.toLong(ReflectUtil.getFieldValue(parameterObject, StrUtil.toCamelCase(dataScopeParam.getUnitField()))); if (entId != null && !dataScopeParam.getEntIdList().contains(entId)) { throw new HasNotAuthException(); } } return invocation.proceed(); } if (SqlCommandType.UPDATE.equals(mappedStatement.getSqlCommandType())) { String updateSql = handleUpdateSql(originalSql, dataScopeParam.getEntIdList(), dataScopeParam.getUnitField(), dataScopeParam.getIgnoreTables()); log.warn("数据权限处理过后UPDATE的SQL: {}", updateSql); metaObject.setValue("delegate.boundSql.sql", updateSql); return invocation.proceed(); } String finalSql = this.handleSql(originalSql, dataScopeParam.getEntIdList(), dataScopeParam.getUnitField(), dataScopeParam.getIgnoreTables()); log.warn("数据权限处理过后SELECT的SQL: {}", finalSql);
metaObject.setValue("delegate.boundSql.sql", finalSql); return invocation.proceed(); }
private String handleSql(String originalSql, Set<Long> entIdList, String fieldName, List<String> ignores) throws JSQLParserException { CCJSqlParserManager parserManager = new CCJSqlParserManager(); Select select = (Select) parserManager.parse(new StringReader(originalSql)); SelectBody selectBody = select.getSelectBody(); if (selectBody instanceof PlainSelect) { this.setWhere((PlainSelect) selectBody, entIdList, fieldName, ignores); } else if (selectBody instanceof SetOperationList) { SetOperationList setOperationList = (SetOperationList) selectBody; List<SelectBody> selectBodyList = setOperationList.getSelects(); selectBodyList.forEach(s -> this.setWhere((PlainSelect) s, entIdList, fieldName, ignores)); } return select.toString(); }
private String handleUpdateSql(String originalSql, Set<Long> entIdList, String fieldName, List<String> ignores) throws JSQLParserException { CCJSqlParserManager parserManager = new CCJSqlParserManager(); Update update = (Update) parserManager.parse(new StringReader(originalSql)); if (ignores.contains(update.getTable().getName())) { return originalSql; } String dataPermissionSql; if (entIdList.size() == 1) { EqualsTo selfEqualsTo = new EqualsTo(); selfEqualsTo.setLeftExpression(new Column(fieldName)); selfEqualsTo.setRightExpression(new LongValue(entIdList.stream().findFirst().orElse(0L))); dataPermissionSql = selfEqualsTo.toString(); } else { dataPermissionSql = fieldName + " in ( " + CollUtil.join(entIdList, StringPool.COMMA) + " )"; } update.setWhere(new AndExpression(update.getWhere(), CCJSqlParserUtil.parseCondExpression(dataPermissionSql))); return update.toString(); }
@SneakyThrows(Exception.class) protected void setWhere(PlainSelect plainSelect, Set<Long> entIdList, String fieldName, List<String> ignores) { Table fromItem = (Table) plainSelect.getFromItem(); Alias fromItemAlias = fromItem.getAlias(); if (ignores.contains(fromItem.getName())) { return; } String mainTableName = fromItemAlias == null ? fromItem.getName() : fromItemAlias.getName(); String dataPermissionSql; if (entIdList.size() == 1) { EqualsTo selfEqualsTo = new EqualsTo(); selfEqualsTo.setLeftExpression(new Column(mainTableName + "." + fieldName)); selfEqualsTo.setRightExpression(new LongValue(entIdList.stream().findFirst().orElse(0L))); dataPermissionSql = selfEqualsTo.toString(); } else if (entIdList.size() < 1) { dataPermissionSql = mainTableName + "." + fieldName + " in ( " + StringPool.NULL + " )"; } else { dataPermissionSql = mainTableName + "." + fieldName + " in ( " + CollUtil.join(entIdList, StringPool.COMMA) + " )"; }
if (plainSelect.getWhere() == null) { plainSelect.setWhere(CCJSqlParserUtil.parseCondExpression(dataPermissionSql)); } else { plainSelect.setWhere(new AndExpression(plainSelect.getWhere(), CCJSqlParserUtil.parseCondExpression(dataPermissionSql))); } }
@Override public Object plugin(Object target) { if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } return target; }
@Override public void setProperties(Properties properties) { log.info(properties.toString()); } }
|