refactor: 优化角色分配功能相关代码

This commit is contained in:
2024-11-11 20:59:16 +08:00
parent d4b02ba918
commit ad3f8329dd
14 changed files with 61 additions and 148 deletions

View File

@@ -35,17 +35,9 @@ public class SysConstants {
public static final Integer YES = 1;
/**
* 管理员角色编码
* 超管用户 ID
*/
public static final String ADMIN_ROLE_CODE = "admin";
/**
* 超管角色组ID
*/
public static final Long SUPER_ROLE_ID = 1L;
/**
* 超管账号ID
*/
public static final Long SUPER_ADMIN_ID = 1L;
public static final Long SUPER_USER_ID = 1L;
/**
* 顶级部门 ID
@@ -57,6 +49,16 @@ public class SysConstants {
*/
public static final Long SUPER_PARENT_ID = 0L;
/**
* 超管角色编码
*/
public static final String SUPER_ROLE_CODE = "admin";
/**
* 超管角色 ID
*/
public static final Long SUPER_ROLE_ID = 1L;
/**
* 全部权限标识
*/

View File

@@ -100,7 +100,7 @@ public class UserContext implements Serializable {
if (CollUtil.isEmpty(roleCodes)) {
return false;
}
return roleCodes.contains(SysConstants.ADMIN_ROLE_CODE);
return roleCodes.contains(SysConstants.SUPER_ROLE_CODE);
}
/**

View File

@@ -145,8 +145,8 @@ public class LoginServiceImpl implements LoginService {
user.setAvatar(authUser.getAvatar());
user.setDeptId(SysConstants.SUPER_DEPT_ID);
Long userId = userService.add(user);
RoleDO role = roleService.getByCode(SysConstants.ADMIN_ROLE_CODE);
userRoleService.add(Collections.singletonList(role.getId()), userId);
RoleDO role = roleService.getByCode(SysConstants.SUPER_ROLE_CODE);
userRoleService.assignRolesToUser(Collections.singletonList(role.getId()), userId);
userSocial = new UserSocialDO();
userSocial.setUserId(userId);
userSocial.setSource(source);
@@ -170,7 +170,7 @@ public class LoginServiceImpl implements LoginService {
}
// 查询菜单列表
Set<MenuResp> menuSet = new LinkedHashSet<>();
if (roleCodeSet.contains(SysConstants.ADMIN_ROLE_CODE)) {
if (roleCodeSet.contains(SysConstants.SUPER_ROLE_CODE)) {
menuSet.addAll(menuService.listAll());
} else {
roleCodeSet.forEach(roleCode -> menuSet.addAll(menuService.listByRoleCode(roleCode)));

View File

@@ -16,13 +16,11 @@
package top.continew.admin.system.service;
import cn.hutool.core.lang.tree.Tree;
import top.continew.admin.system.model.entity.DeptDO;
import top.continew.admin.system.model.query.DeptQuery;
import top.continew.admin.system.model.req.DeptReq;
import top.continew.admin.system.model.resp.DeptResp;
import top.continew.starter.data.mp.service.IService;
import top.continew.starter.extension.crud.model.query.SortQuery;
import top.continew.starter.extension.crud.service.BaseService;
import java.util.List;
@@ -58,14 +56,4 @@ public interface DeptService extends BaseService<DeptResp, DeptResp, DeptQuery,
* @return 部门数量
*/
int countByNames(List<String> deptNames);
/**
* 部门用户树
*
* @param query 部门查询条件
* @param sortQuery 排序条件
* @param isSimple 是否只返回简单部门树
* @return 部门数量
*/
List<Tree<String>> treeWithUsers(DeptQuery query, SortQuery sortQuery, boolean isSimple);
}

View File

@@ -29,22 +29,22 @@ import java.util.List;
public interface UserRoleService {
/**
* 新增
* 批量分配角色给指定用户
*
* @param roleIds 角色 ID 列表
* @param userId 用户 ID
* @return 是否新增成功true成功false无变更/失败)
* @return 是否成功true成功false无变更/失败)
*/
boolean add(List<Long> roleIds, Long userId);
boolean assignRolesToUser(List<Long> roleIds, Long userId);
/**
* 关联用户
* 批量分配角色给用户
*
* @param roleId 角色id
* @param userIds 用户id列表
* @return 是否新增成功true成功false无变更/失败)
* @param roleId 角色 ID
* @param userIds 用户 ID 列表
* @return 是否成功true成功false无变更/失败)
*/
boolean bindUserIds(Long roleId, List<Long> userIds);
boolean assignRoleToUsers(Long roleId, List<Long> userIds);
/**
* 根据用户 ID 删除
@@ -83,5 +83,4 @@ public interface UserRoleService {
* @return 是否已关联true已关联false未关联
*/
boolean isRoleIdExists(List<Long> roleIds);
}

View File

@@ -17,12 +17,7 @@
package top.continew.admin.system.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
@@ -31,26 +26,21 @@ import top.continew.admin.common.enums.DisEnableStatusEnum;
import top.continew.admin.system.mapper.DeptMapper;
import top.continew.admin.system.model.entity.DeptDO;
import top.continew.admin.system.model.query.DeptQuery;
import top.continew.admin.system.model.query.UserQuery;
import top.continew.admin.system.model.req.DeptReq;
import top.continew.admin.system.model.resp.DeptResp;
import top.continew.admin.system.model.resp.user.UserResp;
import top.continew.admin.system.service.DeptService;
import top.continew.admin.system.service.RoleDeptService;
import top.continew.admin.system.service.UserService;
import top.continew.starter.core.util.ReflectUtils;
import top.continew.starter.core.util.validate.CheckUtils;
import top.continew.starter.data.core.enums.DatabaseType;
import top.continew.starter.data.core.util.MetaUtils;
import top.continew.starter.extension.crud.annotation.TreeField;
import top.continew.starter.extension.crud.model.query.SortQuery;
import top.continew.starter.extension.crud.service.impl.BaseServiceImpl;
import top.continew.starter.extension.crud.util.TreeUtils;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* 部门业务实现
@@ -90,75 +80,6 @@ public class DeptServiceImpl extends BaseServiceImpl<DeptMapper, DeptDO, DeptRes
return (int)this.count(Wrappers.<DeptDO>lambdaQuery().in(DeptDO::getName, deptNames));
}
@Override
public List<Tree<String>> treeWithUsers(DeptQuery query, SortQuery sortQuery, boolean isSimple) {
List<DeptResp> list = this.list(query, sortQuery);
if (CollUtil.isEmpty(list)) {
return new ArrayList<>(0);
} else {
TreeNodeConfig treeNodeConfig = TreeUtils.DEFAULT_CONFIG;
TreeField treeField = this.getListClass().getDeclaredAnnotation(TreeField.class);
if (!isSimple) {
treeNodeConfig = TreeUtils.genTreeNodeConfig(treeField);
}
// 创建一个部门ID到用户的映射
UserQuery userQuery = new UserQuery();
userQuery.setStatus(DisEnableStatusEnum.ENABLE);
Map<Long, List<UserResp>> userMap = userService.list(userQuery, null)
.stream()
.collect(Collectors.groupingBy(UserResp::getDeptId));
String rootId = "dept_0";
return TreeUtil.build(list, rootId, treeNodeConfig, (node, tree) -> {
Long departmentId = ReflectUtil.invoke(node, CharSequenceUtil.genGetter(treeField
.value()), new Object[0]);
String uniqueDeptId = "dept_" + departmentId;
tree.setId(uniqueDeptId);
Long parentId = ReflectUtil.invoke(node, CharSequenceUtil.genGetter(treeField
.parentIdKey()), new Object[0]);
tree.setParentId(parentId != null ? "dept_" + parentId : null);
tree.setName(ReflectUtil.invoke(node, CharSequenceUtil.genGetter(treeField.nameKey()), new Object[0]));
tree.setWeight(ReflectUtil.invoke(node, CharSequenceUtil.genGetter(treeField
.weightKey()), new Object[0]));
tree.putExtra("origId", departmentId);
tree.putExtra("isUser", false);
// 添加用户信息到树节点
if (userMap.containsKey(departmentId)) {
List<UserResp> userList = userMap.get(departmentId);
List<Tree<String>> userTrees = userList.stream().map(user -> {
Tree<String> userTree = new Tree<>();
String uniqueUserId = "user_" + user.getId();
String userAliasName = user.getUsername() + "(" + user.getNickname() + ")";
userTree.setId(uniqueUserId);
userTree.setParentId(uniqueDeptId);
userTree.setName(userAliasName);
userTree.setWeight(0);
userTree.putExtra("origId", user.getId()); // 添加原始用户ID
userTree.putExtra("isUser", true); // 添加原始用户ID
return userTree;
}).collect(Collectors.toList());
tree.setChildren(userTrees);
}
if (!isSimple) {
List<Field> fieldList = ReflectUtils.getNonStaticFields(this.getListClass());
fieldList.removeIf((f) -> {
return CharSequenceUtil.equalsAnyIgnoreCase(f.getName(), new CharSequence[] {treeField.value(),
treeField.parentIdKey(), treeField.nameKey(), treeField.weightKey(), treeField
.childrenKey()});
});
fieldList.forEach((f) -> {
tree.putExtra(f.getName(), ReflectUtil.invoke(node, CharSequenceUtil.genGetter(f
.getName()), new Object[0]));
});
}
});
}
}
@Override
protected void beforeAdd(DeptReq req) {
String name = req.getName();

View File

@@ -94,7 +94,7 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleRes
}
// 更新信息
super.update(req, id);
if (SysConstants.ADMIN_ROLE_CODE.equals(req.getCode())) {
if (SysConstants.SUPER_ROLE_CODE.equals(req.getCode())) {
return;
}
// 保存角色和菜单关联
@@ -136,7 +136,7 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleRes
super.fill(obj);
if (obj instanceof RoleDetailResp detail) {
Long roleId = detail.getId();
if (SysConstants.ADMIN_ROLE_CODE.equals(detail.getCode())) {
if (SysConstants.SUPER_ROLE_CODE.equals(detail.getCode())) {
List<MenuResp> list = menuService.listAll();
List<Long> menuIds = list.stream().map(MenuResp::getId).toList();
detail.setMenuIds(menuIds);
@@ -150,7 +150,7 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleRes
public Set<String> listPermissionByUserId(Long userId) {
Set<String> roleCodeSet = this.listCodeByUserId(userId);
// 超级管理员赋予全部权限
if (roleCodeSet.contains(SysConstants.ADMIN_ROLE_CODE)) {
if (roleCodeSet.contains(SysConstants.SUPER_ROLE_CODE)) {
return CollUtil.newHashSet(SysConstants.ALL_PERMISSION);
}
return menuService.listPermissionByUserId(userId);

View File

@@ -45,7 +45,7 @@ public class UserRoleServiceImpl implements UserRoleService {
@Override
@Transactional(rollbackFor = Exception.class)
public boolean add(List<Long> roleIds, Long userId) {
public boolean assignRolesToUser(List<Long> roleIds, Long userId) {
// 检查是否有变更
List<Long> oldRoleIdList = baseMapper.lambdaQuery()
.select(UserRoleDO::getRoleId)
@@ -65,21 +65,21 @@ public class UserRoleServiceImpl implements UserRoleService {
}
@Override
public boolean bindUserIds(Long roleId, List<Long> userIds) {
@Transactional(rollbackFor = Exception.class)
public boolean assignRoleToUsers(Long roleId, List<Long> userIds) {
// 检查是否有变更
List<Long> oldRoleIdList = baseMapper.lambdaQuery()
List<Long> oldUserIdList = baseMapper.lambdaQuery()
.select(UserRoleDO::getUserId)
.eq(UserRoleDO::getRoleId, roleId)
.list()
.stream()
.map(UserRoleDO::getRoleId)
.map(UserRoleDO::getUserId)
.toList();
if (CollUtil.isEmpty(CollUtil.disjunction(userIds, oldRoleIdList))) {
if (CollUtil.isEmpty(CollUtil.disjunction(userIds, oldUserIdList))) {
return false;
}
if (SysConstants.SUPER_ROLE_ID.equals(roleId) && !userIds.contains(SysConstants.SUPER_ADMIN_ID)) {
CheckUtils.throwIf(true, "能移除管理员默认超管角色");
}
CheckUtils.throwIf(SysConstants.SUPER_ROLE_ID.equals(roleId) && !userIds
.contains(SysConstants.SUPER_USER_ID), "允许变更超管用户角色");
// 删除原有关联
baseMapper.lambdaUpdate().eq(UserRoleDO::getRoleId, roleId).remove();
// 保存最新关联

View File

@@ -144,7 +144,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
Long userId = user.getId();
baseMapper.lambdaUpdate().set(UserDO::getPwdResetTime, LocalDateTime.now()).eq(UserDO::getId, userId).update();
// 保存用户和角色关联
userRoleService.add(req.getRoleIds(), userId);
userRoleService.assignRolesToUser(req.getRoleIds(), userId);
}
@Override
@@ -174,7 +174,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
newUser.setId(id);
baseMapper.updateById(newUser);
// 保存用户和角色关联
boolean isSaveUserRoleSuccess = userRoleService.add(req.getRoleIds(), id);
boolean isSaveUserRoleSuccess = userRoleService.assignRolesToUser(req.getRoleIds(), id);
// 如果禁用用户,则踢出在线用户
if (DisEnableStatusEnum.DISABLE.equals(newStatus)) {
onlineUserService.kickOut(id);
@@ -389,7 +389,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
public void updateRole(UserRoleUpdateReq updateReq, Long id) {
super.getById(id);
// 保存用户和角色关联
userRoleService.add(updateReq.getRoleIds(), id);
userRoleService.assignRolesToUser(updateReq.getRoleIds(), id);
}
@Override

View File

@@ -78,12 +78,6 @@ public class CommonController {
return deptService.tree(query, sortQuery, true);
}
@Operation(summary = "查询部门用户树", description = "查询树结构的部门列表")
@GetMapping("/tree/deptWithUsers")
public List<Tree<String>> listDeptWithUsersTree(DeptQuery query, SortQuery sortQuery) {
return deptService.treeWithUsers(query, sortQuery, true);
}
@Operation(summary = "查询菜单树", description = "查询树结构的菜单列表")
@GetMapping("/tree/menu")
public List<Tree<Long>> listMenuTree(MenuQuery query, SortQuery sortQuery) {

View File

@@ -73,7 +73,7 @@ public class NoticeController extends BaseController<NoticeService, NoticeResp,
}
// 校验通知范围
if (NoticeScopeEnum.USER.equals(req.getNoticeScope())) {
ValidationUtils.throwIfEmpty(req.getNoticeUsers(), "请选择通知用户");
ValidationUtils.throwIfEmpty(req.getNoticeUsers(), "通知用户不能为空");
}
}
}

View File

@@ -18,9 +18,13 @@ package top.continew.admin.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.continew.admin.system.model.query.RoleQuery;
@@ -42,6 +46,7 @@ import java.util.List;
* @since 2023/2/8 23:11
*/
@Tag(name = "角色管理 API")
@Validated
@RestController
@RequiredArgsConstructor
@CrudRequestMapping(value = "/system/role", api = {Api.PAGE, Api.GET, Api.ADD, Api.UPDATE, Api.DELETE})
@@ -49,16 +54,18 @@ public class RoleController extends BaseController<RoleService, RoleResp, RoleDe
private final UserRoleService userRoleService;
@Operation(summary = "查询角色关联用户", description = "查询角色组绑定的关联用户")
@GetMapping("/listRoleUsers/{id}")
public List<Long> listUsers(@PathVariable("id") Long roleId) {
return userRoleService.listUserIdByRoleId(roleId);
@Operation(summary = "查询角色关联用户", description = "查询角色关联用户ID列表")
@Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH)
@GetMapping("/{id}/user")
public List<Long> listUser(@PathVariable("id") Long id) {
return userRoleService.listUserIdByRoleId(id);
}
@Operation(summary = "关联用户", description = "批量关联用户")
@SaCheckPermission("system:role:bindUsers")
@PostMapping("/bindUsers/{id}")
public void bindUsers(@PathVariable("id") Long roleId, @RequestBody List<Long> userIds) {
userRoleService.bindUserIds(roleId, userIds);
@Operation(summary = "分配角色给用户", description = "批量分配角色给用户")
@SaCheckPermission("system:role:assign")
@PostMapping("/{id}/user")
public void assignToUsers(@PathVariable("id") Long id,
@Validated @NotEmpty(message = "用户ID列表不能为空") @RequestBody List<Long> userIds) {
userRoleService.assignRoleToUsers(id, userIds);
}
}

View File

@@ -23,6 +23,7 @@ VALUES
(1033, '新增', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:add', 3, 1, 1, NOW(), NULL, NULL),
(1034, '修改', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:update', 4, 1, 1, NOW(), NULL, NULL),
(1035, '删除', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:delete', 5, 1, 1, NOW(), NULL, NULL),
(1036, '分配', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:assign', 6, 1, 1, NOW(), NULL, NULL),
(1050, '菜单管理', 1000, 2, '/system/menu', 'SystemMenu', 'system/menu/index', NULL, 'menu', b'0', b'0', b'0', NULL, 3, 1, 1, NOW(), NULL, NULL),
(1051, '列表', 1050, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:menu:list', 1, 1, 1, NOW(), NULL, NULL),

View File

@@ -23,6 +23,7 @@ VALUES
(1033, '新增', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:add', 3, 1, 1, NOW(), NULL, NULL),
(1034, '修改', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:update', 4, 1, 1, NOW(), NULL, NULL),
(1035, '删除', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:delete', 5, 1, 1, NOW(), NULL, NULL),
(1036, '分配', 1030, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:role:assign', 6, 1, 1, NOW(), NULL, NULL),
(1050, '菜单管理', 1000, 2, '/system/menu', 'SystemMenu', 'system/menu/index', NULL, 'menu', false, false, false, NULL, 3, 1, 1, NOW(), NULL, NULL),
(1051, '列表', 1050, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'system:menu:list', 1, 1, 1, NOW(), NULL, NULL),