From 49b4eedfc0ca13bfb0c4fdfab952b0574c754153 Mon Sep 17 00:00:00 2001 From: YunaiV Date: Thu, 12 May 2022 22:57:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20UserRole=20=E7=9A=84?= =?UTF-8?q?=E7=BC=93=E5=AD=98=EF=BC=8C=E5=AE=8C=E5=96=84=E6=9D=83=E9=99=90?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E7=9A=84=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/admin/auth/AuthController.java | 4 +- .../dal/mysql/permission/UserRoleMapper.java | 6 + .../permission/UserRoleRefreshConsumer.java | 29 ++ .../permission/UserRoleRefreshMessage.java | 21 ++ .../permission/PermissionProducer.java | 9 + .../service/permission/PermissionService.java | 28 +- .../permission/PermissionServiceImpl.java | 151 +++++++--- .../permission/PermissionServiceTest.java | 267 +++++++++++++++++- 8 files changed, 451 insertions(+), 64 deletions(-) create mode 100644 yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/consumer/permission/UserRoleRefreshConsumer.java create mode 100644 yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/message/permission/UserRoleRefreshMessage.java diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java index 64cda89d7..3d38175b5 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java @@ -93,7 +93,7 @@ public class AuthController { return null; } // 获得角色列表 - Set roleIds = permissionService.getUserRoleIds(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); + Set roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); List roleList = roleService.getRolesFromCache(roleIds); // 获得菜单列表 List menuList = permissionService.getRoleMenuListFromCache(roleIds, @@ -107,7 +107,7 @@ public class AuthController { @ApiOperation("获得登录用户的菜单列表") public CommonResult> getMenus() { // 获得角色列表 - Set roleIds = permissionService.getUserRoleIds(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); + Set roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); // 获得用户拥有的菜单列表 List menuList = permissionService.getRoleMenuListFromCache(roleIds, SetUtils.asSet(MenuTypeEnum.DIR.getType(), MenuTypeEnum.MENU.getType()), // 只要目录和菜单类型 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/UserRoleMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/UserRoleMapper.java index e2ab6ce20..51323d749 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/UserRoleMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/permission/UserRoleMapper.java @@ -4,8 +4,10 @@ import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; import java.util.Collection; +import java.util.Date; import java.util.List; @Mapper @@ -36,4 +38,8 @@ public interface UserRoleMapper extends BaseMapperX { default List selectListByRoleIds(Collection roleIds) { return selectList(UserRoleDO::getRoleId, roleIds); } + + @Select("SELECT COUNT(*) FROM system_user_role WHERE update_time > #{maxUpdateTime}") + Long selectCountByUpdateTimeGt(Date maxUpdateTime); + } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/consumer/permission/UserRoleRefreshConsumer.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/consumer/permission/UserRoleRefreshConsumer.java new file mode 100644 index 000000000..d580f58e2 --- /dev/null +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/consumer/permission/UserRoleRefreshConsumer.java @@ -0,0 +1,29 @@ +package cn.iocoder.yudao.module.system.mq.consumer.permission; + +import cn.iocoder.yudao.framework.mq.core.pubsub.AbstractChannelMessageListener; +import cn.iocoder.yudao.module.system.mq.message.permission.UserRoleRefreshMessage; +import cn.iocoder.yudao.module.system.service.permission.PermissionService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * 针对 {@link UserRoleRefreshMessage} 的消费者 + * + * @author 芋道源码 + */ +@Component +@Slf4j +public class UserRoleRefreshConsumer extends AbstractChannelMessageListener { + + @Resource + private PermissionService permissionService; + + @Override + public void onMessage(UserRoleRefreshMessage message) { + log.info("[onMessage][收到 User 与 Role 的关联刷新消息]"); + permissionService.initLocalCache(); + } + +} diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/message/permission/UserRoleRefreshMessage.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/message/permission/UserRoleRefreshMessage.java new file mode 100644 index 000000000..1644f5c00 --- /dev/null +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/message/permission/UserRoleRefreshMessage.java @@ -0,0 +1,21 @@ +package cn.iocoder.yudao.module.system.mq.message.permission; + +import cn.iocoder.yudao.framework.mq.core.pubsub.AbstractChannelMessage; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 用户与角色的数据刷新 Message + * + * @author 芋道源码 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class UserRoleRefreshMessage extends AbstractChannelMessage { + + @Override + public String getChannel() { + return "system.user-role.refresh"; + } + +} diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/producer/permission/PermissionProducer.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/producer/permission/PermissionProducer.java index 56c8e3179..e3c4047c2 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/producer/permission/PermissionProducer.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/mq/producer/permission/PermissionProducer.java @@ -2,6 +2,7 @@ package cn.iocoder.yudao.module.system.mq.producer.permission; import cn.iocoder.yudao.module.system.mq.message.permission.RoleMenuRefreshMessage; import cn.iocoder.yudao.framework.mq.core.RedisMQTemplate; +import cn.iocoder.yudao.module.system.mq.message.permission.UserRoleRefreshMessage; import org.springframework.stereotype.Component; import javax.annotation.Resource; @@ -23,4 +24,12 @@ public class PermissionProducer { redisMQTemplate.send(message); } + /** + * 发送 {@link UserRoleRefreshMessage} 消息 + */ + public void sendUserRoleRefreshMessage() { + UserRoleRefreshMessage message = new UserRoleRefreshMessage(); + redisMQTemplate.send(message); + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionService.java index 11fe1ab88..beee0947e 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionService.java @@ -37,13 +37,13 @@ public interface PermissionService extends SecurityPermissionFrameworkService, D Collection menusStatuses); /** - * 获得用户拥有的角色编号集合 + * 获得用户拥有的角色编号集合,从缓存中获取 * * @param userId 用户编号 * @param roleStatuses 角色状态集合. 允许为空,为空时不过滤 * @return 角色编号集合 */ - Set getUserRoleIds(Long userId, @Nullable Collection roleStatuses); + Set getUserRoleIdsFromCache(Long userId, @Nullable Collection roleStatuses); /** * 获得角色拥有的菜单编号集合 @@ -53,6 +53,14 @@ public interface PermissionService extends SecurityPermissionFrameworkService, D */ Set getRoleMenuIds(Long roleId); + /** + * 获得拥有多个角色的用户编号集合 + * + * @param roleIds 角色编号集合 + * @return 用户编号集合 + */ + Set getUserRoleIdListByRoleIds(Collection roleIds); + /** * 设置角色菜单 * @@ -69,14 +77,6 @@ public interface PermissionService extends SecurityPermissionFrameworkService, D */ Set getUserRoleIdListByUserId(Long userId); - /** - * 获得拥有某个角色的用户编号集合 - * - * @param roleId 角色编号 - * @return 用户编号集合 - */ - Set getUserRoleIdListByRoleId(Long roleId); - /** * 设置用户角色 * @@ -115,12 +115,4 @@ public interface PermissionService extends SecurityPermissionFrameworkService, D */ void processUserDeleted(Long userId); - /** - * 获得拥有多个角色的用户编号集合 - * - * @param roleIds 角色编号集合 - * @return 用户编号集合 - */ - Set getUserRoleIdListByRoleIds(Collection roleIds); - } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java index 76e2055b3..294c9c978 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java @@ -23,10 +23,13 @@ import cn.iocoder.yudao.module.system.enums.permission.DataScopeEnum; import cn.iocoder.yudao.module.system.mq.producer.permission.PermissionProducer; import cn.iocoder.yudao.module.system.service.dept.DeptService; import cn.iocoder.yudao.module.system.service.user.AdminUserService; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; +import lombok.Getter; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; @@ -40,6 +43,8 @@ import javax.annotation.Resource; import java.util.*; import java.util.function.Supplier; +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet; +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.getMaxValue; import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; import static java.util.Collections.singleton; @@ -65,6 +70,8 @@ public class PermissionServiceImpl implements PermissionService { * * 这里声明 volatile 修饰的原因是,每次刷新时,直接修改指向 */ + @Getter + @Setter // 单元测试 private volatile Multimap roleMenuCache; /** * 菜单编号与角色编号的缓存映射 @@ -73,11 +80,29 @@ public class PermissionServiceImpl implements PermissionService { * * 这里声明 volatile 修饰的原因是,每次刷新时,直接修改指向 */ + @Getter private volatile Multimap menuRoleCache; /** - * 缓存菜单的最大更新时间,用于后续的增量轮询,判断是否有更新 + * 缓存 RoleMenu 的最大更新时间,用于后续的增量轮询,判断是否有更新 */ - private volatile Date maxUpdateTime; + @Getter + private volatile Date roleMenuMaxUpdateTime; + + /** + * 用户编号与角色编号的缓存映射 + * key:用户编号 + * value:角色编号的数组 + * + * 这里声明 volatile 修饰的原因是,每次刷新时,直接修改指向 + */ + @Getter + @Setter // 单元测试需要 + private volatile Map> userRoleCache; + /** + * 缓存 UserRole 的最大更新时间,用于后续的增量轮询,判断是否有更新 + */ + @Getter + private volatile Date userRoleMaxUpdateTime; @Resource private RoleMenuMapper roleMenuMapper; @@ -104,15 +129,21 @@ public class PermissionServiceImpl implements PermissionService { @Lazy // 注入自己,所以延迟加载 private PermissionService self; - /** - * 初始化 {@link #roleMenuCache} 和 {@link #menuRoleCache} 缓存 - */ @Override @PostConstruct @TenantIgnore // 初始化缓存,无需租户过滤 public void initLocalCache() { + initUserRoleLocalCache(); + initRoleMenuLocalCache(); + } + + /** + * 初始化 {@link #roleMenuCache} 和 {@link #menuRoleCache} 缓存 + */ + @VisibleForTesting + void initRoleMenuLocalCache() { // 获取角色与菜单的关联列表,如果有更新 - List roleMenuList = loadRoleMenuIfUpdate(maxUpdateTime); + List roleMenuList = loadRoleMenuIfUpdate(roleMenuMaxUpdateTime); if (CollUtil.isEmpty(roleMenuList)) { return; } @@ -126,8 +157,27 @@ public class PermissionServiceImpl implements PermissionService { }); roleMenuCache = roleMenuCacheBuilder.build(); menuRoleCache = menuRoleCacheBuilder.build(); - maxUpdateTime = CollectionUtils.getMaxValue(roleMenuList, RoleMenuDO::getUpdateTime); - log.info("[initLocalCache][初始化角色与菜单的关联数量为 {}]", roleMenuList.size()); + roleMenuMaxUpdateTime = getMaxValue(roleMenuList, RoleMenuDO::getUpdateTime); + log.info("[initRoleMenuLocalCache][初始化角色与菜单的关联数量为 {}]", roleMenuList.size()); + } + + /** + * 初始化 {@link #userRoleCache} 缓存 + */ + @VisibleForTesting + void initUserRoleLocalCache() { + // 获取用户与角色的关联列表,如果有更新 + List userRoleList = loadUserRoleIfUpdate(userRoleMaxUpdateTime); + if (CollUtil.isEmpty(userRoleList)) { + return; + } + + // 初始化 userRoleCache 缓存 + ImmutableMultimap.Builder userRoleCacheBuilder = ImmutableMultimap.builder(); + userRoleList.forEach(userRoleDO -> userRoleCacheBuilder.put(userRoleDO.getUserId(), userRoleDO.getRoleId())); + userRoleCache = CollectionUtils.convertMultiMap2(userRoleList, UserRoleDO::getUserId, UserRoleDO::getRoleId); + userRoleMaxUpdateTime = getMaxValue(userRoleList, UserRoleDO::getUpdateTime); + log.info("[initUserRoleLocalCache][初始化用户与角色的关联数量为 {}]", userRoleList.size()); } @Scheduled(fixedDelay = SCHEDULER_PERIOD, initialDelay = SCHEDULER_PERIOD) @@ -156,6 +206,27 @@ public class PermissionServiceImpl implements PermissionService { return roleMenuMapper.selectList(); } + /** + * 如果用户与角色的关联发生变化,从数据库中获取最新的全量用户与角色的关联。 + * 如果未发生变化,则返回空 + * + * @param maxUpdateTime 当前角色与菜单的关联的最大更新时间 + * @return 角色与菜单的关联列表 + */ + protected List loadUserRoleIfUpdate(Date maxUpdateTime) { + // 第一步,判断是否要更新。 + if (maxUpdateTime == null) { // 如果更新时间为空,说明 DB 一定有新数据 + log.info("[loadUserRoleIfUpdate][首次加载全量用户与角色的关联]"); + } else { // 判断数据库中是否有更新的用户与角色的关联 + if (userRoleMapper.selectCountByUpdateTimeGt(maxUpdateTime) == 0) { + return null; + } + log.info("[loadUserRoleIfUpdate][增量加载全量用户与角色的关联]"); + } + // 第二步,如果有更新,则从数据库加载所有用户与角色的关联 + return userRoleMapper.selectList(); + } + @Override public List getRoleMenuListFromCache(Collection roleIds, Collection menuTypes, Collection menusStatuses) { @@ -176,35 +247,33 @@ public class PermissionServiceImpl implements PermissionService { } @Override - public Set getUserRoleIds(Long userId, Collection roleStatuses) { - List userRoleList = userRoleMapper.selectListByUserId(userId); + public Set getUserRoleIdsFromCache(Long userId, Collection roleStatuses) { + Set roleIds = new HashSet<>(userRoleCache.get(userId)); // 过滤角色状态 if (CollectionUtil.isNotEmpty(roleStatuses)) { - userRoleList.removeIf(userRoleDO -> { - RoleDO role = roleService.getRoleFromCache(userRoleDO.getRoleId()); + roleIds.removeIf(roleId -> { + RoleDO role = roleService.getRoleFromCache(roleId); return role == null || !roleStatuses.contains(role.getStatus()); }); } - return CollectionUtils.convertSet(userRoleList, UserRoleDO::getRoleId); + return roleIds; } @Override public Set getRoleMenuIds(Long roleId) { // 如果是管理员的情况下,获取全部菜单编号 - RoleDO role = roleService.getRole(roleId); - if (roleService.hasAnySuperAdmin(Collections.singletonList(role))) { - return CollectionUtils.convertSet(menuService.getMenus(), MenuDO::getId); + if (roleService.hasAnySuperAdmin(Collections.singleton(roleId))) { + return convertSet(menuService.getMenus(), MenuDO::getId); } // 如果是非管理员的情况下,获得拥有的菜单编号 - return CollectionUtils.convertSet(roleMenuMapper.selectListByRoleId(roleId), - RoleMenuDO::getMenuId); + return convertSet(roleMenuMapper.selectListByRoleId(roleId), RoleMenuDO::getMenuId); } @Override @Transactional(rollbackFor = Exception.class) public void assignRoleMenu(Long roleId, Set menuIds) { // 获得角色拥有菜单编号 - Set dbMenuIds = CollectionUtils.convertSet(roleMenuMapper.selectListByRoleId(roleId), + Set dbMenuIds = convertSet(roleMenuMapper.selectListByRoleId(roleId), RoleMenuDO::getMenuId); // 计算新增和删除的菜单编号 Collection createMenuIds = CollUtil.subtract(menuIds, dbMenuIds); @@ -234,20 +303,21 @@ public class PermissionServiceImpl implements PermissionService { @Override public Set getUserRoleIdListByUserId(Long userId) { - return CollectionUtils.convertSet(userRoleMapper.selectListByUserId(userId), + return convertSet(userRoleMapper.selectListByUserId(userId), UserRoleDO::getRoleId); } @Override - public Set getUserRoleIdListByRoleId(Long roleId) { - return CollectionUtils.convertSet(userRoleMapper.selectListByRoleId(roleId), - UserRoleDO::getRoleId); + public Set getUserRoleIdListByRoleIds(Collection roleIds) { + return convertSet(userRoleMapper.selectListByRoleIds(roleIds), + UserRoleDO::getUserId); } @Override + @Transactional(rollbackFor = Exception.class) public void assignUserRole(Long userId, Set roleIds) { // 获得角色拥有角色编号 - Set dbRoleIds = CollectionUtils.convertSet(userRoleMapper.selectListByUserId(userId), + Set dbRoleIds = convertSet(userRoleMapper.selectListByUserId(userId), UserRoleDO::getRoleId); // 计算新增和删除的角色编号 Collection createRoleIds = CollUtil.subtract(roleIds, dbRoleIds); @@ -264,6 +334,15 @@ public class PermissionServiceImpl implements PermissionService { if (!CollectionUtil.isEmpty(deleteMenuIds)) { userRoleMapper.deleteListByUserIdAndRoleIdIds(userId, deleteMenuIds); } + // 发送刷新消息. 注意,需要事务提交后,在进行发送刷新消息。不然 db 还未提交,结果缓存先刷新了 + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + + @Override + public void afterCommit() { + permissionProducer.sendUserRoleRefreshMessage(); + } + + }); } @Override @@ -284,6 +363,7 @@ public class PermissionServiceImpl implements PermissionService { @Override public void afterCommit() { permissionProducer.sendRoleMenuRefreshMessage(); + permissionProducer.sendUserRoleRefreshMessage(); } }); @@ -305,8 +385,17 @@ public class PermissionServiceImpl implements PermissionService { } @Override + @Transactional(rollbackFor = Exception.class) public void processUserDeleted(Long userId) { userRoleMapper.deleteListByUserId(userId); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + + @Override + public void afterCommit() { + permissionProducer.sendUserRoleRefreshMessage(); + } + + }); } @Override @@ -322,7 +411,7 @@ public class PermissionServiceImpl implements PermissionService { } // 获得当前登录的角色。如果为空,说明没有权限 - Set roleIds = getUserRoleIds(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); + Set roleIds = getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); if (CollUtil.isEmpty(roleIds)) { return false; } @@ -357,7 +446,7 @@ public class PermissionServiceImpl implements PermissionService { } // 获得当前登录的角色。如果为空,说明没有权限 - Set roleIds = getUserRoleIds(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); + Set roleIds = getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus())); if (CollUtil.isEmpty(roleIds)) { return false; } @@ -365,7 +454,7 @@ public class PermissionServiceImpl implements PermissionService { if (roleService.hasAnySuperAdmin(roleIds)) { return true; } - Set userRoles = CollectionUtils.convertSet(roleService.getRolesFromCache(roleIds), + Set userRoles = convertSet(roleService.getRolesFromCache(roleIds), RoleDO::getCode); return CollUtil.containsAny(userRoles, Sets.newHashSet(roles)); } @@ -375,7 +464,7 @@ public class PermissionServiceImpl implements PermissionService { public DeptDataPermissionRespDTO getDeptDataPermission(Long userId) { DeptDataPermissionRespDTO result = new DeptDataPermissionRespDTO(); // 获得用户的角色 - Set roleIds = getUserRoleIds(userId, singleton(CommonStatusEnum.ENABLE.getStatus())); + Set roleIds = getUserRoleIdsFromCache(userId, singleton(CommonStatusEnum.ENABLE.getStatus())); if (CollUtil.isEmpty(roleIds)) { return result; } @@ -425,10 +514,4 @@ public class PermissionServiceImpl implements PermissionService { return result; } - @Override - public Set getUserRoleIdListByRoleIds(Collection roleIds) { - return CollectionUtils.convertSet(userRoleMapper.selectListByRoleIds(roleIds), - UserRoleDO::getUserId); - } - } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java index 12fddf38a..d2ef99e80 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceTest.java @@ -1,10 +1,13 @@ package cn.iocoder.yudao.module.system.service.permission; import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.map.MapUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; +import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.datapermission.core.dept.service.dto.DeptDataPermissionRespDTO; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO; +import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleMenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO; @@ -17,20 +20,24 @@ import cn.iocoder.yudao.module.system.enums.permission.DataScopeEnum; import cn.iocoder.yudao.module.system.mq.producer.permission.PermissionProducer; import cn.iocoder.yudao.module.system.service.dept.DeptService; import cn.iocoder.yudao.module.system.service.user.AdminUserService; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.Multimap; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.util.List; +import java.util.*; +import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; -import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; -import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -62,6 +69,226 @@ public class PermissionServiceTest extends BaseDbUnitTest { @MockBean private PermissionProducer permissionProducer; + @Test + public void testInitRoleMenuLocalCache() { + // mock 数据 + RoleMenuDO roleMenuDO01 = randomPojo(RoleMenuDO.class, o -> o.setRoleId(1L).setMenuId(10L)); + roleMenuMapper.insert(roleMenuDO01); + RoleMenuDO roleMenuDO02 = randomPojo(RoleMenuDO.class, o -> o.setRoleId(1L).setMenuId(20L)); + roleMenuMapper.insert(roleMenuDO02); + + // 调用 + permissionService.initRoleMenuLocalCache(); + // 断言 roleMenuCache 缓存 + assertEquals(1, permissionService.getRoleMenuCache().keySet().size()); + assertEquals(asList(10L, 20L), permissionService.getRoleMenuCache().get(1L)); + // 断言 menuRoleCache 缓存 + assertEquals(2, permissionService.getMenuRoleCache().size()); + assertEquals(singletonList(1L), permissionService.getMenuRoleCache().get(10L)); + assertEquals(singletonList(1L), permissionService.getMenuRoleCache().get(20L)); + // 断言 maxUpdateTime 缓存 + Date maxUpdateTime = permissionService.getRoleMenuMaxUpdateTime(); + assertEquals(ObjectUtils.max(roleMenuDO01.getUpdateTime(), roleMenuDO02.getUpdateTime()), maxUpdateTime); + } + + @Test + public void testInitUserRoleLocalCache() { + // mock 数据 + UserRoleDO userRoleDO01 = randomPojo(UserRoleDO.class, o -> o.setUserId(1L).setRoleId(10L)); + userRoleMapper.insert(userRoleDO01); + UserRoleDO roleMenuDO02 = randomPojo(UserRoleDO.class, o -> o.setUserId(1L).setRoleId(20L)); + userRoleMapper.insert(roleMenuDO02); + + // 调用 + permissionService.initUserRoleLocalCache(); + // 断言 roleMenuCache 缓存 + assertEquals(1, permissionService.getUserRoleCache().size()); + assertEquals(asSet(10L, 20L), permissionService.getUserRoleCache().get(1L)); + // 断言 maxUpdateTime 缓存 + Date maxUpdateTime = permissionService.getUserRoleMaxUpdateTime(); + assertEquals(ObjectUtils.max(userRoleDO01.getUpdateTime(), roleMenuDO02.getUpdateTime()), maxUpdateTime); + } + + @Test + public void testGetRoleMenuListFromCache_superAdmin() { + // 准备参数 + Collection roleIds = singletonList(100L); + Collection menuTypes = asList(2, 3); + Collection menusStatuses = asList(0, 1); + // mock 方法 + List roleList = singletonList(randomPojo(RoleDO.class, o -> o.setId(100L))); + when(roleService.getRolesFromCache(eq(roleIds))).thenReturn(roleList); + when(roleService.hasAnySuperAdmin(same(roleList))).thenReturn(true); + List menuList = randomPojoList(MenuDO.class); + when(menuService.getMenuListFromCache(eq(menuTypes), eq(menusStatuses))).thenReturn(menuList); + + // 调用 + List result = permissionService.getRoleMenuListFromCache(roleIds, menuTypes, menusStatuses); + // 断言 + assertSame(menuList, result); + } + + @Test + public void testGetRoleMenuListFromCache_normal() { + // 准备参数 + Collection roleIds = asSet(100L, 200L); + Collection menuTypes = asList(2, 3); + Collection menusStatuses = asList(0, 1); + // mock 方法 + Multimap roleMenuCache = ImmutableMultimap.builder().put(100L, 1000L) + .put(200L, 2000L).put(200L, 2001L).build(); + permissionService.setRoleMenuCache(roleMenuCache); + List menuList = randomPojoList(MenuDO.class); + when(menuService.getMenuListFromCache(eq(asList(1000L, 2000L, 2001L)), eq(menuTypes), eq(menusStatuses))).thenReturn(menuList); + + // 调用 + List result = permissionService.getRoleMenuListFromCache(roleIds, menuTypes, menusStatuses); + // 断言 + assertSame(menuList, result); + } + + @Test + public void testGetUserRoleIdsFromCache() { + // 准备参数 + Long userId = 1L; + Collection roleStatuses = singleton(CommonStatusEnum.ENABLE.getStatus()); + // mock 方法 + Map> userRoleCache = MapUtil.>builder() + .put(1L, asSet(10L, 20L)).build(); + permissionService.setUserRoleCache(userRoleCache); + RoleDO roleDO01 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(roleService.getRoleFromCache(eq(10L))).thenReturn(roleDO01); + RoleDO roleDO02 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); + when(roleService.getRoleFromCache(eq(20L))).thenReturn(roleDO02); + + // 调用 + Set roleIds = permissionService.getUserRoleIdsFromCache(userId, roleStatuses); + // 断言 + assertEquals(asSet(10L), roleIds); + } + + @Test + public void testGetRoleMenuIds_superAdmin() { + // 准备参数 + Long roleId = 100L; + // mock 方法 + when(roleService.hasAnySuperAdmin(eq(singleton(100L)))).thenReturn(true); + List menuList = singletonList(randomPojo(MenuDO.class).setId(1L)); + when(menuService.getMenus()).thenReturn(menuList); + + // 调用 + Set menuIds = permissionService.getRoleMenuIds(roleId); + // 断言 + assertEquals(singleton(1L), menuIds); + } + + @Test + public void testGetRoleMenuIds_normal() { + // 准备参数 + Long roleId = 100L; + // mock 数据 + RoleMenuDO roleMenu01 = randomPojo(RoleMenuDO.class).setRoleId(100L).setMenuId(1L); + roleMenuMapper.insert(roleMenu01); + RoleMenuDO roleMenu02 = randomPojo(RoleMenuDO.class).setRoleId(100L).setMenuId(2L); + roleMenuMapper.insert(roleMenu02); + + // 调用 + Set menuIds = permissionService.getRoleMenuIds(roleId); + // 断言 + assertEquals(asSet(1L, 2L), menuIds); + } + + @Test + public void testAssignRoleMenu() { + // 准备参数 + Long roleId = 1L; + Set menuIds = asSet(200L, 300L); + // mock 数据 + RoleMenuDO roleMenu01 = randomPojo(RoleMenuDO.class).setRoleId(1L).setMenuId(100L); + roleMenuMapper.insert(roleMenu01); + RoleMenuDO roleMenu02 = randomPojo(RoleMenuDO.class).setRoleId(1L).setMenuId(200L); + roleMenuMapper.insert(roleMenu02); + + // 调用 + permissionService.assignRoleMenu(roleId, menuIds); + // 断言 + List roleMenuList = roleMenuMapper.selectList(); + assertEquals(2, roleMenuList.size()); + assertEquals(1L, roleMenuList.get(0).getRoleId()); + assertEquals(200L, roleMenuList.get(0).getMenuId()); + assertEquals(1L, roleMenuList.get(1).getRoleId()); + assertEquals(300L, roleMenuList.get(1).getMenuId()); + verify(permissionProducer).sendRoleMenuRefreshMessage(); + } + + @Test + public void testAssignUserRole() { + // 准备参数 + Long userId = 1L; + Set roleIds = asSet(200L, 300L); + // mock 数据 + UserRoleDO userRole01 = randomPojo(UserRoleDO.class).setUserId(1L).setRoleId(100L); + userRoleMapper.insert(userRole01); + UserRoleDO userRole02 = randomPojo(UserRoleDO.class).setUserId(1L).setRoleId(200L); + userRoleMapper.insert(userRole02); + + // 调用 + permissionService.assignUserRole(userId, roleIds); + // 断言 + List userRoleDOList = userRoleMapper.selectList(); + assertEquals(2, userRoleDOList.size()); + assertEquals(1L, userRoleDOList.get(0).getUserId()); + assertEquals(200L, userRoleDOList.get(0).getRoleId()); + assertEquals(1L, userRoleDOList.get(1).getUserId()); + assertEquals(300L, userRoleDOList.get(1).getRoleId()); + verify(permissionProducer).sendUserRoleRefreshMessage(); + } + + @Test + public void testGetUserRoleIdListByUserId() { + // 准备参数 + Long userId = 1L; + // mock 数据 + UserRoleDO userRoleDO01 = randomPojo(UserRoleDO.class, o -> o.setUserId(1L).setRoleId(10L)); + userRoleMapper.insert(userRoleDO01); + UserRoleDO roleMenuDO02 = randomPojo(UserRoleDO.class, o -> o.setUserId(1L).setRoleId(20L)); + userRoleMapper.insert(roleMenuDO02); + + // 调用 + Set result = permissionService.getUserRoleIdListByUserId(userId); + // 断言 + assertEquals(asSet(10L, 20L), result); + } + + @Test + public void testGetUserRoleIdListByRoleIds() { + // 准备参数 + Collection roleIds = asSet(10L, 20L); + // mock 数据 + UserRoleDO userRoleDO01 = randomPojo(UserRoleDO.class, o -> o.setUserId(1L).setRoleId(10L)); + userRoleMapper.insert(userRoleDO01); + UserRoleDO roleMenuDO02 = randomPojo(UserRoleDO.class, o -> o.setUserId(2L).setRoleId(20L)); + userRoleMapper.insert(roleMenuDO02); + + // 调用 + Set result = permissionService.getUserRoleIdListByRoleIds(roleIds); + // 断言 + assertEquals(asSet(1L, 2L), result); + } + + @Test + public void testAssignRoleDataScope() { + // 准备参数 + Long roleId = 1L; + Integer dataScope = 2; + Set dataScopeDeptIds = asSet(10L, 20L); + + // 调用 + permissionService.assignRoleDataScope(roleId, dataScope, dataScopeDeptIds); + // 断言 + verify(roleService).updateRoleDataScope(eq(roleId), eq(dataScope), eq(dataScopeDeptIds)); + } + @Test public void testProcessRoleDeleted() { // 准备参数 @@ -89,6 +316,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { assertPojoEquals(dbUserRoles.get(0), userRoleDO02); // 断言调用 verify(permissionProducer).sendRoleMenuRefreshMessage(); + verify(permissionProducer).sendUserRoleRefreshMessage(); } @Test @@ -127,14 +355,33 @@ public class PermissionServiceTest extends BaseDbUnitTest { List dbUserRoles = userRoleMapper.selectList(); assertEquals(1, dbUserRoles.size()); assertPojoEquals(dbUserRoles.get(0), userRoleDO02); + // 断言调用 + verify(permissionProducer).sendUserRoleRefreshMessage(); } +// @Test +// public void testHasAnyRoles_superAdmin() { +// // 准备参数 +// String[] roles = new String[]{"yunai", "tudou"}; +// // mock 方法 +// List roleList = singletonList(randomPojo(RoleDO.class, o -> o.setId(100L))); +// when(roleService.getRolesFromCache(eq(roleIds))).thenReturn(roleList); +// when(roleService.hasAnySuperAdmin(same(roleList))).thenReturn(true); +// List menuList = randomPojoList(MenuDO.class); +// when(menuService.getMenuListFromCache(eq(menuTypes), eq(menusStatuses))).thenReturn(menuList); +// +// // 调用 +// List result = permissionService.getRoleMenuListFromCache(roleIds, menuTypes, menusStatuses); +// // 断言 +// assertSame(menuList, result); +// } + @Test public void testGetDeptDataPermission_All() { // 准备参数 Long userId = 1L; // mock 用户的角色编号 - userRoleMapper.insert(new UserRoleDO().setUserId(userId).setRoleId(2L)); + permissionService.setUserRoleCache(MapUtil.>builder().put(1L, asSet(2L)).build()); // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.ALL.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); @@ -154,7 +401,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // 准备参数 Long userId = 1L; // mock 用户的角色编号 - userRoleMapper.insert(new UserRoleDO().setUserId(userId).setRoleId(2L)); + permissionService.setUserRoleCache(MapUtil.>builder().put(1L, asSet(2L)).build()); // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_CUSTOM.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); @@ -164,7 +411,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用 // 调用 - DeptDataPermissionRespDTO result = permissionService.getDeptDataPermission(1L); + DeptDataPermissionRespDTO result = permissionService.getDeptDataPermission(userId); // 断言 assertFalse(result.getAll()); assertFalse(result.getSelf()); @@ -178,7 +425,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // 准备参数 Long userId = 1L; // mock 用户的角色编号 - userRoleMapper.insert(new UserRoleDO().setUserId(userId).setRoleId(2L)); + permissionService.setUserRoleCache(MapUtil.>builder().put(1L, asSet(2L)).build()); // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_ONLY.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); @@ -188,7 +435,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用 // 调用 - DeptDataPermissionRespDTO result = permissionService.getDeptDataPermission(1L); + DeptDataPermissionRespDTO result = permissionService.getDeptDataPermission(userId); // 断言 assertFalse(result.getAll()); assertFalse(result.getSelf()); @@ -201,7 +448,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // 准备参数 Long userId = 1L; // mock 用户的角色编号 - userRoleMapper.insert(new UserRoleDO().setUserId(userId).setRoleId(2L)); + permissionService.setUserRoleCache(MapUtil.>builder().put(1L, asSet(2L)).build()); // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_AND_CHILD.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus())); @@ -229,7 +476,7 @@ public class PermissionServiceTest extends BaseDbUnitTest { // 准备参数 Long userId = 1L; // mock 用户的角色编号 - userRoleMapper.insert(new UserRoleDO().setUserId(userId).setRoleId(2L)); + permissionService.setUserRoleCache(MapUtil.>builder().put(1L, asSet(2L)).build()); // mock 获得用户的角色 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.SELF.getScope()) .setStatus(CommonStatusEnum.ENABLE.getStatus()));