赞
踩
数据权限说明:不同的用户查看到的数据不一样。比如,部门经理可以查看属于该部门的所有数据,该部门普通员工只能查看属于自己的数据。
数据权限实现思路是:
角色表中通过data_scope字段来控制数据范围。
data_scope取值说明:1表示全部数据权限。 2表示自定数据权限 。3本部门数据权限 。4本部门及以下数据 权限 。5仅本人数据。
data_scope每一个值对应了不同的sql片段。
用户发起请求,后台获取用户的角色,从角色中读取data_scope字段。
在service层,Aop处理将sql片段,加入到bean属性map中,key是dataScope,value是sql片段。 这个map的变量名是param。
在Mapper.xml 通过${params.dataScope},就可以获取到sql片段,进行sql组装。

例子:从用户表中获取用户信息
实体类
public class BaseEntity implements Serializable{
private Map<String, Object> params;
}
public class SysUser extends BaseEntity{
// 省略
}
Service
@Override
@DataScope(deptAlias = "d", userAlias = "u")
public List<SysUser> selectUserList(SysUser user)
{
return userMapper.selectUserList(user);
}
AOP处理
// 处理的是有DataScope注解的方法
public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias)
{
// 省略了代码,后面有详细代码。
// 通过用户id,获取角色
// 通过角色获取data_scope值。
// 根据data_scope值,给map中赋值,key是dataScope。value是sql片段。
BaseEntity baseEntity = (BaseEntity) params;
baseEntity.getParams().put("dataScope", " AND (" + sqlString.substring(4) + ")");
}
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.password, 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 u
left join sys_dept d on u.dept_id = d.dept_id
where u.del_flag = '0'
<!-- 省略了不重要的语句 -->
<!-- 数据范围过滤 -->
${params.dataScope}
</select>
说明:如果只查询自己的数据。最后的sql片段就是 user_id = 用户id。也就是${params.dataScope}的值。
代码分析
核心逻辑是sql的拼接,使用的是Aop技术实现。
自定义注解类
注解类中的字段是用来拼接sql时,获取表的别名。
/** * 数据权限过滤注解 * * @author ruoyi */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataScope { /** * 部门表的别名 */ public String deptAlias() default ""; /** * 用户表的别名 */ public String userAlias() default ""; }
切面类DataScopeAspect
切点为自定的注解DataScope, 使用的是前置通知。当方法使用了DataScope注解,在执行该方法前会被拦截。执行DataScopeAspect的doBefore方法。最后调用dataScopeFilter来处理需要拼接的sql。最后把需要拼接的sql存入到BaseEntity对象中。(所有的实体类都继承来了BaseEntity类,这是关键)
/** * 数据过滤处理 * * @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"; // 配置织入点 @Pointcut("@annotation(com.ruoyi.common.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); if (controllerDataScope == null) { return; } // 获取当前的用户 LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest()); if (StringUtils.isNotNull(loginUser)) { SysUser currentUser = loginUser.getUser(); // 如果是超级管理员,则不过滤数据 if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) { dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), controllerDataScope.userAlias()); } } } /** * 数据范围过滤 * * @param joinPoint 切点 * @param user 用户 * @param userAlias 别名 */ public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) { StringBuilder sqlString = new StringBuilder(); for (SysRole role : user.getRoles()) { String dataScope = role.getDataScope(); if (DATA_SCOPE_ALL.equals(dataScope)) { sqlString = new StringBuilder(); break; } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) { 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(" OR 1=0 "); } } } if (StringUtils.isNotBlank(sqlString.toString())) { Object params = joinPoint.getArgs()[0]; if (StringUtils.isNotNull(params) && params instanceof BaseEntity) { BaseEntity baseEntity = (BaseEntity) params; baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); } } } /** * 是否存在注解,如果存在就获取 */ private DataScope getAnnotationLog(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method != null) { return method.getAnnotation(DataScope.class); } return null; } }
Mapper.xml
通过${params.dataScope}来完成sql的拼接。params是实体类父类中的属性类型,类型为Map。从该属性中可以获取到需要拼接的sql。需要拼接的sql是在切面类中前置方法中存入的。(baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + “)”);)
<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.password, 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 u left join sys_dept d on u.dept_id = d.dept_id where u.del_flag = '0' <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>
代码中的使用
class: com.ruoyi.system.service.impl.SysUserServiceImpl
@Override
@DataScope(deptAlias = "d", userAlias = "u")
public List<SysUser> selectUserList(SysUser user)
{
return userMapper.selectUserList(user);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。