Unverified Commit 355b1e05 authored by G-XD's avatar G-XD Committed by GitHub

feat: Changes related to RBAC functionality (#2184)

* refactor: update menu type & update listMenus api * feat: api authentication by sa-token * chore: fix dinky_sys_role_menu table name * chore: update menu type field of mysql/pg
parent fc7ff5bb
......@@ -21,10 +21,10 @@ package org.dinky.controller;
import org.dinky.data.annotation.Log;
import org.dinky.data.dto.RoleMenuDto;
import org.dinky.data.dto.TreeNodeDTO;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Menu;
import org.dinky.data.result.ProTableResult;
import org.dinky.data.result.Result;
import org.dinky.service.MenuService;
......@@ -39,8 +39,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -73,13 +71,13 @@ public class MenuController {
/**
* list Menus
*
* @param para {@link JsonNode}
* @return {@link ProTableResult} with {@link Menu}
* @return {@link Result} with {@link List<TreeNodeDTO>}
*/
@GetMapping("listMenus")
@ApiOperation("Query Menu List")
public Result<List<Menu>> listMenus() {
return Result.data(menuService.list());
public Result<List<TreeNodeDTO>> listMenus() {
List<Menu> menus = menuService.list();
return Result.data(menuService.buildMenuTreeSelect(menus));
}
/**
......
......@@ -77,4 +77,6 @@ public class BaseConstant {
public static final String UNIQUE = "0";
public static final String NOT_UNIQUE = "1";
/** admin user id */
public static final int ADMIN_ID = 1;
}
......@@ -54,4 +54,20 @@ public class TreeNodeDTO {
this.children = children;
this.size = size;
}
public TreeNodeDTO(
Integer id,
String name,
String path,
Integer parentId,
String desc,
List<TreeNodeDTO> children) {
this.id = id;
this.name = name;
this.path = path;
this.parentId = parentId;
this.desc = desc;
this.children = children;
this.isLeaf = (children == null || children.size() == 0);
}
}
......@@ -79,7 +79,7 @@ public class Menu implements Serializable {
private String icon;
private Integer type;
private String type;
private Double orderNum;
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.vo;
import org.dinky.data.model.Menu;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Treeselect树结构实体类
*
* @author ruoyi
*/
@Data
@NoArgsConstructor
public class TreeSelect implements Serializable {
private static final long serialVersionUID = 1L;
/** 节点ID */
private Integer id;
/** 节点名称 */
private String label;
/** 子节点 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<TreeSelect> children;
public TreeSelect(Menu menu) {
this.id = menu.getId();
this.label = menu.getName();
this.children =
menu.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());
}
}
......@@ -62,7 +62,7 @@ public interface MenuMapper extends SuperMapper<Menu> {
* @param userId 用户ID
* @return 权限列表
*/
List<String> selectMenuPermsByUserId(Long userId);
List<String> selectMenuPermsByUserId(Integer userId);
List<Menu> listMenus4SuperAdmin();
......@@ -106,4 +106,12 @@ public interface MenuMapper extends SuperMapper<Menu> {
* @return 结果
*/
Menu checkMenuNameUnique(@Param("name") String name, @Param("parentId") Long parentId);
/**
* Query permissions based on role ID.
*
* @param roleId role ID
* @return permission List
*/
List<String> selectMenuPermsByRoleId(Integer roleId);
}
......@@ -37,5 +37,19 @@ public interface RoleMapper extends SuperMapper<Role> {
List<Role> getRoleByTenantIdAndIds(
@Param("tenantId") String tenantId, @Param("roleIds") Set<Integer> roleIds);
int deleteByIds(@Param("ids") List<Integer> ids);
/**
* Query roles by user ID.
*
* @param userId user ID
* @return role list
*/
List<Role> selectRolePermissionByUserId(Integer userId);
/**
* Obtain a list of role selection boxes by user ID.
*
* @param userId user ID
* @return result
*/
List<Integer> selectRoleListByUserId(Integer userId);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.security;
import org.dinky.data.constant.BaseConstant;
import org.dinky.service.MenuService;
import org.dinky.service.RoleService;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.base.Preconditions;
import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
/** Permission service by sa-token. TODO add cache */
@Component
public class PermissionService implements StpInterface {
@Autowired private RoleService roleService;
@Autowired private MenuService menuService;
/**
* Get permission list by user ID.
*
* @param userId user id
* @param loginType login type
* @return permission list
*/
@Override
public List<String> getPermissionList(Object userId, String loginType) {
Preconditions.checkArgument(userId != null);
int userIdNum = Integer.parseInt(userId.toString());
Set<String> perms = new HashSet<String>();
if (userIdNum == BaseConstant.ADMIN_ID) {
perms.add(BaseConstant.ALL_PERMISSION);
} else {
List<Integer> roles = roleService.selectRoleListByUserId(userIdNum);
if (CollectionUtil.isNotEmpty(roles)) {
for (int roleId : roles) {
Set<String> rolePerms = menuService.selectMenuPermsByRoleId(roleId);
perms.addAll(rolePerms);
}
} else {
perms.addAll(menuService.selectMenuPermsByUserId(userIdNum));
}
}
return new ArrayList<>(perms);
}
/**
* Get role list by user ID.
*
* @param userId user ID
* @param loginType login type
* @return role list
*/
@Override
public List<String> getRoleList(Object userId, String loginType) {
Preconditions.checkArgument(userId != null);
Set<String> roles =
new HashSet<String>(
roleService.selectRolePermissionByUserId(
Integer.valueOf(userId.toString())));
return new ArrayList<>(roles);
}
}
......@@ -19,10 +19,10 @@
package org.dinky.service;
import org.dinky.data.dto.TreeNodeDTO;
import org.dinky.data.model.Menu;
import org.dinky.data.model.User;
import org.dinky.data.vo.RouterVo;
import org.dinky.data.vo.TreeSelect;
import org.dinky.mybatis.service.ISuperService;
import java.util.List;
......@@ -69,7 +69,7 @@ public interface MenuService extends ISuperService<Menu> {
* @param userId 用户ID
* @return 权限列表
*/
Set<String> selectMenuPermsByUserId(Long userId);
Set<String> selectMenuPermsByUserId(Integer userId);
/**
* 根据用户ID查询菜单树信息
......@@ -109,7 +109,7 @@ public interface MenuService extends ISuperService<Menu> {
* @param menus 菜单列表
* @return 下拉树结构列表
*/
List<TreeSelect> buildMenuTreeSelect(List<Menu> menus);
List<TreeNodeDTO> buildMenuTreeSelect(List<Menu> menus);
/**
* 根据菜单ID查询信息
......@@ -166,4 +166,12 @@ public interface MenuService extends ISuperService<Menu> {
* @return 结果
*/
String checkMenuNameUnique(Menu menu);
/**
* Query permissions by role ID.
*
* @param roleId role ID
* @return permission List
*/
Set<String> selectMenuPermsByRoleId(Integer roleId);
}
......@@ -25,6 +25,7 @@ import org.dinky.data.result.Result;
import org.dinky.mybatis.service.ISuperService;
import java.util.List;
import java.util.Set;
import com.fasterxml.jackson.databind.JsonNode;
......@@ -56,4 +57,20 @@ public interface RoleService extends ISuperService<Role> {
* @return role list
*/
List<Role> getRoleByUserId(Integer userId);
/**
* Query role permissions based on user ID.
*
* @param userId user ID
* @return permissions
*/
Set<String> selectRolePermissionByUserId(Integer userId);
/**
* Query user role list by user ID.
*
* @param userId user ID
* @return role list
*/
List<Integer> selectRoleListByUserId(Integer userId);
}
......@@ -21,12 +21,12 @@ package org.dinky.service.impl;
import org.dinky.assertion.Asserts;
import org.dinky.data.constant.BaseConstant;
import org.dinky.data.dto.TreeNodeDTO;
import org.dinky.data.model.Menu;
import org.dinky.data.model.RoleMenu;
import org.dinky.data.model.User;
import org.dinky.data.vo.MetaVo;
import org.dinky.data.vo.RouterVo;
import org.dinky.data.vo.TreeSelect;
import org.dinky.mapper.MenuMapper;
import org.dinky.mapper.RoleMenuMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
......@@ -49,6 +49,7 @@ import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
@Service
......@@ -117,7 +118,7 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
* @return 权限列表
*/
@Override
public Set<String> selectMenuPermsByUserId(Long userId) {
public Set<String> selectMenuPermsByUserId(Integer userId) {
List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (String perm : perms) {
......@@ -175,9 +176,7 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
router.setComponent(getComponent(menu));
router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
List<Menu> cMenus = menu.getChildren();
if (!cMenus.isEmpty()
&& cMenus.size() > 0
&& BaseConstant.TYPE_DIR.equals(menu.getType())) {
if (CollectionUtil.isNotEmpty(cMenus) && BaseConstant.TYPE_DIR.equals(menu.getType())) {
router.setAlwaysShow(true);
router.setRedirect("noRedirect");
router.setChildren(buildMenus(cMenus));
......@@ -226,9 +225,9 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
* @return 下拉树结构列表
*/
@Override
public List<TreeSelect> buildMenuTreeSelect(List<Menu> menus) {
public List<TreeNodeDTO> buildMenuTreeSelect(List<Menu> menus) {
List<Menu> menuTrees = buildMenuTree(menus);
return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
return menuTrees.stream().map(this::convertToTreeDTO).collect(Collectors.toList());
}
/**
......@@ -316,6 +315,24 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
return BaseConstant.UNIQUE;
}
/**
* Query permissions by role ID.
*
* @param roleId role ID
* @return permission List
*/
@Override
public Set<String> selectMenuPermsByRoleId(Integer roleId) {
List<String> perms = menuMapper.selectMenuPermsByRoleId(roleId);
Set<String> permsSet = new HashSet<>();
for (String perm : perms) {
if (StringUtils.isNotEmpty(perm)) {
permsSet.addAll(Arrays.asList(perm.trim().split(",")));
}
}
return permsSet;
}
/**
* 获取路由名称
*
......@@ -340,7 +357,7 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
public String getRouterPath(Menu menu) {
String routerPath = menu.getPath();
// 非外链并且是一级目录(类型为目录)
if (0 == menu.getParentId().intValue() && BaseConstant.TYPE_DIR.equals(menu.getType())) {
if (menu.isRootMenu() && BaseConstant.TYPE_DIR.equals(menu.getType())) {
routerPath = "/" + menu.getPath();
}
// 非外链并且是一级目录(类型为菜单)
......@@ -371,7 +388,7 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
* @return 结果
*/
public boolean isMeunFrame(Menu menu) {
return menu.getParentId().intValue() == 0 && BaseConstant.TYPE_MENU.equals(menu.getType());
return menu.isRootMenu() && BaseConstant.TYPE_MENU.equals(menu.getType());
}
/**
......@@ -383,8 +400,7 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
*/
public List<Menu> getChildPerms(List<Menu> list, int parentId) {
List<Menu> returnList = new ArrayList<Menu>();
for (Iterator<Menu> iterator = list.iterator(); iterator.hasNext(); ) {
Menu t = (Menu) iterator.next();
for (Menu t : list) {
// 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
if (t.getParentId() == parentId) {
recursionFn(list, t);
......@@ -407,9 +423,7 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
for (Menu tChild : childList) {
if (hasChild(list, tChild)) {
// 判断是否有子节点
Iterator<Menu> it = childList.iterator();
while (it.hasNext()) {
Menu n = (Menu) it.next();
for (Menu n : childList) {
recursionFn(list, n);
}
}
......@@ -419,9 +433,7 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
/** 得到子节点列表 */
private List<Menu> getChildList(List<Menu> list, Menu t) {
List<Menu> tlist = new ArrayList<Menu>();
Iterator<Menu> it = list.iterator();
while (it.hasNext()) {
Menu n = (Menu) it.next();
for (Menu n : list) {
if (n.getParentId().longValue() == t.getId().longValue()) {
tlist.add(n);
}
......@@ -431,6 +443,18 @@ public class MenuServiceImpl extends SuperServiceImpl<MenuMapper, Menu> implemen
/** 判断是否有子节点 */
private boolean hasChild(List<Menu> list, Menu t) {
return getChildList(list, t).size() > 0 ? true : false;
return getChildList(list, t).size() > 0;
}
public TreeNodeDTO convertToTreeDTO(Menu menu) {
return new TreeNodeDTO(
menu.getId(),
menu.getName(),
menu.getPath(),
menu.getParentId(),
menu.getNote(),
menu.getChildren().stream()
.map(this::convertToTreeDTO)
.collect(Collectors.toList()));
}
}
......@@ -35,7 +35,10 @@ import org.dinky.service.TenantService;
import org.dinky.service.UserRoleService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
......@@ -58,6 +61,7 @@ public class RoleServiceImpl extends SuperServiceImpl<RoleMapper, Role> implemen
private final TenantService tenantService;
private final RowPermissionsService roleSelectPermissionsService;
@Lazy @Resource private RoleService roleService;
@Lazy @Resource private RoleMapper roleMapper;
@Override
@Transactional(rollbackFor = Exception.class)
......@@ -133,4 +137,33 @@ public class RoleServiceImpl extends SuperServiceImpl<RoleMapper, Role> implemen
public List<Role> getRoleByUserId(Integer userId) {
return userRoleService.getRoleByUserId(userId);
}
/**
* Query role permission by user ID.
*
* @param userId user ID
* @return permission list
*/
@Override
public Set<String> selectRolePermissionByUserId(Integer userId) {
List<Role> perms = roleMapper.selectRolePermissionByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (Role perm : perms) {
if (perm != null) {
permsSet.addAll(Arrays.asList(perm.getRoleCode().trim().split(",")));
}
}
return permsSet;
}
/**
* Query role list by user ID.
*
* @param userId user ID
* @return role IDs
*/
@Override
public List<Integer> selectRoleListByUserId(Integer userId) {
return roleMapper.selectRoleListByUserId(userId);
}
}
......@@ -1726,7 +1726,7 @@ create table `dinky_sys_menu` (
`component` varchar(64) collate utf8mb4_general_ci default null comment 'routing component component',
`perms` varchar(64) collate utf8mb4_general_ci default null comment 'authority id',
`icon` varchar(64) collate utf8mb4_general_ci default null comment 'icon',
`type` char(2) collate utf8mb4_general_ci default null comment 'type 0:menu 1:button',
`type` char(1) collate utf8mb4_general_ci default null comment 'type(M:directory C:menu F:button)',
`display` tinyint collate utf8mb4_general_ci not null default 1 comment 'whether the menu is displayed',
`order_num` int default null comment 'sort',
`create_time` datetime not null default current_timestamp comment 'create time',
......
......@@ -55,7 +55,7 @@
select distinct m.id, m.parent_id, m.`name`, m.path, m.component, m.display, ifnull(m.perms,'') as perms,
m.type, m.icon, m.order_num, m.create_time
from dinky_sys_menu m
left join dinky_role_menu rm on m.id = rm.menu_id
left join dinky_sys_role_menu rm on m.id = rm.menu_id
left join dinky_user_role ur on rm.role_id = ur.role_id
left join dinky_role ro on ur.role_id = ro.role_id
where ur.user_id = #{params.userId}
......@@ -71,7 +71,7 @@
<select id="selectMenuTreeByUserId" resultMap="DinkySysMenuResult">
select distinct m.id, m.parent_id, m.`name`, m.path, m.component, m.display, ifnull(m.perms,'') as perms, m.type, m.icon, m.order_num, m.create_time
from dinky_sys_menu m
left join dinky_role_menu rm on m.id = rm.menu_id
left join dinky_sys_role_menu rm on m.id = rm.menu_id
left join dinky_user_role ur on rm.role_id = ur.role_id
left join dinky_role ro on ur.role_id = ro.role_id
left join sys_user u on ur.user_id = u.user_id
......@@ -84,26 +84,26 @@
<select id="selectMenuListByRoleId" parameterType="Long" resultType="Integer">
select m.id, m.parent_id
from dinky_sys_menu m
left join dinky_role_menu rm on m.id = rm.menu_id
left join dinky_sys_role_menu rm on m.id = rm.menu_id
where rm.role_id = #{roleId}
and m.id not in (select m.parent_id from dinky_sys_menu m inner join dinky_role_menu rm on m.id = rm.menu_id and rm.role_id = #{roleId})
and m.id not in (select m.parent_id from dinky_sys_menu m inner join dinky_sys_role_menu rm on m.id = rm.menu_id and rm.role_id = #{roleId})
order by m.parent_id, m.order_num
</select>
<select id="selectMenuPerms" resultType="String">
select distinct m.perms
from dinky_sys_menu m
left join dinky_role_menu rm on m.id = rm.menu_id
left join dinky_sys_role_menu rm on m.id = rm.menu_id
left join dinky_user_role ur on rm.role_id = ur.role_id
</select>
<select id="selectMenuPermsByUserId" parameterType="Long" resultType="String">
<select id="selectMenuPermsByUserId" parameterType="Integer" resultType="String">
select distinct m.perms
from dinky_sys_menu m
left join dinky_role_menu rm on m.id = rm.menu_id
left join dinky_sys_role_menu rm on m.id = rm.menu_id
left join dinky_user_role ur on rm.role_id = ur.role_id
left join dinky_role r on r.role_id = ur.role_id
where r.is_delete = '0' and ur.user_id = #{userId}
where r.is_delete = 0 and ur.user_id = #{userId}
</select>
<select id="selectMenuById" parameterType="Long" resultMap="DinkySysMenuResult">
......@@ -120,6 +120,13 @@
where `name`=#{name} and parent_id = #{parentId}
</select>
<select id="selectMenuPermsByRoleId" parameterType="Integer" resultType="String">
select distinct m.perms
from dinky_sys_menu m
left join dinky_sys_role_menu rm on m.id = rm.menu_id
where rm.role_id = #{roleId}
</select>
<select id="selectForProTable" resultType="org.dinky.data.model.Menu">
select
a.*
......
......@@ -91,4 +91,16 @@
</foreach>
</where>
</select>
<select id="selectRolePermissionByUserId" parameterType="Integer" resultMap="roleResultMap">
select distinct r.id, r.tenant_id, r.role_name, r.role_code, r.is_delete, r.note
from dinky_role r
left join dinky_user_role urole on urole.role_id = r.id
left join dinky_user u on u.id = urole.user_id
WHERE r.is_delete = 0 and ur.user_id = #{userId}
</select>
<select id="selectRoleListByUserId" parameterType="Integer" resultType="Integer">
select role_id from dinky_user_role where user_id = #{userId}
</select>
</mapper>
\ No newline at end of file
......@@ -19,7 +19,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</delete>
<insert id="batchRoleMenu">
insert into sys_role_menu(role_id, menu_id) values
insert into dinky_sys_role_menu(role_id, menu_id) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.roleId},#{item.menuId})
</foreach>
......
......@@ -1150,7 +1150,7 @@ create table `dinky_sys_menu` (
`component` varchar(64) collate utf8mb4_general_ci default null comment 'routing component component',
`perms` varchar(64) collate utf8mb4_general_ci default null comment 'authority id',
`icon` varchar(64) collate utf8mb4_general_ci default null comment 'icon',
`type` char(2) collate utf8mb4_general_ci default null comment 'type 0:menu 1:button',
`type` char(1) collate utf8mb4_general_ci default null comment 'type(M:directory C:menu F:button)',
`display` tinyint collate utf8mb4_general_ci not null default 1 comment 'whether the menu is displayed',
`order_num` int default null comment 'sort',
`create_time` datetime not null default current_timestamp comment 'create time',
......
......@@ -2123,7 +2123,7 @@ create table public.dinky_sys_menu (
component character varying(64),
perms character varying(64),
icon character varying(64),
type character(2),
type character(1),
display smallint,
order_num integer,
create_time timestamp without time zone,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment