Revert "支持角色父子继承,允许子角色单独调整自己有的权限"

This reverts commit 64806dc4
This commit is contained in:
陈博文
2025-06-22 16:16:43 +08:00
parent 036dcb9c31
commit ff493a66b2
16 changed files with 32 additions and 296 deletions

2
.gitignore vendored
View File

@@ -52,6 +52,7 @@ npm-debug.log*
yarn-error.log yarn-error.log
/coverage /coverage
.idea
yarn.lock yarn.lock
package-lock.json package-lock.json
*bak *bak
@@ -72,4 +73,3 @@ functions/mock
screenshot screenshot
.firebase .firebase
sessionStore sessionStore
/http/

View File

@@ -3,12 +3,12 @@
spring: spring:
cloud: cloud:
nacos: nacos:
server-addr: 172.16.46.63:30848 # Nacos 服务器地址 # server-addr: 172.16.46.63:30848 # Nacos 服务器地址
# server-addr: 120.26.250.247:8848 # Nacos 服务器地址 server-addr: 120.26.250.247:8848 # Nacos 服务器地址
username: # Nacos 账号 username: # Nacos 账号
password: # Nacos 密码 password: # Nacos 密码
discovery: # 【配置中心】配置项 discovery: # 【配置中心】配置项
namespace: local # 命名空间。这里使用 dev 开发环境 namespace: dev # 命名空间。这里使用 dev 开发环境
group: DEFAULT_GROUP # 使用的 Nacos 配置分组,默认为 DEFAULT_GROUP group: DEFAULT_GROUP # 使用的 Nacos 配置分组,默认为 DEFAULT_GROUP
metadata: metadata:
version: 1.0.0 # 服务实例的版本号,可用于灰度发布 version: 1.0.0 # 服务实例的版本号,可用于灰度发布

View File

@@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.common.exception.ErrorCode;
* System 错误码枚举类 * System 错误码枚举类
* *
* system 系统,使用 1-002-000-000 段 * system 系统,使用 1-002-000-000 段
* @author chenbowen
*/ */
public interface ErrorCodeConstants { public interface ErrorCodeConstants {
@@ -34,8 +33,6 @@ public interface ErrorCodeConstants {
ErrorCode ROLE_CAN_NOT_UPDATE_SYSTEM_TYPE_ROLE = new ErrorCode(1_002_002_003, "不能操作类型为系统内置的角色"); ErrorCode ROLE_CAN_NOT_UPDATE_SYSTEM_TYPE_ROLE = new ErrorCode(1_002_002_003, "不能操作类型为系统内置的角色");
ErrorCode ROLE_IS_DISABLE = new ErrorCode(1_002_002_004, "名字为【{}】的角色已被禁用"); ErrorCode ROLE_IS_DISABLE = new ErrorCode(1_002_002_004, "名字为【{}】的角色已被禁用");
ErrorCode ROLE_ADMIN_CODE_ERROR = new ErrorCode(1_002_002_005, "标识【{}】不能使用"); ErrorCode ROLE_ADMIN_CODE_ERROR = new ErrorCode(1_002_002_005, "标识【{}】不能使用");
ErrorCode ROLE_CAN_NOT_DELETE_HAS_CHILDREN = new ErrorCode(1_002_002_006, " 角色【{}】存在子角色,不允许删除");
ErrorCode ROLE_PARENT_IS_CHILD = new ErrorCode(1_002_002_007, "不能设置自己的子角色为父角色");
// ========== 用户模块 1-002-003-000 ========== // ========== 用户模块 1-002-003-000 ==========
ErrorCode USER_USERNAME_EXISTS = new ErrorCode(1_002_003_000, "用户账号已经存在"); ErrorCode USER_USERNAME_EXISTS = new ErrorCode(1_002_003_000, "用户账号已经存在");

View File

@@ -5,22 +5,16 @@ import lombok.Getter;
/** /**
* 登录结果的枚举类 * 登录结果的枚举类
* @author chenbowen
*/ */
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum LoginResultEnum { public enum LoginResultEnum {
// 成功 SUCCESS(0), // 成功
SUCCESS(0), BAD_CREDENTIALS(10), // 账号或密码不正确
// 账号或密码不正确 USER_DISABLED(20), // 用户被禁用
BAD_CREDENTIALS(10), CAPTCHA_NOT_FOUND(30), // 图片验证码不存在
// 用户被禁用 CAPTCHA_CODE_ERROR(31), // 图片验证码不正确
USER_DISABLED(20),
// 图片验证码不存在
CAPTCHA_NOT_FOUND(30),
// 图片验证码不正确
CAPTCHA_CODE_ERROR(31),
; ;

View File

@@ -3,10 +3,6 @@ package cn.iocoder.yudao.module.system.enums.permission;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
/**
* @author chenbowen
*/
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum RoleTypeEnum { public enum RoleTypeEnum {
@@ -15,14 +11,10 @@ public enum RoleTypeEnum {
* 内置角色 * 内置角色
*/ */
SYSTEM(1), SYSTEM(1),
/**
* 标准角色
*/
NORMAL(2),
/** /**
* 自定义角色 * 自定义角色
*/ */
CUSTOM(3); CUSTOM(2);
private final Integer type; private final Integer type;

View File

@@ -10,11 +10,6 @@ import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Set; import java.util.Set;

View File

@@ -25,15 +25,11 @@ import org.springframework.web.bind.annotation.*;
import java.io.IOException; import java.io.IOException;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT; import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static java.util.Collections.singleton; import static java.util.Collections.singleton;
/**
* @author chenbowen
*/
@Tag(name = "管理后台 - 角色") @Tag(name = "管理后台 - 角色")
@RestController @RestController
@RequestMapping("/system/role") @RequestMapping("/system/role")
@@ -47,7 +43,7 @@ public class RoleController {
@Operation(summary = "创建角色") @Operation(summary = "创建角色")
@PreAuthorize("@ss.hasPermission('system:role:create')") @PreAuthorize("@ss.hasPermission('system:role:create')")
public CommonResult<Long> createRole(@Valid @RequestBody RoleSaveReqVO createReqVO) { public CommonResult<Long> createRole(@Valid @RequestBody RoleSaveReqVO createReqVO) {
return success(roleService.createRole(createReqVO, createReqVO.getType() == null ? null : Integer.valueOf(createReqVO.getType()))); return success(roleService.createRole(createReqVO, null));
} }
@PutMapping("/update") @PutMapping("/update")
@@ -80,20 +76,6 @@ public class RoleController {
@PreAuthorize("@ss.hasPermission('system:role:query')") @PreAuthorize("@ss.hasPermission('system:role:query')")
public CommonResult<PageResult<RoleRespVO>> getRolePage(RolePageReqVO pageReqVO) { public CommonResult<PageResult<RoleRespVO>> getRolePage(RolePageReqVO pageReqVO) {
PageResult<RoleDO> pageResult = roleService.getRolePage(pageReqVO); PageResult<RoleDO> pageResult = roleService.getRolePage(pageReqVO);
// 获取所有父级角色信息
List<Long> parentIds = pageResult.getList().stream().filter(role -> role.getParentId() != null && role.getParentId() > 0)
.map(RoleDO::getParentId)
.distinct()
.toList();
List<RoleDO> parentRoles = roleService.getRoleList(parentIds);
// 将父级角色信息转换为 id 与 name 的 Map
var parentRoleMap = parentRoles.stream().collect(Collectors.toMap(RoleDO::getId, RoleDO::getName, (v1, v2) -> v1));
// 补全父级角色名称
pageResult.getList().forEach(role -> {
if (role.getParentId() != null && role.getParentId() > 0) {
role.setParentName(parentRoleMap.get(role.getParentId()));
}
});
return success(BeanUtils.toBean(pageResult, RoleRespVO.class)); return success(BeanUtils.toBean(pageResult, RoleRespVO.class));
} }
@@ -105,16 +87,6 @@ public class RoleController {
return success(BeanUtils.toBean(list, RoleRespVO.class)); return success(BeanUtils.toBean(list, RoleRespVO.class));
} }
@GetMapping({"/list-all-extend-simple", "/simple-extend-list"})
@Operation(summary = "获取所有可继承角色精简信息列表", description = "只包含被开启的角色,主要用于前端的下拉选项")
public CommonResult<List<RoleRespVO>> getParentSimpleRoleList() {
List<RoleDO> list = roleService.getRoleListByStatus(singleton(CommonStatusEnum.ENABLE.getStatus()));
// 过滤掉系统内置角色(如有需要)
list.removeIf(role -> role.getType() != null && role.getType().equals(1));
list.sort(Comparator.comparing(RoleDO::getSort));
return success(BeanUtils.toBean(list, RoleRespVO.class));
}
@GetMapping("/export-excel") @GetMapping("/export-excel")
@Operation(summary = "导出角色 Excel") @Operation(summary = "导出角色 Excel")
@ApiAccessLog(operateType = EXPORT) @ApiAccessLog(operateType = EXPORT)

View File

@@ -7,9 +7,6 @@ import lombok.Data;
import java.util.Collections; import java.util.Collections;
import java.util.Set; import java.util.Set;
/**
* @author chenbowen
*/
@Schema(description = "管理后台 - 赋予用户角色 Request VO") @Schema(description = "管理后台 - 赋予用户角色 Request VO")
@Data @Data
public class PermissionAssignUserRoleReqVO { public class PermissionAssignUserRoleReqVO {
@@ -19,6 +16,6 @@ public class PermissionAssignUserRoleReqVO {
private Long userId; private Long userId;
@Schema(description = "角色编号列表", example = "1,3,5") @Schema(description = "角色编号列表", example = "1,3,5")
private Set<Long> roleIds = Collections.emptySet(); private Set<Long> roleIds = Collections.emptySet(); // 兜底
} }

View File

@@ -12,9 +12,6 @@ import lombok.Data;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Set; import java.util.Set;
/**
* @author chenbowen
*/
@Schema(description = "管理后台 - 角色信息 Response VO") @Schema(description = "管理后台 - 角色信息 Response VO")
@Data @Data
@ExcelIgnoreUnannotated @ExcelIgnoreUnannotated
@@ -59,11 +56,4 @@ public class RoleRespVO {
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED, example = "时间戳格式") @Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED, example = "时间戳格式")
private LocalDateTime createTime; private LocalDateTime createTime;
@Schema(description = "父级角色名称", example = "1")
@ExcelProperty("父级角色名称")
private String parentName;
@Schema(description = "父级角色 Id", example = "1")
@ExcelProperty("父级角色 Id")
private Long parentId;
} }

View File

@@ -33,6 +33,7 @@ public class RoleDO extends TenantBaseDO {
private String name; private String name;
/** /**
* 角色标识 * 角色标识
*
* 枚举 * 枚举
*/ */
private String code; private String code;
@@ -42,11 +43,13 @@ public class RoleDO extends TenantBaseDO {
private Integer sort; private Integer sort;
/** /**
* 角色状态 * 角色状态
*
* 枚举 {@link CommonStatusEnum} * 枚举 {@link CommonStatusEnum}
*/ */
private Integer status; private Integer status;
/** /**
* 角色类型 * 角色类型
*
* 枚举 {@link RoleTypeEnum} * 枚举 {@link RoleTypeEnum}
*/ */
private Integer type; private Integer type;
@@ -57,27 +60,16 @@ public class RoleDO extends TenantBaseDO {
/** /**
* 数据范围 * 数据范围
*
* 枚举 {@link DataScopeEnum} * 枚举 {@link DataScopeEnum}
*/ */
private Integer dataScope; private Integer dataScope;
/** /**
* 数据范围(指定部门数组) * 数据范围(指定部门数组)
*
* 适用于 {@link #dataScope} 的值为 {@link DataScopeEnum#DEPT_CUSTOM} 时 * 适用于 {@link #dataScope} 的值为 {@link DataScopeEnum#DEPT_CUSTOM} 时
*/ */
@TableField(typeHandler = JacksonTypeHandler.class) @TableField(typeHandler = JacksonTypeHandler.class)
private Set<Long> dataScopeDeptIds; private Set<Long> dataScopeDeptIds;
/**
* 父级标准角色 Id : 继承的标准角色Id系统角色为 -1、标准角色为 0
*/
private Long parentId;
/**
* 父级角色名称
* 仅用于前端角色界面展示
*/
@TableField(exist = false)
private String parentName;
} }

View File

@@ -1,44 +0,0 @@
package cn.iocoder.yudao.module.system.dal.dataobject.rolemenuexclusion;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
/**
* 角色菜单剔除 DO
*
* @author 管理员
*/
@TableName("system_role_menu_exclusion")
@KeySequence("system_role_menu_exclusion_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RoleMenuExclusionDO extends BaseDO {
/**
* 主键ID
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 角色ID
*/
private Long roleId;
/**
* 菜单ID
*/
private Long menuId;
/**
* 备注
*/
private String remark;
}

View File

@@ -12,9 +12,6 @@ import org.springframework.lang.Nullable;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
/**
* @author chenbowen
*/
@Mapper @Mapper
public interface RoleMapper extends BaseMapperX<RoleDO> { public interface RoleMapper extends BaseMapperX<RoleDO> {
@@ -39,8 +36,4 @@ public interface RoleMapper extends BaseMapperX<RoleDO> {
return selectList(RoleDO::getStatus, statuses); return selectList(RoleDO::getStatus, statuses);
} }
default long selectCountByParentId(Long parentId) {
return selectCount(RoleDO::getParentId, parentId);
}
} }

View File

@@ -1,39 +0,0 @@
package cn.iocoder.yudao.module.system.dal.mysql.rolemenuexclusion;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.system.dal.dataobject.rolemenuexclusion.RoleMenuExclusionDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.Collection;
import java.util.List;
/**
* 角色菜单剔除 Mapper
*
* @author 管理员
*/
@Mapper
public interface RoleMenuExclusionMapper extends BaseMapperX<RoleMenuExclusionDO> {
/**
* 根据角色编号,查询角色菜单剔除列表
*
* @param roleIds 角色编号
*/
default List<RoleMenuExclusionDO> selectMenuIdListByRoleId(Collection<Long> roleIds) {
return selectList(RoleMenuExclusionDO::getRoleId, roleIds);
}
/**
* 根据角色编号,菜单编号,删除角色菜单剔除列表
*
* @param roleId 角色编号
* @param menuIds 菜单编号
*/
default void deleteListByRoleIdAndMenuIds(Long roleId, Collection<Long> menuIds) {
delete(new LambdaQueryWrapper<RoleMenuExclusionDO>()
.eq(RoleMenuExclusionDO::getRoleId, roleId)
.in(RoleMenuExclusionDO::getMenuId, menuIds));
}
}

View File

@@ -12,10 +12,8 @@ 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.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleMenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleMenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.rolemenuexclusion.RoleMenuExclusionDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMenuMapper; import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMenuMapper;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper; import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.rolemenuexclusion.RoleMenuExclusionMapper;
import cn.iocoder.yudao.module.system.dal.redis.RedisKeyConstants; import cn.iocoder.yudao.module.system.dal.redis.RedisKeyConstants;
import cn.iocoder.yudao.module.system.enums.permission.DataScopeEnum; import cn.iocoder.yudao.module.system.enums.permission.DataScopeEnum;
import cn.iocoder.yudao.module.system.service.dept.DeptService; import cn.iocoder.yudao.module.system.service.dept.DeptService;
@@ -36,7 +34,6 @@ import java.util.*;
import java.util.function.Supplier; 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.convertSet;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.singleton;
import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString; import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;
/** /**
@@ -61,8 +58,6 @@ public class PermissionServiceImpl implements PermissionService {
private DeptService deptService; private DeptService deptService;
@Resource @Resource
private AdminUserService userService; private AdminUserService userService;
@Resource
private RoleMenuExclusionMapper roleMenuExclusionMapper;
@Override @Override
public boolean hasAnyPermissions(Long userId, String... permissions) { public boolean hasAnyPermissions(Long userId, String... permissions) {
@@ -145,49 +140,22 @@ public class PermissionServiceImpl implements PermissionService {
}) })
public void assignRoleMenu(Long roleId, Set<Long> menuIds) { public void assignRoleMenu(Long roleId, Set<Long> menuIds) {
// 获得角色拥有菜单编号 // 获得角色拥有菜单编号
Set<Long> dbMenuIds = convertSet(getRoleMenuListByRoleId(roleId)); Set<Long> dbMenuIds = convertSet(roleMenuMapper.selectListByRoleId(roleId), RoleMenuDO::getMenuId);
// 获取父级角色拥有的菜单编号
Set<Long> parentRoleIds = roleService.getAllParentAndSelfRoleIds(singleton(roleId));
// 移除自身角色编号
parentRoleIds.remove(roleId);
Set<Long> dbInheritedMenuIds = convertSet(roleMenuMapper.selectListByRoleId(parentRoleIds), RoleMenuDO::getMenuId);
// 计算新增和删除的菜单编号 // 计算新增和删除的菜单编号
Set<Long> menuIdList = CollUtil.emptyIfNull(menuIds); Set<Long> menuIdList = CollUtil.emptyIfNull(menuIds);
Collection<Long> createMenuIds = CollUtil.subtract(menuIdList, dbMenuIds); Collection<Long> createMenuIds = CollUtil.subtract(menuIdList, dbMenuIds);
Collection<Long> deleteMenuIds = CollUtil.subtract(dbMenuIds, menuIdList); Collection<Long> deleteMenuIds = CollUtil.subtract(dbMenuIds, menuIdList);
// 执行新增和删除。对于已经授权的菜单,不用进行新增和删除,处理排除关系即可 // 执行新增和删除。对于已经授权的菜单,不用做任何处理
if (CollUtil.isNotEmpty(createMenuIds)) { if (CollUtil.isNotEmpty(createMenuIds)) {
Set<Long> inheritedCreateMenuIds = new HashSet<>(dbInheritedMenuIds); roleMenuMapper.insertBatch(CollectionUtils.convertList(createMenuIds, menuId -> {
inheritedCreateMenuIds.retainAll(createMenuIds); RoleMenuDO entity = new RoleMenuDO();
if (CollUtil.isNotEmpty(inheritedCreateMenuIds)) { entity.setRoleId(roleId);
// 不需要新增,只需要检查是否存在排除关系,如果存在,则标记排除关系失效 entity.setMenuId(menuId);
roleMenuExclusionMapper.deleteListByRoleIdAndMenuIds(roleId, inheritedCreateMenuIds); return entity;
createMenuIds.removeAll(inheritedCreateMenuIds); }));
}
if (CollUtil.isNotEmpty(createMenuIds)) {
roleMenuMapper.insertBatch(CollectionUtils.convertList(createMenuIds, menuId -> {
RoleMenuDO entity = new RoleMenuDO();
entity.setRoleId(roleId);
entity.setMenuId(menuId);
return entity;
}));
}
} }
if (CollUtil.isNotEmpty(deleteMenuIds)) { if (CollUtil.isNotEmpty(deleteMenuIds)) {
Set<Long> inheritedDeleteMenuIds = new HashSet<>(dbInheritedMenuIds); roleMenuMapper.deleteListByRoleIdAndMenuIds(roleId, deleteMenuIds);
inheritedDeleteMenuIds.retainAll(deleteMenuIds);
if (CollUtil.isNotEmpty(inheritedDeleteMenuIds)) {
// 标记排除
roleMenuExclusionMapper.insertBatch(CollectionUtils.convertList(inheritedDeleteMenuIds, menuId -> {
RoleMenuExclusionDO entity = new RoleMenuExclusionDO();
entity.setRoleId(roleId);
entity.setMenuId(menuId);
return entity;
}));
}
if (CollUtil.isNotEmpty(deleteMenuIds)) {
roleMenuMapper.deleteListByRoleIdAndMenuIds(roleId, deleteMenuIds);
}
} }
} }
@@ -222,14 +190,8 @@ public class PermissionServiceImpl implements PermissionService {
if (roleService.hasAnySuperAdmin(roleIds)) { if (roleService.hasAnySuperAdmin(roleIds)) {
return convertSet(menuService.getMenuList(), MenuDO::getId); return convertSet(menuService.getMenuList(), MenuDO::getId);
} }
// 递归获取所有父角色id // 如果是非管理员的情况下,获得拥有的菜单编号
Set<Long> allRoleIds = roleService.getAllParentAndSelfRoleIds(roleIds); return convertSet(roleMenuMapper.selectListByRoleId(roleIds), RoleMenuDO::getMenuId);
// 如果是非管理员的情况下,获得拥有的菜单编号(含父角色,需要剔除当前角色排除的菜单)
Set<Long> menuIds = convertSet(roleMenuMapper.selectListByRoleId(allRoleIds), RoleMenuDO::getMenuId);
// 排除当前角色排除的菜单编号
Set<Long> excludeMenuIds = convertSet(roleMenuExclusionMapper.selectMenuIdListByRoleId(allRoleIds), RoleMenuExclusionDO::getMenuId);
menuIds.removeAll(excludeMenuIds);
return menuIds;
} }
@Override @Override

View File

@@ -121,11 +121,4 @@ public interface RoleService {
*/ */
void validateRoleList(Collection<Long> ids); void validateRoleList(Collection<Long> ids);
/**
* 获取所有父角色id递归
* @param roleIds 当前角色id集合
* @return 包含自身和所有父级的id集合
*/
Set<Long> getAllParentAndSelfRoleIds(Collection<Long> roleIds);
} }

View File

@@ -22,7 +22,6 @@ import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.service.impl.DiffParseFunction; import com.mzt.logapi.service.impl.DiffParseFunction;
import com.mzt.logapi.starter.annotation.LogRecord; import com.mzt.logapi.starter.annotation.LogRecord;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
@@ -31,7 +30,6 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
@@ -64,11 +62,8 @@ public class RoleServiceImpl implements RoleService {
// 2. 插入到数据库 // 2. 插入到数据库
RoleDO role = BeanUtils.toBean(createReqVO, RoleDO.class) RoleDO role = BeanUtils.toBean(createReqVO, RoleDO.class)
.setType(ObjectUtil.defaultIfNull(type, RoleTypeEnum.CUSTOM.getType())) .setType(ObjectUtil.defaultIfNull(type, RoleTypeEnum.CUSTOM.getType()))
// 如果类型不为公司角色则设置 parentId 为 0
.setParentId(!ObjectUtil.equal(RoleTypeEnum.CUSTOM.getType(), type) ? 0L : createReqVO.getParentId())
.setStatus(ObjUtil.defaultIfNull(createReqVO.getStatus(), CommonStatusEnum.ENABLE.getStatus())) .setStatus(ObjUtil.defaultIfNull(createReqVO.getStatus(), CommonStatusEnum.ENABLE.getStatus()))
// 默认可查看所有数据。原因是,可能一些项目不需要项目权限 .setDataScope(DataScopeEnum.ALL.getScope()); // 默认可查看所有数据。原因是,可能一些项目不需要项目权限
.setDataScope(DataScopeEnum.ALL.getScope());
roleMapper.insert(role); roleMapper.insert(role);
// 3. 记录操作日志上下文 // 3. 记录操作日志上下文
@@ -85,11 +80,6 @@ public class RoleServiceImpl implements RoleService {
RoleDO role = validateRoleForUpdate(updateReqVO.getId()); RoleDO role = validateRoleForUpdate(updateReqVO.getId());
// 1.2 校验角色的唯一字段是否重复 // 1.2 校验角色的唯一字段是否重复
validateRoleDuplicate(updateReqVO.getName(), updateReqVO.getCode(), updateReqVO.getId()); validateRoleDuplicate(updateReqVO.getName(), updateReqVO.getCode(), updateReqVO.getId());
// 1.3 校验角色当前修改的父角色是否为当前角色的子角色
if (updateReqVO.getParentId() != null && !updateReqVO.getParentId().equals(0L) && isChildRole(updateReqVO.getId(), updateReqVO.getParentId())) {
throw exception(ROLE_PARENT_IS_CHILD, updateReqVO.getName());
}
// 2. 更新到数据库 // 2. 更新到数据库
RoleDO updateObj = BeanUtils.toBean(updateReqVO, RoleDO.class); RoleDO updateObj = BeanUtils.toBean(updateReqVO, RoleDO.class);
@@ -115,7 +105,6 @@ public class RoleServiceImpl implements RoleService {
} }
@Override @Override
@SneakyThrows
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@CacheEvict(value = RedisKeyConstants.ROLE, key = "#id") @CacheEvict(value = RedisKeyConstants.ROLE, key = "#id")
@LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_DELETE_SUB_TYPE, bizNo = "{{#id}}", @LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_DELETE_SUB_TYPE, bizNo = "{{#id}}",
@@ -124,11 +113,6 @@ public class RoleServiceImpl implements RoleService {
// 1. 校验是否可以更新 // 1. 校验是否可以更新
RoleDO role = validateRoleForUpdate(id); RoleDO role = validateRoleForUpdate(id);
// 1.1 校验角色是否存在子角色,如果存在,则不允许删除
if (roleMapper.selectCountByParentId(id) > 0) {
throw exception(ROLE_CAN_NOT_DELETE_HAS_CHILDREN , role.getName());
}
// 2.1 标记删除 // 2.1 标记删除
roleMapper.deleteById(id); roleMapper.deleteById(id);
// 2.2 删除相关数据 // 2.2 删除相关数据
@@ -140,6 +124,7 @@ public class RoleServiceImpl implements RoleService {
/** /**
* 校验角色的唯一字段是否重复 * 校验角色的唯一字段是否重复
*
* 1. 是否存在相同名字的角色 * 1. 是否存在相同名字的角色
* 2. 是否存在相同编码的角色 * 2. 是否存在相同编码的角色
* *
@@ -215,7 +200,7 @@ public class RoleServiceImpl implements RoleService {
if (CollectionUtil.isEmpty(ids)) { if (CollectionUtil.isEmpty(ids)) {
return Collections.emptyList(); return Collections.emptyList();
} }
return roleMapper.selectByIds(ids); return roleMapper.selectBatchIds(ids);
} }
@Override @Override
@@ -251,7 +236,7 @@ public class RoleServiceImpl implements RoleService {
return; return;
} }
// 获得角色信息 // 获得角色信息
List<RoleDO> roles = roleMapper.selectByIds(ids); List<RoleDO> roles = roleMapper.selectBatchIds(ids);
Map<Long, RoleDO> roleMap = convertMap(roles, RoleDO::getId); Map<Long, RoleDO> roleMap = convertMap(roles, RoleDO::getId);
// 校验 // 校验
ids.forEach(id -> { ids.forEach(id -> {
@@ -265,29 +250,6 @@ public class RoleServiceImpl implements RoleService {
}); });
} }
@Override
public Set<Long> getAllParentAndSelfRoleIds(Collection<Long> roleIds) {
// 递归获取所有父角色id最多递归5层防止环
if (CollUtil.isEmpty(roleIds)) {
return Collections.emptySet();
}
RoleServiceImpl self = getSelf();
return roleIds.stream()
.flatMap(id -> {
Set<Long> chain = new LinkedHashSet<>();
Long current = id;
for (int depth = 0; current != null && current > 0 && depth < 5 && chain.add(current); depth++) {
RoleDO role = self.getRoleFromCache(current);
if (role == null || role.getParentId() == null || role.getParentId() <= 0) {
break;
}
current = role.getParentId();
}
return chain.stream();
})
.collect(Collectors.toSet());
}
/** /**
* 获得自身的代理对象,解决 AOP 生效问题 * 获得自身的代理对象,解决 AOP 生效问题
* *
@@ -297,24 +259,4 @@ public class RoleServiceImpl implements RoleService {
return SpringUtil.getBean(getClass()); return SpringUtil.getBean(getClass());
} }
/**
* 判断 parentId 是否为 roleId 的子孙节点递归最多5次
*/
private boolean isChildRole(Long roleId, Long parentId) {
return isChildRole(roleId, parentId, 0);
}
private boolean isChildRole(Long roleId, Long parentId, int depth) {
if (roleId.equals(parentId)) {
return true;
}
if (depth >= 5) {
return false;
}
RoleDO parent = roleMapper.selectById(parentId);
if (parent == null || parent.getParentId() == null || parent.getParentId().equals(0L) || parent.getParentId().equals(-1L)) {
return false;
}
return isChildRole(roleId, parent.getParentId(), depth + 1);
}
} }