Skip to content

Commit

Permalink
refactor: 优化角色分配功能相关代码
Browse files Browse the repository at this point in the history
  • Loading branch information
Charles7c committed Nov 11, 2024
1 parent d4b02ba commit ad3f832
Show file tree
Hide file tree
Showing 14 changed files with 61 additions and 148 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;

/**
* 全部权限标识
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public boolean isAdmin() {
if (CollUtil.isEmpty(roleCodes)) {
return false;
}
return roleCodes.contains(SysConstants.ADMIN_ROLE_CODE);
return roleCodes.contains(SysConstants.SUPER_ROLE_CODE);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,8 @@ public String socialLogin(AuthUser authUser) {
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);
Expand All @@ -170,7 +170,7 @@ public List<RouteResp> buildRouteTree(Long userId) {
}
// 查询菜单列表
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)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,22 @@
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 删除
Expand Down Expand Up @@ -83,5 +83,4 @@ public interface UserRoleService {
* @return 是否已关联(true:已关联;false:未关联)
*/
boolean isRoleIdExists(List<Long> roleIds);

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -31,26 +26,21 @@
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;

/**
* 部门业务实现
Expand Down Expand Up @@ -90,75 +80,6 @@ public int countByNames(List<String> deptNames) {
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public void update(RoleReq req, Long id) {
}
// 更新信息
super.update(req, id);
if (SysConstants.ADMIN_ROLE_CODE.equals(req.getCode())) {
if (SysConstants.SUPER_ROLE_CODE.equals(req.getCode())) {
return;
}
// 保存角色和菜单关联
Expand Down Expand Up @@ -136,7 +136,7 @@ protected void fill(Object obj) {
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);
Expand All @@ -150,7 +150,7 @@ protected void fill(Object obj) {
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -65,21 +65,21 @@ public boolean add(List<Long> roleIds, Long userId) {
}

@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();
// 保存最新关联
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public void afterAdd(UserReq req, UserDO user) {
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
Expand Down Expand Up @@ -174,7 +174,7 @@ public void update(UserReq req, Long id) {
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);
Expand Down Expand Up @@ -389,7 +389,7 @@ public void resetPassword(UserPasswordResetReq req, Long id) {
public void updateRole(UserRoleUpdateReq updateReq, Long id) {
super.getById(id);
// 保存用户和角色关联
userRoleService.add(updateReq.getRoleIds(), id);
userRoleService.assignRolesToUser(updateReq.getRoleIds(), id);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,6 @@ public List<Tree<Long>> listDeptTree(DeptQuery query, SortQuery sortQuery) {
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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ private void check(NoticeReq req) {
}
// 校验通知范围
if (NoticeScopeEnum.USER.equals(req.getNoticeScope())) {
ValidationUtils.throwIfEmpty(req.getNoticeUsers(), "请选择通知用户");
ValidationUtils.throwIfEmpty(req.getNoticeUsers(), "通知用户不能为空");
}
}
}
Loading

0 comments on commit ad3f832

Please sign in to comment.