基于aop注解形式和 mybatis-plus3.4.2实现数据权限控制

  • Post author:
  • Post category:其他


1、

数据权限过滤注解
package com.pojo.common.datascope.annotation;

import com.pojo.common.core.config.HkhjDataPermissionHandler;
import com.pojo.common.core.utils.DataScopeContext;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 数据权限过滤注解
 *
 * @author zsj
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope {
    /**
     * 部门数据权限查询列名
     */
    String deptId() default DataScopeContext.DEPT_ID;

    /**
     * 用户数据权限查询列名
     */
    String userSelf() default DataScopeContext.USER_SELF;

    /**
     * 需要开启数据权限的表对应的mapper
     */
    String mapperName() default "SysUserMapper";
}

2、数据权限拦截切面

package com.pojo.common.datascope.aspect;

import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.pojo.common.core.config.HkhjDataPermissionHandler;
import com.pojo.common.core.constant.CacheConstant;
import com.pojo.common.core.utils.DataScopeContext;
import com.pojo.common.core.utils.StringUtils;
import com.pojo.system.api.model.LoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.pojo.common.datascope.annotation.DataScope;
import com.pojo.common.security.service.TokenService;
import com.pojo.system.api.domain.SysUser;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class DataScopeAspect {


    @Autowired
    private TokenService tokenService;

    @Autowired
    RedissonClient redissonClient;


    // 配置织入点
    @Pointcut("@annotation(com.pojo.common.datascope.annotation.DataScope)")
    public void dataScopePointCut() {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint) {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        Map<String, String> map = Maps.newConcurrentMap();
        if (controllerDataScope == null) {
            map.put(DataScopeContext.OPEN_DATA_SCOPE, "false");
            DataScopeContext.setContextMap(map);
            return;
        }
        // 获取当前的用户
        LoginUser loginUser = tokenService.getLoginUser();
        if (Objects.nonNull(loginUser)) {
            SysUser currentUser = loginUser.getSysUser();
            Map<String, String> dataScopeFilter = dataScopeFilter(currentUser);
            map.put(DataScopeContext.OPEN_DATA_SCOPE, controllerDataScope.mapperName());
            map.put(DataScopeContext.DEPT_ID, controllerDataScope.deptId());
            map.put(DataScopeContext.USER_SELF, controllerDataScope.userSelf());
            map.put(DataScopeContext.USER_NAME, currentUser.getUserName());
            map.put(DataScopeContext.DATA_SCOPE_DEPT_ID, dataScopeFilter.getOrDefault(DataScopeContext.DATA_SCOPE_DEPT_ID, "-1"));
            map.put(DataScopeContext.DATA_SCOPE, dataScopeFilter.get(DataScopeContext.DATA_SCOPE));
            map.put(DataScopeContext.DATA_SCOPE_CUSTOM_DEPT_ID, dataScopeFilter.get(DataScopeContext.DATA_SCOPE_CUSTOM_DEPT_ID));
            DataScopeContext.setContextMap(map);
        }

    }

    /**
     * 数据范围过滤
     *
     * @param user 用户
     */
    public Map<String, String> dataScopeFilter(SysUser user) {
        Set<String> dataScope = Sets.newHashSet();
        Map<String, String> result = Maps.newHashMap();
        if (1 == user.getId()) {
            dataScope.add("1");
        }
        if (CollUtil.isNotEmpty(user.getRoles())) {
            user.getRoles().forEach(i -> {
                dataScope.add(i.getDataScope());
            });
        }

        if (CollUtil.isNotEmpty(dataScope)) {
            if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_CUSTOM)) {
                //包含自定义权限
                Set<String> deptIds = Sets.newHashSet();
                if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_ALL)) {
                    //全部
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_ALL);
                } else if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_DEPT_AND_CHILD)) {
                    //部门及以下 和自定义
                    result.put(DataScopeContext.DATA_SCOPE_DEPT_ID, user.getDeptId() + "");
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_DEPT_AND_CHILD_AND_CUSTOM);
                } else if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_DEPT)) {
                    //部门 和自定义
                    deptIds.add(user.getDeptId() + "");
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_CUSTOM);
                } else if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_SELF)) {
                    //自定义
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_CUSTOM);
                }
                //获取自定义的权限部门id
                user.getRoles().forEach(i -> {
                    if (Objects.equals(i.getDataScope(), HkhjDataPermissionHandler.DATA_SCOPE_CUSTOM)) {
                        RBucket<String> rBucket = redissonClient.getBucket(CacheConstant.ROLE_AND_DEPT + i.getId());
                        String depts = rBucket.get();
                        if (StringUtils.isNotBlank(depts)) {
                            List<String> deptIdList = Arrays.asList(depts.split(","));
                            deptIds.addAll(deptIdList);
                        }
                    }
                });

                List<String> dept = deptIds.stream().distinct().collect(Collectors.toList());
                result.put(DataScopeContext.DATA_SCOPE_CUSTOM_DEPT_ID, StringUtils.join(dept, ","));
            } else {
                result.put(DataScopeContext.DATA_SCOPE_CUSTOM_DEPT_ID, "");
                //不包含自定义权限
                if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_ALL)) {
                    //全部
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_ALL);
                } else if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_DEPT_AND_CHILD)) {
                    //部门及以下
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_DEPT_AND_CHILD);
                    result.put(DataScopeContext.DATA_SCOPE_DEPT_ID, user.getDeptId() + "");
                } else if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_DEPT)) {
                    //部门
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_DEPT);
                    result.put(DataScopeContext.DATA_SCOPE_DEPT_ID, user.getDeptId() + "");
                } else if (dataScope.contains(HkhjDataPermissionHandler.DATA_SCOPE_SELF)) {
                    //自己
                    result.put(DataScopeContext.DATA_SCOPE, HkhjDataPermissionHandler.DATA_SCOPE_SELF);
                }
            }
        }
        return result;
    }

    /**
     * 是否存在注解,如果存在就获取
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (Objects.nonNull(method)) {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }
}

3、mybatis-plus的sql拦截

package com.pojo.common.core.config;

import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.pojo.common.core.utils.DataScopeContext;
import com.pojo.common.core.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.cond



版权声明:本文为zsj777原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。