从零开始,手打一个权限管理系统(第十章 数据权限)

第十章 数据权限


前言

这章主要讲解如何实现对表数据权限的控制,让授权用户只能看到指定范围的数据。


一、实现思路

我们用组织机构ID(org_id)来作为数据权限的过滤字段,通过对sql语句添加where条件来实现对数据的过滤;这里我们需要用到MyBatis-Plus的一个数据权限的插件DataPermissionInterceptor,通过实现自定义的数据权限处理器DataPermissionHandler,就可以满足我们在sql语句里面添加过滤条件的需求。


二、主要代码

1、自定义数据拦截器,实现DataPermissionHandler接口

package com.ailot.cloud.base.data.datascope;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.ailot.cloud.base.common.constants.CommonConstant;
import com.ailot.cloud.base.common.exception.CheckedException;
import com.ailot.cloud.base.data.enums.DataScopeTypeEnum;
import com.ailot.cloud.base.security.constant.SecurityConstants;
import com.ailot.cloud.base.security.model.JwtUser;
import com.ailot.cloud.base.security.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import lombok.SneakyThrows;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.schema.Column;
import org.springframework.security.core.GrantedAuthority;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


public class DataScopeHandler implements DataPermissionHandler {

    private final DataScopeProperties dataScopeProperties;

    private final DataSource dataSource;


    public DataScopeHandler(DataScopeProperties dataScopeProperties, DataSource dataSource) {
        this.dataScopeProperties = dataScopeProperties;
        this.dataSource = dataSource;
    }

    @SneakyThrows
    @Override
    public Expression getSqlSegment(Expression where, String mappedStatementId) {
        //查询需要配置数据权限的方法
        List<String> mapperIds = dataScopeProperties.getMapperIds();
        if (CollUtil.isEmpty(mapperIds)) {
            return where;
        } else {
            if (!CollUtil.contains(mapperIds, mappedStatementId)) {
                return where;
            }
        }
        List<String> orgIds = new ArrayList<>();
        JwtUser user = SecurityUtils.getUser();
        if (user == null) {
            throw new CheckedException("用户信息为空");
        }
        //获取角色ID列表
        List<String> roleIdList = user.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .filter(authority -> authority.startsWith(SecurityConstants.ROLE))
                .map(authority -> authority.split("_")[1])
                .collect(Collectors.toList());

        // 获取角色信息
        Entity query = Db.use(dataSource)
                .query("SELECT * FROM " + CommonConstant.UPMS_DATABASE + ".sys_role where id IN ('" + CollUtil.join(roleIdList, "','") + "')")
                .stream().min(Comparator.comparingInt(o -> o.getInt("ds_type"))).get();
        Integer dsType = query.getInt("ds_type");
        //查询全部
        if (DataScopeTypeEnum.ALL.getType() == dsType) {
            return where;
        }
        // 自定义
        if (DataScopeTypeEnum.CUSTOM.getType() == dsType) {
            //部门范围
            String dsScope = query.getStr("ds_scope");
            orgIds.addAll(Arrays.stream(dsScope.split(",")).map(String::toString).collect(Collectors.toList()));
        }
        // 只查询本级
        if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
            orgIds.add(user.getOrgId());
        }
        ItemsList itemsList = new ExpressionList(orgIds.stream().map(StringValue::new).collect(Collectors.toList()));
        InExpression inExpression = new InExpression(new Column(CommonConstant.ORG_SCOPE), itemsList);
        return ObjectUtils.isNotEmpty(where) ? new AndExpression(where, inExpression) : inExpression;
    }
}

简单说一下这个代码的逻辑,首先是拿到需要数据权限拦截的方法,然后获取当前用户的角色,通过角色就可以获取到数据权限类型(ds_type);这里我们定义了三种类型的数据权限(全部、自定义、本级),全部就不用加where条件,自定义就是获取到指定范围ds_scope的数据,本级就是当前用户所在部门的数据,然后我们只需要将这些条件拼接起来,生成一个新的sql语句就可以了。
拦截后生成的新SQL语句

2、配置拦截器
要使用数据拦截器需要在Mybatis配置文件里面初始化

DataPermissionInterceptor dataPermissionInterceptor = new DataPermissionInterceptor();
dataPermissionInterceptor.setDataPermissionHandler(new DataScopeHandler(dataScopeProperties, dataSource));
 MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
 //数据权限拦截
 interceptor.addInnerInterceptor(dataPermissionInterceptor);

3、在yml文件里面配置需要拦截的方法

base:
  datascope:
    mapperIds:
      - com.ailot.cloud.upms.api.mapper.SysUserMapper.pageUser

至此数据权限的配置就已经全部完成了,后面只需要在有拦截需求的表加上拦截字段,在yml配置文件上添加需要拦截的方法就可以实现数据权限的过滤了。


三、效果展示

全部数据可看

只能看自己部门的数据

当前版本tag:1.0.9
代码仓库


四、 体验地址

后台数据库只给了部分权限,报错属于正常!
想学的老铁给点点关注吧!!!
欢迎留言交流!!!

我是阿咕噜,一个从互联网慢慢上岸的程序员,如果喜欢我的文章,记得帮忙点个赞哟,谢谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值