xiejun
2024-11-01 80b6cbfc9c861469146318d0b3dd5f8b8b525b8a
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
/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.core.datascope.interceptor;
 
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springblade.core.datascope.annotation.DataAuth;
import org.springblade.core.datascope.handler.DataScopeHandler;
import org.springblade.core.datascope.model.DataScopeModel;
import org.springblade.core.datascope.props.DataScopeProperties;
import org.springblade.core.mp.intercept.QueryInterceptor;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.ClassUtil;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.core.tool.utils.StringUtil;
 
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
 
 
/**
 * mybatis 数据权限拦截器
 *
 * @author L.cm, Chill
 */
@Slf4j
@RequiredArgsConstructor
@SuppressWarnings({"rawtypes"})
public class DataScopeInterceptor implements QueryInterceptor {
 
    private final ConcurrentMap<String, DataAuth> dataAuthMap = new ConcurrentHashMap<>(8);
 
    private final DataScopeHandler dataScopeHandler;
    private final DataScopeProperties dataScopeProperties;
 
    @Override
    public void intercept(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        //未启用则放行
        if (!dataScopeProperties.getEnabled()) {
            return;
        }
 
        //未取到用户则放行
        BladeUser bladeUser = AuthUtil.getUser();
        if (bladeUser == null) {
            return;
        }
 
        if (SqlCommandType.SELECT != ms.getSqlCommandType() || StatementType.CALLABLE == ms.getStatementType()) {
            return;
        }
 
        String originalSql = boundSql.getSql();
 
        //查找注解中包含DataAuth类型的参数
        DataAuth dataAuth = findDataAuthAnnotation(ms);
 
        //注解为空并且数据权限方法名未匹配到,则放行
        String mapperId = ms.getId();
        String className = mapperId.substring(0, mapperId.lastIndexOf(StringPool.DOT));
        String mapperName = ClassUtil.getShortName(className);
        String methodName = mapperId.substring(mapperId.lastIndexOf(StringPool.DOT) + 1);
        boolean mapperSkip = dataScopeProperties.getMapperKey().stream().noneMatch(methodName::contains)
            || dataScopeProperties.getMapperExclude().stream().anyMatch(mapperName::contains);
        if (dataAuth == null && mapperSkip) {
            return;
        }
 
        //创建数据权限模型
        DataScopeModel dataScope = new DataScopeModel();
 
        //若注解不为空,则配置注解项
        if (dataAuth != null) {
            dataScope.setResourceCode(dataAuth.code());
            dataScope.setScopeColumn(dataAuth.column());
            dataScope.setScopeType(dataAuth.type().getType());
            dataScope.setScopeField(dataAuth.field());
            dataScope.setScopeValue(dataAuth.value());
        }
 
        //获取数据权限规则对应的筛选Sql
        String sqlCondition = dataScopeHandler.sqlCondition(mapperId, dataScope, bladeUser, originalSql);
        if (!StringUtil.isBlank(sqlCondition)) {
            PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
            mpBoundSql.sql(sqlCondition);
        }
    }
 
    /**
     * 获取数据权限注解信息
     *
     * @param mappedStatement mappedStatement
     * @return DataAuth
     */
    private DataAuth findDataAuthAnnotation(MappedStatement mappedStatement) {
        String id = mappedStatement.getId();
        return dataAuthMap.computeIfAbsent(id, (key) -> {
            String className = key.substring(0, key.lastIndexOf(StringPool.DOT));
            String mapperBean = StringUtil.firstCharToLower(ClassUtil.getShortName(className));
            Object mapper = SpringUtil.getBean(mapperBean);
            String methodName = key.substring(key.lastIndexOf(StringPool.DOT) + 1);
            Class<?>[] interfaces = ClassUtil.getAllInterfaces(mapper);
            for (Class<?> mapperInterface : interfaces) {
                for (Method method : mapperInterface.getDeclaredMethods()) {
                    if (methodName.equals(method.getName()) && method.isAnnotationPresent(DataAuth.class)) {
                        return method.getAnnotation(DataAuth.class);
                    }
                }
            }
            return null;
        });
    }
 
}