數據權限(若依框架)
數據權限說明:不同的用戶查看到的數據不一樣。比如,部門經理可以查看屬於該部門的所有數據,該部門普通員工只能查看屬於自己的數據。
若依框架使用的策略是:
-
角色表中通過數據范圍字段來控制角色。
-
數據范圍字段取值說明:1:全部數據權限 2:自定數據權限 3:本部門數據權限 4:本部門及以下數據 權限 5:僅本人數據權限
-
用戶發起請求,后台獲取用戶的角色,從角色中讀取數據范圍字段,拼接sql,執行查詢操作。
例子說明:查詢用戶信息,該例子針對一個用戶只用一個角色。
1. 定義通用sql
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'
2. 獲取用戶角色的數據范圍字段,進行拼接sql。
如果數據范圍為 全部數據權限 : sql + "";
如果數據范圍為 本部門數據權限: sql + d.dept_id = 登錄用戶的部門id;
如果數據范圍為 僅本人數據權限: sql + u.user_id = 登錄用戶的id;
代碼分析
核心邏輯是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);
}