若依前后端分离版学习笔记(十)——数据权限
一 数据权限使用详解
在实际开发中,需要设置用户只能查看哪些部门的数据,这种情况一般称为数据权限。
例如对于销售,财务的数据,它们是非常敏感的,因此要求对数据权限进行控制, 对于基于集团性的应用系统而言,就更多需要控制好各自公司的数据了。如设置只能看本公司、或者本部门的数据,对于特殊的领导,可能需要跨部门的数据, 因此程序不能硬编码那个领导该访问哪些数据,需要进行后台的权限和数据权限的控制。
默认系统管理员admin拥有所有数据权限(userId=1),默认角色拥有所有数据权限(如不需要数据权限不用设置数据权限操作)
在角色管理处可设置角色的数据权限
我们下面走一遍设置数据权限并更改的流程
1.新建测试角色设置数据权限为本部门数据权限
2.新建用户test,选择测试角色(部门为研发部门)
3.登录test用户,查看数据权限情况(部门管理处只有本部门)
4.重新登录admin用户,给测试角色新增测试部门权限,再重新登录test用户验证
二 数据权限代码详解
本节以下内容部分来自ruoyi官方文档
注解参数说明
permission说明: 一个user会拥有多个role,每个role都负责不同的业务场景,user可以通过permission精确控制哪些role在本次操作能生效
例子:当前user有两个role,分别为Role A(有权限字符串a)和Role B(有权限字符串b),分别是Dept A和Dept B部门下的角色。
而method接口能都返回这两个部门的数据,此时有个业务需求是user访问method这个接口希望仅返回Dept A的数据。
此时只需要控制permission中的权限让Role A有而Role B没有即可,即permission = "a"就能让Role A生效而Role B失效
1、在(系统管理-角色管理)设置需要数据权限的角色 目前支持以下几种权限
- 全部数据权限
- 自定数据权限
- 部门数据权限
- 部门及以下数据权限
- 仅本人数据权限
2、在需要数据权限控制方法上添加@DataScope注解,其中d和u用来表示表的别名
@DataScope(deptAlias = "d")
public List<...> select(...)
{return mapper.select(...);
}
部门及用户权限注解
@DataScope(deptAlias = "d", userAlias = "u")
public List<...> select(...)
{return mapper.select(...);
}
如SysUserServiceImpl中
/*** 根据条件分页查询用户列表* * @param user 用户信息* @return 用户信息集合信息*/
@Override
@DataScope(deptAlias = "d", userAlias = "u")
public List<SysUser> selectUserList(SysUser user)
{return userMapper.selectUserList(user);
}
3、在mybatis查询底部标签添加数据范围过滤
<select id="select" parameterType="..." resultMap="...Result"><include refid="select...Vo"/><!-- 数据范围过滤 -->${params.dataScope}
</select>
如SysUserMapper.xml中
<select id="selectUserList" parameterType="SysUser" resultMap="SysUserResult">select u.user_id, u.dept_id, u.nick_name, u.user_name, u.email, u.avatar, u.phonenumber, u.sex, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name, d.leader from sys_user uleft join sys_dept d on u.dept_id = d.dept_idwhere u.del_flag = '0'<if test="userId != null and userId != 0">AND u.user_id = #{userId}</if><if test="userName != null and userName != ''">AND u.user_name like concat('%', #{userName}, '%')</if><if test="status != null and status != ''">AND u.status = #{status}</if><if test="phonenumber != null and phonenumber != ''">AND u.phonenumber like concat('%', #{phonenumber}, '%')</if><if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->AND date_format(u.create_time,'%Y%m%d') >= date_format(#{params.beginTime},'%Y%m%d')</if><if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->AND date_format(u.create_time,'%Y%m%d') <= date_format(#{params.endTime},'%Y%m%d')</if><if test="deptId != null and deptId != 0">AND (u.dept_id = #{deptId} OR u.dept_id IN ( SELECT t.dept_id FROM sys_dept t WHERE find_in_set(#{deptId}, ancestors) ))</if><!-- 数据范围过滤 -->${params.dataScope}
</select>
例如:用户管理(未过滤数据权限的情况):
select u.user_id, u.dept_id, u.login_name, u.user_name, u.email, u.phonenumber, u.password, u.sex, u.avatar, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name
from sys_user uleft join sys_dept d on u.dept_id = d.dept_id
where u.del_flag = '0'
例如:用户管理(已过滤数据权限的情况):
select u.user_id, u.dept_id, u.login_name, u.user_name, u.email, u.phonenumber, u.password, u.sex, u.avatar, u.salt, u.status, u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark, d.dept_name
from sys_user uleft join sys_dept d on u.dept_id = d.dept_id
where u.del_flag = '0'and u.dept_id in (select dept_idfrom sys_role_deptwhere role_id = 2)
结果很明显,我们多了如下语句。通过角色部门表(sys_role_dept)完成了数据权限过滤
and u.dept_id in (select dept_idfrom sys_role_deptwhere role_id = 2
)
下面我们来看一下是如何实现的,查看切面类DataScopeAspect
package com.ruoyi.framework.aspectj;import java.util.ArrayList;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.context.PermissionContextHolder;/*** 数据过滤处理** @author ruoyi*/
@Aspect
@Component
public class DataScopeAspect
{/*** 全部数据权限*/public static final String DATA_SCOPE_ALL = "1";/*** 自定数据权限*/public static final String DATA_SCOPE_CUSTOM = "2";/*** 部门数据权限*/public static final String DATA_SCOPE_DEPT = "3";/*** 部门及以下数据权限*/public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";/*** 仅本人数据权限*/public static final String DATA_SCOPE_SELF = "5";/*** 数据权限过滤关键字*/public static final String DATA_SCOPE = "dataScope";// 目标方法执行前处理@Before("@annotation(controllerDataScope)")public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable{clearDataScope(point);handleDataScope(point, controllerDataScope);}protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope){// 获取当前的用户LoginUser loginUser = SecurityUtils.getLoginUser();if (StringUtils.isNotNull(loginUser)){// 获取当前登录用户信息SysUser currentUser = loginUser.getUser();// 如果是超级管理员,则不过滤数据if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()){// 获取权限标识符,优先使用注解中配置的permission,否则使用上下文中的权限String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), PermissionContextHolder.getContext());// 调用dataScopeFilter()方法进行数据范围过滤处理dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), controllerDataScope.userAlias(), permission);}}}/*** 数据范围过滤** @param joinPoint 切点* @param user 用户* @param deptAlias 部门别名 sql中表别名 d* @param userAlias 用户别名 sql中表别名 u* @param permission 权限字符*/public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission){StringBuilder sqlString = new StringBuilder();List<String> conditions = new ArrayList<String>();List<String> scopeCustomIds = new ArrayList<String>();// 遍历用户所有角色user.getRoles().forEach(role -> {// 如果用户是自定义数据权限且角色状态正常且包含指定权限的角色if (DATA_SCOPE_CUSTOM.equals(role.getDataScope()) && StringUtils.equals(role.getStatus(), UserConstants.ROLE_NORMAL) && StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))){// 将角色id放入集合scopeCustomIds.add(Convert.toStr(role.getRoleId()));}});// 遍历用户角色,根据角色类型生成sql for (SysRole role : user.getRoles()){String dataScope = role.getDataScope();if (conditions.contains(dataScope) || StringUtils.equals(role.getStatus(), UserConstants.ROLE_DISABLE)){continue;}if (!StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))){continue;}if (DATA_SCOPE_ALL.equals(dataScope)){sqlString = new StringBuilder();conditions.add(dataScope);break;}else if (DATA_SCOPE_CUSTOM.equals(dataScope)){if (scopeCustomIds.size() > 1){// 多个自定数据权限使用in查询,避免多次拼接。sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id in ({}) ) ", deptAlias, String.join(",", scopeCustomIds)));}else{sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId()));}}else if (DATA_SCOPE_DEPT.equals(dataScope)){sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));}else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)){sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", deptAlias, user.getDeptId(), user.getDeptId()));}else if (DATA_SCOPE_SELF.equals(dataScope)){if (StringUtils.isNotBlank(userAlias)){sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));}else{// 数据权限为仅本人且没有userAlias别名不查询任何数据sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));}}conditions.add(dataScope);}// 角色都不包含传递过来的权限字符,这个时候sqlString也会为空,所以要限制一下,不查询任何数据if (StringUtils.isEmpty(conditions)){sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));}// 如果生成的sql不为空if (StringUtils.isNotBlank(sqlString.toString())){// 获取拦截方法的第一个参数Object params = joinPoint.getArgs()[0];// 该参数不为空且继承BaseEntity,则将参数转为BaseEntity并将sql put进其参数中if (StringUtils.isNotNull(params) && params instanceof BaseEntity){BaseEntity baseEntity = (BaseEntity) params;baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");}}}/*** 拼接权限sql前先清空params.dataScope参数防止注入*/private void clearDataScope(final JoinPoint joinPoint){Object params = joinPoint.getArgs()[0];if (StringUtils.isNotNull(params) && params instanceof BaseEntity){BaseEntity baseEntity = (BaseEntity) params;baseEntity.getParams().put(DATA_SCOPE, "");}}
}
仅实体继承BaseEntity才会进行处理,SQL语句会存放到BaseEntity对象中的params属性中,然后在xml中通过${params.dataScope}获取拼接后的语句。
PS:如果是自己的业务表需要实现数据权限,需要有dept_id和user_id这两个字段
三 数据权限业务实现
给操作日志记录表sys_oper_log新增数据权限管理
1、 新增dept_id和user_id这两个字段
2、实体类SysOperLog里新增这两个属性及getter setter方法
private Long userId;private Long deptId;public Long getUserId() {return userId;
}public void setUserId(Long userId) {this.userId = userId;
}public Long getDeptId() {return deptId;
}public void setDeptId(Long deptId) {this.deptId = deptId;
}
3、在查询操作日志列表SysOperLogServiceImpl的selectOperLogList方法上新增注解
@DataScope(deptAlias = "d", userAlias = "u")
/*** 查询系统操作日志集合* * @param operLog 操作日志对象* @return 操作日志集合*/
@Override
@DataScope(deptAlias = "d", userAlias = "u")
public List<SysOperLog> selectOperLogList(SysOperLog operLog)
{return operLogMapper.selectOperLogList(operLog);
}
4、给SysOperLogMapper.xml的selectOperLogList查询底部标签添加数据范围过滤
<select id="selectOperLogList" parameterType="SysOperLog" resultMap="SysOperLogResult"><include refid="selectOperLogVo"/><!-- 去掉where标签并新增 where 1=1,防止过滤条件都为空时新增数据范围过滤and报错 -->where 1=1<if test="operIp != null and operIp != ''">AND oper_ip like concat('%', #{operIp}, '%')</if><if test="title != null and title != ''">AND title like concat('%', #{title}, '%')</if><if test="businessType != null">AND business_type = #{businessType}</if><if test="businessTypes != null and businessTypes.length > 0">AND business_type in<foreach collection="businessTypes" item="businessType" open="(" separator="," close=")">#{businessType}</foreach> </if><if test="status != null">AND status = #{status}</if><if test="operName != null and operName != ''">AND oper_name like concat('%', #{operName}, '%')</if><if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->AND oper_time >= #{params.beginTime}</if><if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->AND oper_time <= #{params.endTime}</if><!-- 数据范围过滤 -->${params.dataScope}order by oper_id desc
</select>
调整查询列表selectOperLogVo
<!--调整前-->
<sql id="selectOperLogVo">select oper_id, title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time, cost_timefrom sys_oper_log</sql>
<!--调整后-->
<sql id="selectOperLogVo">select o.oper_id, o.user_id, o.dept_id, o.title, o.business_type, o.method, o.request_method, o.operator_type, o.oper_name, o.dept_name, o.oper_url, o.oper_ip, o.oper_location, o.oper_param, o.json_result, o.status, o.error_msg, o.oper_time, o.cost_timefrom sys_oper_log oleft join sys_user u on o.user_id = u.user_idleft join sys_dept d on u.dept_id = d.dept_id</sql>
5、在LogAspect类中设置日志插入user_id 和 dept_id两个字段信息
// 调整前
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult)
{try{// 获取当前的用户LoginUser loginUser = SecurityUtils.getLoginUser();// *========数据库日志=========*//SysOperLog operLog = new SysOperLog();operLog.setStatus(BusinessStatus.SUCCESS.ordinal());// 请求的地址String ip = IpUtils.getIpAddr();operLog.setOperIp(ip);operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));if (loginUser != null){operLog.setOperName(loginUser.getUsername());SysUser currentUser = loginUser.getUser();if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept())){operLog.setDeptName(currentUser.getDept().getDeptName());}}if (e != null){operLog.setStatus(BusinessStatus.FAIL.ordinal());operLog.setErrorMsg(StringUtils.substring(Convert.toStr(e.getMessage(), ExceptionUtil.getExceptionMessage(e)), 0, 2000));}// 设置方法名称String className = joinPoint.getTarget().getClass().getName();String methodName = joinPoint.getSignature().getName();operLog.setMethod(className + "." + methodName + "()");// 设置请求方式operLog.setRequestMethod(ServletUtils.getRequest().getMethod());// 处理设置注解上的参数getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);// 设置消耗时间operLog.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());// 保存数据库AsyncManager.me().execute(AsyncFactory.recordOper(operLog));}catch (Exception exp){// 记录本地异常日志log.error("异常信息:{}", exp.getMessage());exp.printStackTrace();}finally{TIME_THREADLOCAL.remove();}
}// 调整后
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult)
{try{// 获取当前的用户LoginUser loginUser = SecurityUtils.getLoginUser();// *========数据库日志=========*//SysOperLog operLog = new SysOperLog();operLog.setStatus(BusinessStatus.SUCCESS.ordinal());// 请求的地址String ip = IpUtils.getIpAddr();operLog.setOperIp(ip);operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));if (loginUser != null){operLog.setUserId(loginUser.getUserId());operLog.setDeptId(loginUser.getDeptId());operLog.setOperName(loginUser.getUsername());SysUser currentUser = loginUser.getUser();if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept())){operLog.setDeptName(currentUser.getDept().getDeptName());}}if (e != null){operLog.setStatus(BusinessStatus.FAIL.ordinal());operLog.setErrorMsg(StringUtils.substring(Convert.toStr(e.getMessage(), ExceptionUtil.getExceptionMessage(e)), 0, 2000));}// 设置方法名称String className = joinPoint.getTarget().getClass().getName();String methodName = joinPoint.getSignature().getName();operLog.setMethod(className + "." + methodName + "()");// 设置请求方式operLog.setRequestMethod(ServletUtils.getRequest().getMethod());// 处理设置注解上的参数getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);// 设置消耗时间operLog.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());// 保存数据库AsyncManager.me().execute(AsyncFactory.recordOper(operLog));}catch (Exception exp){// 记录本地异常日志log.error("异常信息:{}", exp.getMessage());exp.printStackTrace();}finally{TIME_THREADLOCAL.remove();}
}
6、SysOperLogMapper.xml中日志表插入sql新增user_id和dept_id字段
<insert id="insertOperlog" parameterType="SysOperLog">insert into sys_oper_log(title, user_id, dept_id, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, cost_time, oper_time)values (#{title}, #{userId}, #{deptId}, #{businessType}, #{method}, #{requestMethod}, #{operatorType}, #{operName}, #{deptName}, #{operUrl}, #{operIp}, #{operLocation}, #{operParam}, #{jsonResult}, #{status}, #{errorMsg}, #{costTime}, sysdate())
</insert>
7、登录admin账号新增岗位,测试日志表中是否能插入用户id和部门id字段值
8、将测试角色数据权限修改为仅本人数据权限
修改前测试用户(测试角色)查看操作日志页面
修改后