新增:新增功能权限适配及校验

1.后端 API 注解鉴权使用方式:@SaCheckPermission("system:user:add")
2.前端全局指令函数使用方式:v-permission="['system:user:add']"
3.前端权限判断函数使用方式:checkPermission(['system:user:add'])
This commit is contained in:
2023-03-02 23:39:22 +08:00
parent 843cac4e54
commit 94be1f9553
51 changed files with 548 additions and 149 deletions

View File

@@ -24,8 +24,10 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
@@ -53,7 +55,23 @@ public class SaTokenConfiguration implements WebMvcConfigurer {
* Sa-Token 整合 JWT简单模式
*/
@Bean
public StpLogic getStpLogicJwt() {
public StpLogic stpLogic() {
return new StpLogicJwtForSimple();
}
/**
* Sa-Token 持久层本地 Redis 适配
*/
@Bean
public SaTokenDao saTokenDao() {
return new SaTokenRedisDaoImpl();
}
/**
* Sa-Token 权限认证适配
*/
@Bean
public StpInterface stpInterface() {
return new SaTokenPermissionImpl();
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed 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 top.charles7c.cnadmin.auth.config.satoken;
import java.util.ArrayList;
import java.util.List;
import cn.dev33.satoken.stp.StpInterface;
import top.charles7c.cnadmin.common.model.dto.LoginUser;
import top.charles7c.cnadmin.common.util.helper.LoginHelper;
/**
* Sa-Token 权限认证适配
*
* @author Charles7c
* @since 2023/3/1 22:28
*/
public class SaTokenPermissionImpl implements StpInterface {
@Override
public List<String> getPermissionList(Object loginId, String loginType) {
LoginUser loginUser = LoginHelper.getLoginUser();
return new ArrayList<>(loginUser.getPermissions());
}
@Override
public List<String> getRoleList(Object loginId, String loginType) {
LoginUser loginUser = LoginHelper.getLoginUser();
return new ArrayList<>(loginUser.getRoles());
}
}

View File

@@ -21,20 +21,17 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.util.SaFoxUtil;
import top.charles7c.cnadmin.common.util.RedisUtils;
/**
* SaTokenDao 的本地 Redis 适配参考Sa-Token/sa-token-plugin/sa-token-dao-redisx/SaTokenDaoOfRedis.java
* Sa-Token 持久层本地 Redis 适配参考Sa-Token/sa-token-plugin/sa-token-dao-redisx/SaTokenDaoOfRedis.java
*
* @author Charles7c
* @since 2022/12/28 22:55
*/
@Component
public class SaTokenRedisDaoImpl implements SaTokenDao {
@Override

View File

@@ -19,6 +19,7 @@ package top.charles7c.cnadmin.auth.model.vo;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Set;
import lombok.Data;
import lombok.experimental.Accessors;
@@ -123,9 +124,16 @@ public class UserInfoVO implements Serializable {
private String deptName;
/**
* 用户角色(临时 mock 用,写完角色体系后移除)
* 权限码集合
*/
private String role = "admin";
@Schema(description = "权限码集合")
private Set<String> permissions;
/**
* 角色编码集合
*/
@Schema(description = "角色编码集合")
private Set<String> roles;
public String getPhone() {
return DesensitizedUtil.mobilePhone(phone);

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed 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 top.charles7c.cnadmin.auth.service;
import java.util.Set;
/**
* 权限业务接口
*
* @author Charles7c
* @since 2023/3/2 20:40
*/
public interface PermissionService {
/**
* 根据用户 ID 查询权限码
*
* @param userId
* 用户 ID
* @return 权限码集合
*/
Set<String> listPermissionsByUserId(Long userId);
/**
* 根据用户 ID 查询角色编码
*
* @param userId
* 用户 ID
* @return 角色编码集合
*/
Set<String> listRoleCodesByUserId(Long userId);
}

View File

@@ -24,6 +24,7 @@ import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import top.charles7c.cnadmin.auth.service.LoginService;
import top.charles7c.cnadmin.auth.service.PermissionService;
import top.charles7c.cnadmin.common.enums.DisEnableStatusEnum;
import top.charles7c.cnadmin.common.model.dto.LoginUser;
import top.charles7c.cnadmin.common.util.ExceptionUtils;
@@ -46,6 +47,7 @@ public class LoginServiceImpl implements LoginService {
private final UserService userService;
private final DeptService deptService;
private final PermissionService permissionService;
@Override
public String login(String username, String password) {
@@ -58,6 +60,8 @@ public class LoginServiceImpl implements LoginService {
// 登录
LoginUser loginUser = BeanUtil.copyProperties(userDO, LoginUser.class);
loginUser.setDeptName(ExceptionUtils.exToNull(() -> deptService.get(loginUser.getDeptId()).getDeptName()));
loginUser.setPermissions(permissionService.listPermissionsByUserId(userId));
loginUser.setRoles(permissionService.listRoleCodesByUserId(userId));
LoginHelper.login(loginUser);
// 返回令牌

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed 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 top.charles7c.cnadmin.auth.service.impl;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import cn.hutool.core.collection.CollUtil;
import top.charles7c.cnadmin.auth.service.PermissionService;
import top.charles7c.cnadmin.common.consts.Constants;
import top.charles7c.cnadmin.system.service.MenuService;
import top.charles7c.cnadmin.system.service.RoleService;
/**
* 权限业务实现类
*
* @author Charles7c
* @since 2023/3/2 20:40
*/
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {
private final MenuService menuService;
private final RoleService roleService;
@Override
public Set<String> listPermissionsByUserId(Long userId) {
Set<String> roleCodeSet = this.listRoleCodesByUserId(userId);
// 超级管理员赋予全部权限
if (roleCodeSet.contains(Constants.SUPER_ADMIN)) {
return CollUtil.newHashSet(Constants.ALL_PERMISSION);
}
return menuService.listPermissionsByUserId(userId);
}
@Override
public Set<String> listRoleCodesByUserId(Long userId) {
return roleService.listRoleCodesByUserId(userId);
}
}

View File

@@ -16,6 +16,10 @@
package top.charles7c.cnadmin.system.mapper;
import java.util.Set;
import org.apache.ibatis.annotations.Param;
import top.charles7c.cnadmin.common.base.BaseMapper;
import top.charles7c.cnadmin.system.model.entity.MenuDO;
@@ -25,4 +29,14 @@ import top.charles7c.cnadmin.system.model.entity.MenuDO;
* @author Charles7c
* @since 2023/2/15 20:30
*/
public interface MenuMapper extends BaseMapper<MenuDO> {}
public interface MenuMapper extends BaseMapper<MenuDO> {
/**
* 根据 ID 查询权限码
*
* @param userId
* 用户 ID
* @return 权限码集合
*/
Set<String> selectPermissionsByUserId(@Param("userId") Long userId);
}

View File

@@ -18,9 +18,6 @@ package top.charles7c.cnadmin.system.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import top.charles7c.cnadmin.common.base.BaseMapper;
import top.charles7c.cnadmin.system.model.entity.RoleMenuDO;
@@ -33,12 +30,11 @@ import top.charles7c.cnadmin.system.model.entity.RoleMenuDO;
public interface RoleMenuMapper extends BaseMapper<RoleMenuDO> {
/**
* 根据角色 ID 查询
* 根据角色 ID 列表查询
*
* @param roleId
* 角色 ID
* @param roleIds
* 角色 ID 列表
* @return 菜单 ID 列表
*/
@Select("SELECT `menu_id` FROM `sys_role_menu` WHERE `role_id` = #{roleId}")
List<Long> selectMenuIdsByRoleId(@Param("roleId") Long roleId);
List<Long> selectMenuIdsByRoleIds(List<Long> roleIds);
}

View File

@@ -16,6 +16,11 @@
package top.charles7c.cnadmin.system.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import top.charles7c.cnadmin.common.base.BaseMapper;
import top.charles7c.cnadmin.system.model.entity.UserRoleDO;
@@ -25,4 +30,15 @@ import top.charles7c.cnadmin.system.model.entity.UserRoleDO;
* @author Charles7c
* @since 2023/2/13 23:13
*/
public interface UserRoleMapper extends BaseMapper<UserRoleDO> {}
public interface UserRoleMapper extends BaseMapper<UserRoleDO> {
/**
* 根据用户 ID 查询
*
* @param userId
* 用户 ID
* @return 角色 ID 列表
*/
@Select("SELECT `role_id` FROM `sys_user_role` WHERE `user_id` = #{userId}")
List<Long> selectRoleIdsByUserId(@Param("userId") Long userId);
}

View File

@@ -104,13 +104,11 @@ public class UserRequest extends BaseRequest {
* 部门 ID
*/
@Schema(description = "所属部门")
@NotNull(message = "所属部门不能为空")
private Long deptId;
/**
* 角色 ID 列表
*/
@Schema(description = "所属角色")
@NotEmpty(message = "所属角色不能为空")
private List<Long> roleIds;
}

View File

@@ -90,7 +90,7 @@ public class RoleVO extends BaseVO {
private Boolean disabled;
public Boolean getDisabled() {
if (Constants.ADMIN_ROLE_CODE.equals(roleCode)) {
if (Constants.SUPER_ADMIN.equals(roleCode)) {
return true;
}
return disabled;

View File

@@ -16,6 +16,8 @@
package top.charles7c.cnadmin.system.service;
import java.util.Set;
import top.charles7c.cnadmin.common.base.BaseService;
import top.charles7c.cnadmin.system.model.query.MenuQuery;
import top.charles7c.cnadmin.system.model.request.MenuRequest;
@@ -27,4 +29,14 @@ import top.charles7c.cnadmin.system.model.vo.MenuVO;
* @author Charles7c
* @since 2023/2/15 20:30
*/
public interface MenuService extends BaseService<MenuVO, MenuVO, MenuQuery, MenuRequest> {}
public interface MenuService extends BaseService<MenuVO, MenuVO, MenuQuery, MenuRequest> {
/**
* 根据用户 ID 查询
*
* @param userId
* 用户 ID
* @return 权限码集合
*/
Set<String> listPermissionsByUserId(Long userId);
}

View File

@@ -39,9 +39,9 @@ public interface RoleMenuService {
/**
* 根据角色 ID 查询
*
* @param roleId
* 角色 ID
* @param roleIds
* 角色 ID 列表
* @return 菜单 ID 列表
*/
List<Long> listMenuIdByRoleId(Long roleId);
List<Long> listMenuIdByRoleIds(List<Long> roleIds);
}

View File

@@ -17,6 +17,7 @@
package top.charles7c.cnadmin.system.service;
import java.util.List;
import java.util.Set;
import top.charles7c.cnadmin.common.base.BaseService;
import top.charles7c.cnadmin.common.model.vo.LabelValueVO;
@@ -50,4 +51,13 @@ public interface RoleService extends BaseService<RoleVO, RoleDetailVO, RoleQuery
* @return 角色名称列表
*/
List<String> listRoleNamesByRoleIds(List<Long> roleIds);
/**
* 根据用户 ID 查询角色编码
*
* @param userId
* 用户 ID
* @return 角色编码集合
*/
Set<String> listRoleCodesByUserId(Long userId);
}

View File

@@ -16,7 +16,7 @@
package top.charles7c.cnadmin.system.service.impl;
import java.util.List;
import java.util.*;
import lombok.RequiredArgsConstructor;
@@ -89,4 +89,9 @@ public class MenuServiceImpl extends BaseServiceImpl<MenuMapper, MenuDO, MenuVO,
return super.lambdaQuery().eq(MenuDO::getMenuName, name).eq(MenuDO::getParentId, parentId)
.ne(id != null, MenuDO::getMenuId, id).exists();
}
@Override
public Set<String> listPermissionsByUserId(Long userId) {
return baseMapper.selectPermissionsByUserId(userId);
}
}

View File

@@ -16,6 +16,7 @@
package top.charles7c.cnadmin.system.service.impl;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@@ -57,7 +58,10 @@ public class RoleMenuServiceImpl implements RoleMenuService {
}
@Override
public List<Long> listMenuIdByRoleId(Long roleId) {
return roleMenuMapper.selectMenuIdsByRoleId(roleId);
public List<Long> listMenuIdByRoleIds(List<Long> roleIds) {
if (CollUtil.isEmpty(roleIds)) {
return Collections.emptyList();
}
return roleMenuMapper.selectMenuIdsByRoleIds(roleIds);
}
}

View File

@@ -18,6 +18,7 @@ package top.charles7c.cnadmin.system.service.impl;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
@@ -61,8 +62,11 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleVO,
@Transactional(rollbackFor = Exception.class)
public Long add(RoleRequest request) {
String roleName = request.getRoleName();
boolean isExists = this.checkNameExists(roleName, request.getRoleId());
CheckUtils.throwIf(() -> isExists, String.format("新增失败,'%s'已存在", roleName));
CheckUtils.throwIf(() -> this.checkNameExists(roleName, request.getRoleId()),
String.format("新增失败,'%s'已存在", roleName));
String roleCode = request.getRoleCode();
CheckUtils.throwIf(() -> this.checkCodeExists(roleCode, request.getRoleId()),
String.format("新增失败,'%s'已存在", roleCode));
// 新增角色
request.setStatus(DisEnableStatusEnum.ENABLE);
@@ -78,8 +82,11 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleVO,
@Transactional(rollbackFor = Exception.class)
public void update(RoleRequest request) {
String roleName = request.getRoleName();
boolean isExists = this.checkNameExists(roleName, request.getRoleId());
CheckUtils.throwIf(() -> isExists, String.format("修改失败,'%s'已存在", roleName));
CheckUtils.throwIf(() -> this.checkNameExists(roleName, request.getRoleId()),
String.format("修改失败,'%s'已存在", roleName));
String roleCode = request.getRoleCode();
CheckUtils.throwIf(() -> this.checkCodeExists(roleCode, request.getRoleId()),
String.format("修改失败,'%s'已存在", roleCode));
// 更新角色
super.update(request);
@@ -110,18 +117,31 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleVO,
return super.lambdaQuery().eq(RoleDO::getRoleName, name).ne(id != null, RoleDO::getRoleId, id).exists();
}
/**
* 检查编码是否存在
*
* @param code
* 编码
* @param id
* ID
* @return 是否存在
*/
private boolean checkCodeExists(String code, Long id) {
return super.lambdaQuery().eq(RoleDO::getRoleCode, code).ne(id != null, RoleDO::getRoleId, id).exists();
}
@Override
public void fillDetail(Object detailObj) {
super.fillDetail(detailObj);
if (detailObj instanceof RoleDetailVO) {
RoleDetailVO detailVO = (RoleDetailVO)detailObj;
Long roleId = detailVO.getRoleId();
if (Constants.ADMIN_ROLE_CODE.equals(detailVO.getRoleCode())) {
if (Constants.SUPER_ADMIN.equals(detailVO.getRoleCode())) {
List<MenuVO> list = menuService.list(null, null);
List<Long> menuIds = list.stream().map(MenuVO::getMenuId).collect(Collectors.toList());
detailVO.setMenuIds(menuIds);
} else {
detailVO.setMenuIds(roleMenuService.listMenuIdByRoleId(roleId));
detailVO.setMenuIds(roleMenuService.listMenuIdByRoleIds(Collections.singletonList(roleId)));
}
detailVO.setDeptIds(roleDeptService.listDeptIdByRoleId(roleId));
}
@@ -143,4 +163,14 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleVO,
}
return roleList.stream().map(RoleDO::getRoleName).collect(Collectors.toList());
}
@Override
public Set<String> listRoleCodesByUserId(Long userId) {
List<Long> roleIds = userRoleService.listRoleIdsByUserId(userId);
List<RoleDO> roleList = super.lambdaQuery().select(RoleDO::getRoleCode).in(RoleDO::getRoleId, roleIds).list();
if (CollUtil.isEmpty(roleList)) {
return Collections.emptySet();
}
return roleList.stream().map(RoleDO::getRoleCode).collect(Collectors.toSet());
}
}

View File

@@ -16,7 +16,6 @@
package top.charles7c.cnadmin.system.service.impl;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@@ -64,11 +63,6 @@ public class UserRoleServiceImpl implements UserRoleService {
@Override
public List<Long> listRoleIdsByUserId(Long userId) {
List<UserRoleDO> userRoleList = userRoleMapper.selectList(
Wrappers.<UserRoleDO>lambdaQuery().select(UserRoleDO::getRoleId).eq(UserRoleDO::getUserId, userId));
if (CollUtil.isEmpty(userRoleList)) {
return Collections.emptyList();
}
return userRoleList.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
return userRoleMapper.selectRoleIdsByUserId(userId);
}
}

View File

@@ -1,4 +1,16 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="top.charles7c.cnadmin.system.mapper.MenuMapper">
<select id="selectPermissionsByUserId" resultType="java.lang.String">
SELECT DISTINCT m.`permission`
FROM `sys_menu` m
LEFT JOIN `sys_role_menu` rm ON rm.`menu_id` = m.`menu_id`
LEFT JOIN `sys_role` r ON r.`role_id` = rm.`role_id`
LEFT JOIN `sys_user_role` ur ON ur.`role_id` = rm.`role_id`
LEFT JOIN `sys_user` u ON u.`user_id` = ur.`user_id`
WHERE u.`user_id` = #{userId}
AND m.`menu_type` IN (2, 3)
AND m.`status` = 1
AND r.`status` = 1
</select>
</mapper>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="top.charles7c.cnadmin.system.mapper.RoleMenuMapper">
<select id="selectMenuIdsByRoleIds" resultType="java.lang.Long">
SELECT
`menu_id`
FROM `sys_role_menu`
<where>
`role_id` IN
<foreach collection="list" item="roleId" open="(" close=")" separator=",">
#{roleId}
</foreach>
</where>
</select>
</mapper>