天天看點

mybatis攔截器實作資料權限

作者:Java架構學習指南

前端的菜單和按鈕權限都可以通過配置來實作,但很多時候,背景查詢資料庫資料的權限需要通過手動添加SQL來實作。比如員工打卡記錄表,有id,name,dpt_id,company_id等字段,後兩個表示部門ID和分公司ID。檢視員工打卡記錄SQL為:select id,name,dpt_id,company_id from t_record

當一個總部賬号可以檢視全部資料此時,sql無需改變。因為他可以看到全部資料。當一個部門管理者權限員工檢視全部資料時,sql需要在末屬添加 where dpt_id = #{dpt_id}如果每個功能子產品都需要手動寫代碼去拿到目前登陸使用者的所屬部門,然後手動添加where條件,就顯得非常的繁瑣。

是以,可以通過mybatis的攔截器拿到查詢sql語句,再自動改寫sql。

mybatis 攔截器

MyBatis 允許你在映射語句執行過程中的某一點進行攔截調用。預設情況下,MyBatis 允許使用插件來攔截的方法調用包括:

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

這些類中方法的細節可以通過檢視每個方法的簽名來發現,或者直接檢視 MyBatis 發行包中的源代碼。 如果你想做的不僅僅是監控方法的調用,那麼你最好相當了解要重寫的方法的行為。 因為在試圖修改或重寫已有方法的行為時,很可能會破壞 MyBatis 的核心子產品。 這些都是更底層的類和方法,是以使用插件的時候要特别當心。

通過 MyBatis 提供的強大機制,使用插件是非常簡單的,隻需實作 Interceptor 接口,并指定想要攔截的方法簽名即可。

分頁插件pagehelper就是一個典型的通過攔截器去改寫SQL的。

mybatis攔截器實作資料權限

可以看到它通過注解 @Intercepts 和簽名 @Signature 來實作,攔截Executor執行器,攔截所有的query查詢類方法。

我們可以據此也實作自己的攔截器。

import com.skycomm.common.util.user.Cpip2UserDeptVo;
    import com.skycomm.common.util.user.Cpip2UserDeptVoUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.ibatis.cache.CacheKey;
    import org.apache.ibatis.executor.Executor;
    import org.apache.ibatis.mapping.BoundSql;
    import org.apache.ibatis.mapping.MappedStatement;
    import org.apache.ibatis.mapping.SqlSource;
    import org.apache.ibatis.plugin.Interceptor;
    import org.apache.ibatis.plugin.Intercepts;
    import org.apache.ibatis.plugin.Invocation;
    import org.apache.ibatis.plugin.Signature;
    import org.apache.ibatis.session.ResultHandler;
    import org.apache.ibatis.session.RowBounds;
    import org.springframework.stereotype.Component;
    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;

    import javax.servlet.http.HttpServletRequest;
    import java.lang.reflect.Method;

    @Component
    @Intercepts({
            @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
            @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
    })
    @Slf4j
    public class MySqlInterceptor implements Interceptor {

        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = invocation.getArgs()[1];
            BoundSql boundSql = statement.getBoundSql(parameter);
            String originalSql = boundSql.getSql();
            Object parameterObject = boundSql.getParameterObject();

            SqlLimit sqlLimit = isLimit(statement);
            if (sqlLimit == null) {
                return invocation.proceed();
            }

            RequestAttributes req = RequestContextHolder.getRequestAttributes();
            if (req == null) {
                return invocation.proceed();
            }

            //處理request
            HttpServletRequest request = ((ServletRequestAttributes) req).getRequest();
            Cpip2UserDeptVo userVo = Cpip2UserDeptVoUtil.getUserDeptInfo(request);
            String depId = userVo.getDeptId();

            String sql = addTenantCondition(originalSql, depId, sqlLimit.alis());
            log.info("原SQL:{}, 資料權限替換後的SQL:{}", originalSql, sql);
            BoundSql newBoundSql = new BoundSql(statement.getConfiguration(), sql, boundSql.getParameterMappings(), parameterObject);
            MappedStatement newStatement = copyFromMappedStatement(statement, new BoundSqlSqlSource(newBoundSql));
            invocation.getArgs()[0] = newStatement;
            return invocation.proceed();
        }

        /**
         * 重新拼接SQL
         */
        private String addTenantCondition(String originalSql, String depId, String alias) {
            String field = "dpt_id";
            if(StringUtils.isNoneBlank(alias)){
                field = alias + "." + field;
            }

            StringBuilder sb = new StringBuilder(originalSql);
            int index = sb.indexOf("where");
            if (index < 0) {
                sb.append(" where ") .append(field).append(" = ").append(depId);
            } else {
                sb.insert(index + 5, " " + field +" = " + depId + " and ");
            }
            return sb.toString();
        }

        private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
            MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
            builder.resource(ms.getResource());
            builder.fetchSize(ms.getFetchSize());
            builder.statementType(ms.getStatementType());
            builder.keyGenerator(ms.getKeyGenerator());
            builder.timeout(ms.getTimeout());
            builder.parameterMap(ms.getParameterMap());
            builder.resultMaps(ms.getResultMaps());
            builder.cache(ms.getCache());
            builder.useCache(ms.isUseCache());
            return builder.build();
        }


        /**
         * 通過注解判斷是否需要限制資料
         * @return
         */
        private SqlLimit isLimit(MappedStatement mappedStatement) {
            SqlLimit sqlLimit = null;
            try {
                String id = mappedStatement.getId();
                String className = id.substring(0, id.lastIndexOf("."));
                String methodName = id.substring(id.lastIndexOf(".") + 1, id.length());
                final Class<?> cls = Class.forName(className);
                final Method[] method = cls.getMethods();
                for (Method me : method) {
                    if (me.getName().equals(methodName) && me.isAnnotationPresent(SqlLimit.class)) {
                        sqlLimit = me.getAnnotation(SqlLimit.class);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sqlLimit;
        }


        public static class BoundSqlSqlSource implements SqlSource {

            private final BoundSql boundSql;

            public BoundSqlSqlSource(BoundSql boundSql) {
                this.boundSql = boundSql;
            }

            @Override
            public BoundSql getBoundSql(Object parameterObject) {
                return boundSql;
            }
        }
    }           

順便加了個注解 @SqlLimit,在mapper方法上加了此注解才進行資料權限過濾。

同時注解有兩個屬性,

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface SqlLimit {
    /**
     * sql表别名
     * @return
     */
    String alis() default "";

    /**
     * 通過此列名進行限制
     * @return
     */
    String columnName() default "";
}           

columnName表示通過此列名進行限制,一般來說一個系統,各表當中的此列是統一的,可以忽略。

alis用于标注sql表别名,如 針對sql select * from tablea as a left join tableb as b on a.id = b.id 進行改寫,如果不知道表别名,會直接在後面拼接 where dpt_id = #{dptId},

那此SQL就會錯誤的,通過别名 @SqlLimit(alis = "a") 就可以知道需要拼接的是 where a.dpt_id = #{dptId}

執行結果

原SQL:select * from person, 資料權限替換後的SQL:select * from person where dpt_id = 234

原SQL:select * from person where id > 1, 資料權限替換後的SQL:select * from person where dpt_id = 234 and id > 1

但是在使用PageHelper進行分頁的時候還是有問題。

mybatis攔截器實作資料權限

可以看到先執行了_COUNT方法也就是PageHelper,再執行了自定義的攔截器。

在我們的業務方法中注入SqlSessionFactory

@Autowired
@Lazy
private List<SqlSessionFactory> sqlSessionFactoryList;           
mybatis攔截器實作資料權限

PageInterceptor為1,自定義攔截器為0,跟order相反,PageInterceptor優先級更高,是以越先執行。

mybatis攔截器優先級

@Order

通過@Order控制PageInterceptor和MySqlInterceptor可行嗎?

mybatis攔截器實作資料權限

将MySqlInterceptor的加載優先級調到最高,但測試證明依然不行。

定義3個類

@Component
@Order(2)
public class OrderTest1 {

    @PostConstruct
    public void init(){
        System.out.println(" 00000 init");
    }
}           
@Component
@Order(1)
public class OrderTest2 {

    @PostConstruct
    public void init(){
        System.out.println(" 00001 init");
    }
}           
@Component
@Order(0)
public class OrderTest3 {

    @PostConstruct
    public void init(){
        System.out.println(" 00002 init");
    }
}           

OrderTest1,OrderTest2,OrderTest3的優先級從低到高。

順序預期的執行順序應該是相反的:

00002 init
00001 init
00000 init           

但事實上執行的順序是

00000 init
00001 init
00002 init           

@Order 不控制執行個體化順序,隻控制執行順序。 @Order 隻跟特定一些注解生效 如:@Compent @Service @Aspect … 不生效的如: @WebFilter

是以這裡達不到預期效果。

@Priority 類似,同樣不行。

@DependsOn

使用此注解将目前類将在依賴類執行個體化之後再執行執行個體化。

在MySqlInterceptor上标記@DependsOn("queryInterceptor")

mybatis攔截器實作資料權限

啟動報錯,這個時候queryInterceptor還沒有執行個體化對象。

@PostConstruct

@PostConstruct修飾的方法會在伺服器加載Servlet的時候運作,并且隻會被伺服器執行一次。在同一個類裡,執行順序為順序如下:Constructor > @Autowired > @PostConstruct。但它也不能保證不同類的執行順序。PageHelper的springboot start也是通過這個來初始化攔截器的。

mybatis攔截器實作資料權限

ApplicationRunner

在目前springboot容器加載完成後執行,那麼這個時候pagehelper的攔截器已經加入,在這個時候加入自定義攔截器,就能達到我們想要的效果。

仿照PageHelper來寫

@Component
public class InterceptRunner implements ApplicationRunner {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        MySqlInterceptor mybatisInterceptor = new MySqlInterceptor();
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            configuration.addInterceptor(mybatisInterceptor);
        }
    }
}           

再執行,可以看到自定義攔截器在攔截器鍊當中下标變為了1(優先級與order剛好相反)

mybatis攔截器實作資料權限

背景列印結果,達到了預期效果。

mybatis攔截器實作資料權限

繼續閱讀