栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis拦截器实现数据权限

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis拦截器实现数据权限

package com.tcl.tg.hrsp.config.config;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.MapUtils;
import com.tcl.core.convertor.ApplicationContextHelper;
import com.tcl.core.domain.PageInfo;
import com.tcl.core.oauth.CustomUserDetails;
import com.tcl.core.oauth.DetailsHelper;
import com.tcl.mybatis.pagehelper.domain.Sort;
import com.tcl.mybatis.pagehelper.page.PageMethod;
import com.tcl.tg.hrsp.config.common.annotation.DataAuth;
import com.tcl.tg.hrsp.config.constants.BaseConstant;
import com.tcl.tg.hrsp.config.dto.HrOrgDeptViewDTO;
import com.tcl.tg.hrsp.config.dto.HrSysDimensionDTO;
import com.tcl.tg.hrsp.config.entity.HrEyasMainForm;
import com.tcl.tg.hrsp.config.service.HrEyasMainFormService;
import com.tcl.tg.hrsp.config.service.HrOrgDeptTService;
import com.tcl.tg.hrsp.config.service.HrSysScopeTService;
import com.tcl.tg.hrsp.config.util.SpringContextHolder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.StringJoiner;
import java.util.stream.Collectors;


@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}),
        }
)
public class DataAuthInterceptor implements Interceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextHelper.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (invocation.getTarget() instanceof Executor) {
            LOGGER.info("MyBatisInterceptor==>新增数据权限");
            return addDataAuth(invocation);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    
    private Object addDataAuth(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        //由于逻辑关系,只会进入一次
        if (args.length == 4) {
            //4 个参数时
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            //6 个参数时
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        // 如果sql类型是查询
        if (ms.getSqlCommandType() == SqlCommandType.SELECt) {
            String id = ms.getId();
            String className = id.substring(0, id.lastIndexOf("."));
            String methodName = id.substring(id.lastIndexOf(".") + 1);
            Class aClass = Class.forName(className);
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                declaredMethod.setAccessible(true);
                String name = declaredMethod.getName();
                //方法名相同,并且注解是DataAuth
                if (methodName.equals(name) && declaredMethod.isAnnotationPresent(DataAuth.class)) {
                    DataAuth annotation = declaredMethod.getAnnotation(DataAuth.class);
                    Object object = boundSql.getParameterObject();
                    String key = getKey(object, annotation);
                    if (StringUtils.isBlank(key)) {
                        continue;
                    }
                    //获取到原始sql语句
                    String sql = boundSql.getSql();
                    if (StringUtils.isBlank(sql)) {
                        continue;
                    }
                    PageInfo pageInfo = PageMethod.getLocalPage();
                    Sort sort = PageMethod.getLocalSort();
                    PageMethod.clearSort();
                    PageMethod.clearPage();
                    //通过反射修改sql语句
                    Field field = boundSql.getClass().getDeclaredField("sql");
                    field.setAccessible(true);
                    String dbDeptField = annotation.dbDeptField();
                    String newSql = getNewSql(getSql(sql, dbDeptField), key, annotation);
                    field.set(boundSql, newSql);
                    //设置分页参数
                    setPageInfo(pageInfo, sort);
                }
            }
        }
        return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
    }

    private SQL getSql(String sql, String dbDeptField) {
        return new SQL()
                .SELECT("*")
                .FROM("(" + sql + ") HRSP_AUTH")
                .LEFT_OUTER_JOIN("HR_ORG_DEPT_VIEW odv ON odv.FD_DEPT_CODE = HRSP_AUTH." + dbDeptField);
    }

    
    private void setPageInfo(PageInfo pageInfo, Sort sort) throws Throwable {
        //获取设置Page参数的私有方法
        Method setPageMethod = PageMethod.class.getDeclaredMethod("setLocalPage", PageInfo.class);
        setPageMethod.setAccessible(true);
        setPageMethod.invoke(setPageMethod, pageInfo);
        //获取设置Sort参数的私有方法
        Method setSortMethod = PageMethod.class.getDeclaredMethod("setLocalSort", Sort.class);
        setSortMethod.setAccessible(true);
        setSortMethod.invoke(setSortMethod, sort);
    }

    
    private String getKey(Object object, DataAuth annotation) {
        if (Objects.isNull(object) || Objects.isNull(annotation)) {
            return null;
        }
        String key = annotation.moduleAttributeKey();
        if (StringUtils.isBlank(key)) {
            return null;
        }
        String jsonStr = JSONObject.toJSONString(object);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Object value = jsonObject.get(key);
        if (Objects.nonNull(value)) {
            return value.toString();
        }
        Iterator iterator = jsonObject.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry entry = (Entry) iterator.next();
            Object strObject = entry.getValue();
            if (Objects.isNull(strObject)) {
                continue;
            }
            if (JSONObject.isValidObject(strObject.toString())) {
                value = getKey(strObject, annotation);
                if (Objects.nonNull(value)) {
                    return value.toString();
                }
            }
        }
        return null;
    }

    
    private String getNewSql(SQL sql, String key, DataAuth annotation) {
        String dbModelField = annotation.dbModelField();
        String dbCenterField = annotation.dbCenterField();
        String dbDeptField = annotation.dbDeptField();
        //1. 获取登录用户数据范围
        Map> scopeListMap = getUserScopeList(key);
        if (MapUtils.isEmpty(scopeListMap)) {
            sql.WHERe("1 = 2");
            return sql.toString();
        }
        String strSql = sql.toString();
        HrOrgDeptTService hrOrgDeptTService = (HrOrgDeptTService) SpringContextHolder
                .getObject(HrOrgDeptTService.class);
        //2. 拼接sql
        for (Entry> entry : scopeListMap.entrySet()) {
            List list = entry.getValue();
            boolean isOr = true;
            for (HrSysDimensionDTO hrSysDimensionDTO : list) {
                String value = hrSysDimensionDTO.getValue();
                String dimensionCode = hrSysDimensionDTO.getDimensionCode();
                if (isContinue(value, dimensionCode)) {
                    continue;
                }
                value = value.replaceAll(",", "','");
                if (StringUtils.isNotBlank(dbModelField) && strSql.contains(dbModelField) && "model_code"
                        .equals(dimensionCode)) {
                    if (isOr) {
                        sql.OR();
                        isOr = false;
                    }
                    sql.WHERe(" HRSP_AUTH." + dbModelField + " IN('" + value + "')");
                }
                if (StringUtils.isNotBlank(dbCenterField) && strSql.contains(dbCenterField) && "center_code"
                        .equals(dimensionCode)) {
                    if (isOr) {
                        sql.OR();
                        isOr = false;
                    }
                    sql.WHERe(" HRSP_AUTH." + dbCenterField + " IN('" + value + "')");
                }
                if (StringUtils.isNotBlank(dbDeptField) && strSql.contains(dbDeptField) && "dept_code"
                        .equals(dimensionCode)) {
                    List orgList = hrOrgDeptTService.selectCurrentDepts(hrSysDimensionDTO.getValue());
                    if (CollectionUtils.isEmpty(orgList)) {
                        continue;
                    }
                    StringJoiner sj = new StringJoiner("OR", "(", ")");
                    for (HrOrgDeptViewDTO hrOrgDeptViewDTO : orgList) {
                        sj.add(" odv.PARENT_CODE" + hrOrgDeptViewDTO.getFdDeptLevel() + " = '" + hrOrgDeptViewDTO
                                .getFdDeptCode() + "'");
                    }
                    if (isOr) {
                        sql.OR();
                        isOr = false;
                    }
                    sql.WHERe(sj.toString());
                }
            }
        }
        return sql.toString();

    }


    
    private boolean isContinue(String value, String dimensionCode) {
        if (value.equalsIgnoreCase(BaseConstant.SCOPE_ALL)) {
            return true;
        }
        if (BaseConstant.SCOPE_DEPT_CODE.equals(dimensionCode) && value
                .contains(BaseConstant.TCL_TOP_CODE)) {
            return true;
        }
        return false;
    }

    
    private Map> getUserScopeList(String key) {
        //获取当前登录用户
        CustomUserDetails details = DetailsHelper.getUserDetails();
        if (Objects.isNull(details)) {
            LOGGER.info("获取登录用户失败==>details:{}", details);
            return null;
        }
        HrSysScopeTService hrSysScopeTService = (HrSysScopeTService) SpringContextHolder
                .getObject(HrSysScopeTService.class);
        //获取当前登录用户的数据范围
        List scopeList = hrSysScopeTService.selectListByLoginName(details.getUsername());
        if (CollectionUtils.isEmpty(scopeList)) {
            LOGGER.info("当前用户没有配置数据范围==>scopeList:{}", scopeList);
            return null;
        }
        //获取该用户所有的功能模块
        Map modelMap = scopeList.stream()
                .filter(hrSysDimensionDTO -> StringUtils.isNotBlank(hrSysDimensionDTO.getDimensionCode()))
                .filter(hrSysDimensionDTO -> "model_code".equals(hrSysDimensionDTO.getDimensionCode()))
                .collect(Collectors.toMap(HrSysDimensionDTO::getScopeId, HrSysDimensionDTO::getValue,
                        (oldValue, newValue) -> newValue));
        if (MapUtils.isEmpty(modelMap)) {
            LOGGER.info("当前用户没有配置数据范围==>modelMap:{}", modelMap);
            return null;
        }
        HrEyasMainFormService hrEyasMainFormService = (HrEyasMainFormService) SpringContextHolder
                .getObject(HrEyasMainFormService.class);
        //获取表单数据
        HrEyasMainForm hrEyasMainForm = hrEyasMainFormService.selectOneByKey(key);
        if (Objects.isNull(hrEyasMainForm)) {
            LOGGER.info("表单未配置==>hrEyasMainForm:{}", hrEyasMainForm);
            return null;
        }
        String fdType = hrEyasMainForm.getFdType();

        List scopeIds = new ArrayList<>();
        for (Entry entry : modelMap.entrySet()) {
            String scopeId = entry.getKey();
            String value = entry.getValue();
            if (value.equalsIgnoreCase("ALL")) {
                scopeIds.add(scopeId);
                continue;
            }
            List strings = Arrays.asList(value.split(","));
            if (strings.contains(fdType)) {
                scopeIds.add(scopeId);
            }
        }
        if (CollectionUtils.isEmpty(scopeIds)) {
            LOGGER.info("当前用户没有配置数据范围==>scopeIds:{}", scopeIds);
            return null;
        }
        //1.0 根据范围id,角色分组
        Map> scopeListMap = scopeList.stream()
                .filter(hrSysDimensionDTO -> scopeIds.contains(hrSysDimensionDTO.getScopeId()))
                .collect(Collectors.groupingBy(HrSysDimensionDTO::getScopeId, Collectors.toList()));
        if (MapUtils.isEmpty(scopeListMap)) {
            LOGGER.info("当前用户没有配置数据范围==>scopeListMap:{}", scopeListMap);
            return null;
        }
        return scopeListMap;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/940436.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号