禅道问题修复:1、组织套餐允许超管操作;2、角色权限修改触发角色下用户的token缓存删除;3、网关checktoken移除本地缓存,直接查feignapi;4、order_goods的goods_id转为字符串类型的相关代码适配;

This commit is contained in:
gaoqr
2024-09-10 18:28:34 +08:00
parent 433e6825e5
commit e7192ff6cd
8 changed files with 182 additions and 98 deletions
@@ -1,6 +1,8 @@
package com.cf.imes.module.system.dal.mysql.permission;
import com.cf.imes.framework.mybatis.core.mapper.BaseMapperX;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.core.aop.OrganIgnore;
import com.cf.imes.module.system.dal.dataobject.permission.UserRoleDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
@@ -45,4 +47,24 @@ public interface UserRoleMapper extends BaseMapperX<UserRoleDO> {
return selectList(UserRoleDO::getRoleId, roleIds);
}
/**
* 忽视多组织查询角色下的用户id列表
*
* @param roleId
* @return
*/
@OrganIgnore
default List<UserRoleDO> selectRoleUserIds(Long roleId) {
return selectList(new LambdaQueryWrapperX<UserRoleDO>().eq(UserRoleDO::getRoleId, roleId).select(UserRoleDO::getUserId));
}
/**
* 查询角色下的用户id列表
*
* @param roleId
* @return
*/
default List<UserRoleDO> selectOrgRoleUserIds(Long roleId) {
return selectList(new LambdaQueryWrapperX<UserRoleDO>().eq(UserRoleDO::getRoleId, roleId).select(UserRoleDO::getUserId));
}
}
@@ -7,6 +7,7 @@ import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.controller.admin.organ.vo.packages.TenantPackagePageReqVO;
import com.cf.imes.module.system.controller.admin.organ.vo.packages.TenantPackageSaveReqVO;
import com.cf.imes.module.system.dal.dataobject.organ.OrganizationDO;
@@ -58,7 +59,8 @@ public class TenantPackageServiceImpl implements TenantPackageService {
validateTenantPackageUnique(updateReqVO);
// 校验存在
TenantPackageDO tenantPackage = validateTenantPackageExists(updateReqVO.getId());
if(Objects.equals(tenantPackage.getId(), SYSTEM_ORGAN_PACKAGE_ID) || Objects.equals(tenantPackage.getId(), SYSTEM_SUPER_PACKAGE_ID)) {
if (Boolean.FALSE.equals(SecurityFrameworkUtils.isSuperAdmin()) &&
(Objects.equals(tenantPackage.getId(), SYSTEM_ORGAN_PACKAGE_ID) || Objects.equals(tenantPackage.getId(), SYSTEM_SUPER_PACKAGE_ID))) {
throw exception(TENANT_PACKAGE_DEPT_EXIT);
}
@@ -1,13 +1,13 @@
package com.cf.imes.module.system.service.permission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.util.collection.CollectionUtils;
import com.cf.imes.framework.common.util.json.JsonUtils;
import com.cf.imes.framework.datapermission.core.annotation.DataPermission;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.core.aop.OrganIgnore;
@@ -18,7 +18,7 @@ import com.cf.imes.module.system.api.permission.dto.DeptDataPermissionRespDTO;
import com.cf.imes.module.system.constants.permission.InternalRoleConstants;
import com.cf.imes.module.system.controller.admin.permission.vo.permission.PermissionAssignRoleUserReqVO;
import com.cf.imes.module.system.controller.admin.permission.vo.permission.PermissionAssignUserRoleReqVO;
import com.cf.imes.module.system.convert.auth.AuthConvert;
import com.cf.imes.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.cf.imes.module.system.dal.dataobject.permission.MenuDO;
import com.cf.imes.module.system.dal.dataobject.permission.RoleDO;
import com.cf.imes.module.system.dal.dataobject.permission.RoleMenuDO;
@@ -32,17 +32,17 @@ import com.cf.imes.module.system.enums.permission.DataScopeEnum;
import com.cf.imes.module.system.service.dept.DeptService;
import com.cf.imes.module.system.service.user.AdminUserService;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.cf.imes.module.system.util.organ.OrganUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -54,10 +54,10 @@ import java.util.function.Supplier;
import java.util.stream.Collectors;
import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.framework.common.pojo.CommonResult.success;
import static com.cf.imes.framework.common.util.collection.CollectionUtils.convertSet;
import static com.cf.imes.framework.common.util.json.JsonUtils.toJsonString;
import static com.cf.imes.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static com.cf.imes.module.system.dal.redis.RedisKeyConstants.OAUTH2_ACCESS_TOKEN;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.ROLE_ME_ERROR;
/**
@@ -83,8 +83,8 @@ public class PermissionServiceImpl implements PermissionService {
@Resource
private AdminUserService userService;
@Autowired
private RedisTemplate redisTemplate;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public boolean hasAnyPermissions(Long userId, String... permissions) {
@@ -164,18 +164,15 @@ public class PermissionServiceImpl implements PermissionService {
allEntries = true) // allEntries 清空所有缓存,主要一次更新涉及到的 menuIds 较多,反倒批量会更快
public void assignRoleMenu(Long roleId, Set<Long> menuIds, Long organId) {
// 获得角色拥有菜单编号
Set<Long> dbMenuIds = null;
boolean isOrganRole = Objects.equals(roleId, InternalRoleConstants.ORGAN_ADMIN_ROLE_ID) || Objects.equals(roleId, InternalRoleConstants.ORGAN_STAFF_ROLE_ID);
Set<Long> dbMenuIds;
boolean isOrganRole = OrganUtils.isOrgRole(roleId);
if (isOrganRole) {
dbMenuIds = convertSet(roleMenuMapper.selectListByRoleIdWithOrganAdmin(List.of(roleId)), RoleMenuDO::getMenuId);
}else {
dbMenuIds = convertSet(roleMenuMapper.selectListByRoleId(roleId), RoleMenuDO::getMenuId);
}
// 查询角色获取角色的组织id,如果没有传入组织id就跟角色的组织统一
RoleDO role = roleService.getRole(roleId);
if (Objects.isNull(role)) {
throw new ServiceException(ErrorCodeConstants.ROLE_NOT_EXISTS);
}
RoleDO role = validateRole(roleId);
// 前端没传或者查一次后切换了组织导致跟角色组织不一致的统一为角色的组织
Long roleOrganId = role.getOrganId();
if (Objects.isNull(organId) || ObjectUtil.notEqual(roleOrganId, organId)) {
@@ -206,25 +203,75 @@ public class PermissionServiceImpl implements PermissionService {
roleMenuMapper.deleteListByRoleIdAndMenuIds(roleId, deleteMenuIds);
}
// 角色菜单权限发生修改,通知刷新本地缓存
flushRoleMenuCache(roleId, isOrganRole, createMenuIds, deleteMenuIds, finalOrganId);
}
/**
* 跨机构清理角色菜单缓存 + 通知刷新本地缓存
*
* @param roleId 操作的角色id
* @param isOrganRole 是否内置角色
* @param createMenuIds 新增角色-菜单关联id
* @param deleteMenuIds 删除角色-菜单关联id
* @param organId 角色所属机构id
*/
private void flushRoleMenuCache(Long roleId, boolean isOrganRole, Collection<Long> createMenuIds, Collection<Long> deleteMenuIds, Long organId) {
Long currentOrganId = SecurityFrameworkUtils.getUserOrganId();
// 角色菜单权限发生修改,通知刷新本地缓存
if (CollectionUtil.isNotEmpty(createMenuIds) || CollectionUtil.isNotEmpty(deleteMenuIds)) {
if (CollUtil.isNotEmpty(createMenuIds) || CollUtil.isNotEmpty(deleteMenuIds)) {
CompletableFuture.runAsync(() -> {
// 当前操作人和所操作的目标菜单机构不同时,清空MENU_ROLE_ID_LIST:*:菜单id的缓存
if (ObjectUtil.notEqual(finalOrganId, currentOrganId)) {
// 获取新增和删除菜单id的并集
Collection<Long> delMenuIds = CollUtil.union(createMenuIds, deleteMenuIds);
delMenuIds.forEach(delMenuId -> {
String patternKey = String.format(String.valueOf(new StringBuffer(RedisKeyConstants.MENU_ROLE_ID_LIST).append(":*:%s")), delMenuId);
Long batchDelNum = scanAndDelKeys(patternKey);
log.info("[assignRoleMenu] 批量删除redis[{}]数量:{}", patternKey, batchDelNum);
// 当前操作人和所操作的目标菜单机构不同时,清空MENU_ROLE_ID_LIST:*:菜单id的缓存
if (ObjectUtil.notEqual(organId, currentOrganId)) {
// 获取新增和删除菜单id的并集
Collection<Long> delMenuIds = CollUtil.union(createMenuIds, deleteMenuIds);
delMenuIds.forEach(delMenuId -> {
String patternKey = String.format(String.valueOf(new StringBuffer(RedisKeyConstants.MENU_ROLE_ID_LIST).append(":*:%s")), delMenuId);
Long batchDelNum = scanAndDelKeys(patternKey);
log.info("[assignRoleMenu] 批量删除redis[{}]数量:{}", patternKey, batchDelNum);
});
}
stringRedisTemplate.convertAndSend(RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, "");
})
.thenRunAsync(() -> {
// 清空角色下用户的token缓存
List<Long> userIds;
if(isOrganRole) {
userIds = userRoleMapper.selectRoleUserIds(roleId).stream().map(UserRoleDO::getUserId).toList();
} else {
userIds = userRoleMapper.selectOrgRoleUserIds(roleId).stream().map(UserRoleDO::getUserId).toList();
}
scanAndCompareUserAndDelKeys(String.format(OAUTH2_ACCESS_TOKEN, "*"), userIds);
})
.exceptionally(e -> {
log.error("[assignRoleMenu][flushRoleMenuCache]失败, 异常:{}", e);
return null;
});
}
}
/**
* scan匹配oauth2_access_token:下缓存并删除缓存
* @param keyPattern
* @param userIds
*/
private void scanAndCompareUserAndDelKeys(String keyPattern, List<Long> userIds) {
// 根据keyPattern scan匹配的redis key
List<String> matchKeys = new ArrayList<>();
Cursor<String> cursor = stringRedisTemplate.scan(ScanOptions.scanOptions().match(keyPattern).count(200).build());
while (cursor.hasNext()) {
matchKeys.add(cursor.next());
}
cursor.close();
if (CollUtil.isNotEmpty(matchKeys)) {
for (String key : matchKeys) {
// 获取key下的用户信息
OAuth2AccessTokenDO oAuth2AccessTokenDO = JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(key), OAuth2AccessTokenDO.class);
if (CollUtil.contains(userIds, oAuth2AccessTokenDO.getUserId())) {
// 角色下的用户id匹配上了删除redis中的token缓存
stringRedisTemplate.delete(key);
}
redisTemplate.convertAndSend(RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, "");
}).exceptionally(e -> {
log.error("[assignRoleMenu] redis 清空MENU_ROLE_ID_LIST或message发送失败, topic:{}, 异常:{}", RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, e);
return null;
});
}
}
}
@@ -236,18 +283,32 @@ public class PermissionServiceImpl implements PermissionService {
private Long scanAndDelKeys(String keyPattern) {
// 根据keyPattern scan匹配的redis key
List<String> delKeys = new ArrayList<>();
Cursor<String> cursor = redisTemplate.scan(ScanOptions.scanOptions().match(keyPattern).count(200).build());
Cursor<String> cursor = stringRedisTemplate.scan(ScanOptions.scanOptions().match(keyPattern).count(200).build());
while (cursor.hasNext()) {
delKeys.add(cursor.next());
}
cursor.close();
// 删除匹配到的key
if (CollectionUtil.isNotEmpty(delKeys)) {
return redisTemplate.delete(delKeys);
if (CollUtil.isNotEmpty(delKeys)) {
return stringRedisTemplate.delete(delKeys);
}
return 0L;
}
/**
* 校验角色
*
* @param roleId
*/
private RoleDO validateRole(Long roleId) {
RoleDO role = roleService.getRole(roleId);
if (Objects.isNull(role)) {
throw new ServiceException(ErrorCodeConstants.ROLE_NOT_EXISTS);
}
return role;
}
@Override
@Transactional(rollbackFor = Exception.class)
@Caching(evict = {
@@ -343,13 +404,10 @@ public class PermissionServiceImpl implements PermissionService {
}
}
// 查询角色获取角色的组织id,如果没有传入组织id就跟角色的组织统一
RoleDO role = roleService.getRole(roleId);
if (Objects.isNull(role)) {
throw new ServiceException(ErrorCodeConstants.ROLE_NOT_EXISTS);
}
RoleDO role = validateRole(roleId);
// 前端没传或者查一次后切换了组织导致跟角色组织不一致的统一为角色的组织
Long roleOrganId = role.getOrganId();
boolean isOrganRole = Objects.equals(roleId, InternalRoleConstants.ORGAN_ADMIN_ROLE_ID) || Objects.equals(roleId, InternalRoleConstants.ORGAN_STAFF_ROLE_ID);
boolean isOrganRole = OrganUtils.isOrgRole(roleId);
// 内置角色还是按照机构来存
if (!isOrganRole && (Objects.isNull(organId) || ObjectUtil.notEqual(roleOrganId, organId))) {
organId = roleOrganId;
@@ -364,7 +422,7 @@ public class PermissionServiceImpl implements PermissionService {
// 筛选要新增的userRole:前端有,数据库没有
Collection<Long> createRoleUserIds = CollUtil.subtract(userIds, roleUserIds);
if (!CollectionUtil.isEmpty(createRoleUserIds)) {
if (CollUtil.isNotEmpty(createRoleUserIds)) {
userRoleMapper.insertBatch(CollectionUtils.convertList(createRoleUserIds, userId -> {
UserRoleDO entity = new UserRoleDO();
entity.setUserId(userId).setRoleId(roleId).setOrganId(finalOrganId);
@@ -374,7 +432,7 @@ public class PermissionServiceImpl implements PermissionService {
// 筛选要删除的userRole:前端没有,数据库有
Collection<Long> deleteRoleUserIds = CollUtil.subtract(roleUserIds, userIds);
if (!CollectionUtil.isEmpty(deleteRoleUserIds)) {
if (CollUtil.isNotEmpty(deleteRoleUserIds)) {
// 当前用户不能移除自身的角色
Long incloudSelf = deleteRoleUserIds.stream().filter(userId -> userId.equals(loginUser.getId())).findAny().orElse(null);
if (incloudSelf != null) {
@@ -382,13 +440,24 @@ public class PermissionServiceImpl implements PermissionService {
}
userRoleMapper.deleteListByRoleIdAndUserIds(roleId, deleteRoleUserIds);
}
// 角色菜单权限发生修改,通知刷新本地缓存
flushRoleUserCache(createRoleUserIds, deleteRoleUserIds, finalOrganId);
}
/**
* 跨机构清理角色用户缓存 + 通知刷新本地缓存
*
* @param createRoleUserIds 新增角色-用户关联id
* @param deleteRoleUserIds 删除角色-用户关联id
* @param organId 角色所属机构
*/
private void flushRoleUserCache(Collection<Long> createRoleUserIds, Collection<Long> deleteRoleUserIds, Long organId) {
Long currentOrganId = SecurityFrameworkUtils.getUserOrganId();
// 角色菜单权限发生修改,通知刷新本地缓存
if (CollectionUtil.isNotEmpty(createRoleUserIds) || CollectionUtil.isNotEmpty(deleteRoleUserIds)) {
if (CollUtil.isNotEmpty(createRoleUserIds) || CollUtil.isNotEmpty(deleteRoleUserIds)) {
CompletableFuture.runAsync(() -> {
// 当前操作人和所操作的目标菜单机构不同时,清空USER_ROLE_ID_LIST:*:用户id的缓存
if (ObjectUtil.notEqual(finalOrganId, currentOrganId)) {
if (ObjectUtil.notEqual(organId, currentOrganId)) {
// 获取新增和删除用户id的并集
Collection<Long> delRoleUserIds = CollUtil.union(createRoleUserIds, deleteRoleUserIds);
delRoleUserIds.forEach(delRoleUserId -> {
@@ -397,7 +466,7 @@ public class PermissionServiceImpl implements PermissionService {
log.info("[batchAssignRoleUsers] 批量删除redis[{}]数量:{}", patternKey, batchDelNum);
});
}
redisTemplate.convertAndSend(RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, "");
stringRedisTemplate.convertAndSend(RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, "");
}).exceptionally(e -> {
log.error("[batchAssignRoleUsers] redis 清空USER_ROLE_ID_LIST或message发送失败, topic:{}, 异常:{}", RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, e);
return null;
@@ -461,7 +530,7 @@ public class PermissionServiceImpl implements PermissionService {
Collection<Long> createRoleIds = CollUtil.subtract(roleIdList, dbRoleIds);
Collection<Long> deleteMenuIds = CollUtil.subtract(dbRoleIds, roleIdList);
// 执行新增和删除。对于已经授权的角色,不用做任何处理
if (!CollectionUtil.isEmpty(createRoleIds)) {
if (CollUtil.isNotEmpty(createRoleIds)) {
userRoleMapper.insertBatch(CollectionUtils.convertList(createRoleIds, roleId -> {
UserRoleDO entity = new UserRoleDO();
entity.setUserId(userId);
@@ -470,16 +539,16 @@ public class PermissionServiceImpl implements PermissionService {
return entity;
}));
}
if (!CollectionUtil.isEmpty(deleteMenuIds)) {
if (CollUtil.isNotEmpty(deleteMenuIds)) {
userRoleMapper.deleteListByUserIdAndRoleIdIds(userId, deleteMenuIds);
}
// 角色菜单权限发生修改,通知刷新本地缓存
if (CollectionUtil.isNotEmpty(createRoleIds) || CollectionUtil.isNotEmpty(deleteMenuIds)) {
if (CollUtil.isNotEmpty(createRoleIds) || CollUtil.isNotEmpty(deleteMenuIds)) {
CompletableFuture.runAsync(() -> {
// 移除redis中的缓存
redisTemplate.delete(String.format(String.valueOf(new StringBuffer(RedisKeyConstants.USER_ROLE_ID_LIST).append(":%s:%s")), organId, userId));
redisTemplate.convertAndSend(RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, "");
stringRedisTemplate.delete(String.format(String.valueOf(new StringBuffer(RedisKeyConstants.USER_ROLE_ID_LIST).append(":%s:%s")), organId, userId));
stringRedisTemplate.convertAndSend(RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, "");
}).exceptionally(e -> {
log.error("[assignUserRole] redis message发送失败, topic:{}, 异常:{}", RedisRefreshChannelTopicConstants.PERMISSION_REFRESH, e);
return null;
@@ -0,0 +1,24 @@
package com.cf.imes.module.system.util.organ;
import com.cf.imes.module.system.constants.permission.InternalRoleConstants;
import java.util.Objects;
/**
* 组织相关工具类
*
* @author Gqr
* @since 2024/9/10 15:59
*/
public class OrganUtils {
/**
* 是否内置角色
*
* @param roleId
* @return
*/
public static boolean isOrgRole(Long roleId) {
return Objects.equals(roleId, InternalRoleConstants.ORGAN_ADMIN_ROLE_ID) || Objects.equals(roleId, InternalRoleConstants.ORGAN_STAFF_ROLE_ID);
}
}