refactor: 登录用户权限校验逻辑调整

This commit is contained in:
haoxr 2024-01-30 13:52:04 +08:00
parent fe80aa3b76
commit 369f2e6b04
19 changed files with 344 additions and 125 deletions

View File

@ -43,7 +43,7 @@ public class SmsCodeAuthenticationProvider implements AuthenticationProvider {
private final MemberDetailsService memberDetailsService;
private final RedisTemplate redisTemplate;
private final RedisTemplate<String,Object> redisTemplate;
/**
* Constructs an {@code OAuth2ResourceOwnerPasswordAuthenticationProviderNew} using the provided parameters.

View File

@ -5,43 +5,28 @@ public interface SecurityConstants {
/**
* 黑名单TOKEN Key前缀
*/
String BLACKLIST_TOKEN_PREFIX = "AUTH:BLACKLIST_TOKEN:";
String TOKEN_BLACKLIST_PREFIX = "token:blacklist:";
/**
* 验证码key前缀
* 图形验证码key前缀
*/
String VERIFY_CODE_CACHE_KEY_PREFIX = "AUTH:VERIFY_CODE:";
String CAPTCHA_CODE_PREFIX = "captcha_code:";
/**
* 短信验证码key前缀
*/
String SMS_CODE_PREFIX = "AUTH:SMS_CODE:";
/**
* 用户权限集合缓存前缀
*/
String USER_PERMS_CACHE_KEY_PREFIX = "AUTH:USER_PERMS:";
/**
* 授权信息中的权限或角色的key
*/
String AUTHORITIES_CLAIM_NAME_KEY = "authorities";
/**
* 商城管理端客户端ID
*/
String MALL_ADMIN_CLIENT_ID = "mall-admin";
/**
* 商城移动端客户端ID
*/
String MALL_APP_CLIENT_ID = "mall-app";
String SMS_CODE_PREFIX = "sms_code:";
/**
* Knife4j测试客户端IDKnife4j自动填充的 access_token 须原生返回不能被包装成业务码数据格式
*/
String KNIFE4J_TEST_CLIENT_ID = "client";
String TEST_OAUTH2_CLIENT_ID = "client";
String JWK_SET_KEY = "jwk_set";
/**
* 角色和权限缓存前缀
*/
String ROLE_PERMS_PREFIX = "role_perms:";
}

View File

@ -70,7 +70,7 @@ public class SysMenuController {
@PostMapping
@PreAuthorize("@ss.hasPerm('sys:menu:add')")
@PreventDuplicateResubmit
@CacheEvict(cacheNames = "system", key = "'routes'")
@CacheEvict(cacheNames = "menu", key = "'routes'")
public Result addMenu(@RequestBody MenuForm menuForm) {
boolean result = menuService.saveMenu(menuForm);
return Result.judge(result);
@ -79,7 +79,7 @@ public class SysMenuController {
@Operation(summary = "修改菜单",security = {@SecurityRequirement(name = "Authorization")})
@PutMapping(value = "/{id}")
@PreAuthorize("@ss.hasPerm('sys:menu:edit')")
@CacheEvict(cacheNames = "system", key = "'routes'")
@CacheEvict(cacheNames = "menu", key = "'routes'")
public Result updateMenu(
@RequestBody MenuForm menuForm
) {
@ -90,7 +90,7 @@ public class SysMenuController {
@Operation(summary = "删除菜单",security = {@SecurityRequirement(name = "Authorization")})
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPerm('sys:menu:delete')")
@CacheEvict(cacheNames = "system", key = "'routes'")
@CacheEvict(cacheNames = "menu", key = "'routes'")
public Result deleteMenu(
@Parameter(description ="菜单ID多个以英文(,)分割") @PathVariable("id") Long id
) {

View File

@ -102,11 +102,11 @@ public class SysRoleController {
@Operation(summary = "分配菜单权限给角色",security = {@SecurityRequirement(name = "Authorization")})
@PutMapping("/{roleId}/menus")
public Result updateRoleMenus(
public Result assignMenusToRole(
@PathVariable Long roleId,
@RequestBody List<Long> menuIds
) {
boolean result = roleService.updateRoleMenus(roleId,menuIds);
boolean result = roleService.assignMenusToRole(roleId,menuIds);
return Result.judge(result);
}
}

View File

@ -135,8 +135,8 @@ public class SysUserController {
@Operation(summary = "获取登录用户信息")
@GetMapping("/me")
public Result<UserInfoVO> getUserLoginInfo() {
UserInfoVO userInfoVO = userService.getUserLoginInfo();
public Result<UserInfoVO> getCurrentUserInfo() {
UserInfoVO userInfoVO = userService.getCurrentUserInfo();
return Result.success(userInfoVO);
}

View File

@ -1,6 +1,7 @@
package com.youlai.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youlai.system.model.bo.RolePermsBO;
import com.youlai.system.model.entity.SysRoleMenu;
import org.apache.ibatis.annotations.Mapper;
@ -22,4 +23,9 @@ public interface SysRoleMenuMapper extends BaseMapper<SysRoleMenu> {
* @return
*/
List<Long> listMenuIdsByRoleId(Long roleId);
/**
* 获取权限和拥有权限的角色列表
*/
List<RolePermsBO> getRolePermsList(String roleCode);
}

View File

@ -5,7 +5,7 @@ import com.youlai.system.model.entity.SysUserRole;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户角色持久
* 用户角色访问
*
* @author haoxr
* @since 2022/1/15
@ -13,4 +13,10 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
/**
* 获取角色绑定的用户数
*
* @param roleId 角色ID
*/
int countUsersForRole(Long roleId);
}

View File

@ -6,9 +6,14 @@ import com.youlai.system.model.entity.SysRoleMenu;
import java.util.List;
/**
* 角色菜单业务接口
*
* @author haoxr
* @since 0.0.1
*/
public interface SysRoleMenuService extends IService<SysRoleMenu> {
/**
* 获取角色拥有的菜单ID集合
*
@ -16,4 +21,26 @@ public interface SysRoleMenuService extends IService<SysRoleMenu> {
* @return
*/
List<Long> listMenuIdsByRoleId(Long roleId);
/**
* 刷新权限缓存(所有角色)
*/
void refreshRolePermsCache();
/**
* 刷新权限缓存(指定角色)
*
* @param roleCode 角色编码
*/
void refreshRolePermsCache(String roleCode);
/**
* 刷新权限缓存(修改角色编码时调用)
*
* @param oldRoleCode 旧角色编码
* @param newRoleCode 新角色编码
*/
void refreshRolePermsCache(String oldRoleCode, String newRoleCode);
}

View File

@ -23,8 +23,8 @@ public interface SysRoleService extends IService<SysRole> {
/**
* 角色分页列表
*
* @param queryParams
* @return
* @param queryParams 角色查询参数
* @return {@link Page<RolePageVO>} 角色分页列表
*/
Page<RolePageVO> getRolePage(RolePageQuery queryParams);
@ -32,14 +32,15 @@ public interface SysRoleService extends IService<SysRole> {
/**
* 角色下拉列表
*
* @return
* @return {@link List<Option>} 角色下拉列表
*/
List<Option> listRoleOptions();
/**
* 保存角色
*
* @param roleForm
* @return
* @param roleForm 角色表单数据
* @return {@link Boolean}
*/
boolean saveRole(RoleForm roleForm);
@ -64,11 +65,10 @@ public interface SysRoleService extends IService<SysRole> {
* 批量删除角色
*
* @param ids 角色ID多个使用英文逗号(,)分割
* @return
* @return {@link Boolean}
*/
boolean deleteRoles(String ids);
/**
* 获取角色的菜单ID集合
*
@ -77,21 +77,20 @@ public interface SysRoleService extends IService<SysRole> {
*/
List<Long> getRoleMenuIds(Long roleId);
/**
* 修改角色的资源权限
* 分配角色资源权限
*
* @param roleId
* @param menuIds
* @return
* @param roleId 角色ID
* @param menuIds 菜单ID集合
* @return {@link Boolean}
*/
boolean updateRoleMenus(Long roleId, List<Long> menuIds);
boolean assignMenusToRole(Long roleId, List<Long> menuIds);
/**
* 获取最大范围的数据权限
*
* @param roles
* @return
* @param roles 角色编码集合
* @return {@link Integer} 最大范围的数据权限
*/
Integer getMaxDataRangeDataScope(Set<String> roles);

View File

@ -16,4 +16,13 @@ public interface SysUserRoleService extends IService<SysUserRole> {
* @return
*/
boolean saveUserRoles(Long userId, List<Long> roleIds);
/**
* 判断角色是否存在绑定的用户
*
* @param roleId 角色ID
* @return true已分配 false未分配
*/
boolean hasAssignedUsers(Long roleId);
}

View File

@ -98,7 +98,7 @@ public interface SysUserService extends IService<SysUser> {
*
* @return
*/
UserInfoVO getUserLoginInfo();
UserInfoVO getCurrentUserInfo();
/**
* 注销登出

View File

@ -1,7 +1,6 @@
package com.youlai.system.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
@ -20,6 +19,7 @@ import com.youlai.system.model.vo.MenuVO;
import com.youlai.common.web.model.Option;
import com.youlai.system.model.vo.RouteVO;
import com.youlai.system.service.SysMenuService;
import com.youlai.system.service.SysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
@ -39,7 +39,9 @@ import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
private final MenuConverter menuConverter;
private final SysRoleMenuService roleMenuService;
/**
* 菜单列表
@ -66,11 +68,10 @@ public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> impl
.toList();
// 使用递归函数来构建菜单树
List<MenuVO> menuList = rootIds.stream()
return rootIds.stream()
.flatMap(rootId -> buildMenuTree(rootId, menus).stream())
.collect(Collectors.toList());
return menuList;
}
/**
@ -129,7 +130,7 @@ public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> impl
* 路由列表
*/
@Override
@Cacheable(cacheNames = "system", key = "'routes'")
@Cacheable(cacheNames = "menu", key = "'routes'")
public List<RouteVO> listRoutes() {
List<RouteBO> menuList = this.baseMapper.listRoutes();
return buildRoutes(SystemConstants.ROOT_NODE_ID, menuList);
@ -214,7 +215,14 @@ public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> impl
String treePath = generateMenuTreePath(menuForm.getParentId());
entity.setTreePath(treePath);
return this.saveOrUpdate(entity);
boolean result = this.saveOrUpdate(entity);
if (result) {
// 编辑刷新角色权限缓存
if (menuForm.getId() != null) {
roleMenuService.refreshRolePermsCache();
}
}
return result;
}
/**
@ -238,7 +246,7 @@ public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> impl
*
* @param menuId 菜单ID
* @param visible 是否显示(1->显示2->隐藏)
* @return
* @return 是否成功
*/
@Override
public boolean updateMenuVisible(Long menuId, Integer visible) {
@ -251,43 +259,44 @@ public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> impl
/**
* 获取角色权限集合
*
* @param roles
* @return
* @param roles 角色编码集合
* @return 权限标识集合
*/
@Override
public Set<String> listRolePerms(Set<String> roles) {
Set<String> perms = this.baseMapper.listRolePerms(roles);
return perms;
return this.baseMapper.listRolePerms(roles);
}
/**
* 获取菜单表单数据
*
* @param id 菜单ID
* @return
* @return {@link MenuForm}
*/
@Override
public MenuForm getMenuForm(Long id) {
SysMenu entity = this.getById(id);
MenuForm menuForm = menuConverter.entity2Form(entity);
return menuForm;
return menuConverter.entity2Form(entity);
}
/**
* 删除菜单
*
* @param id 菜单ID
* @return
* @return 是否成功
*/
@Override
public boolean deleteMenu(Long id) {
if (id != null) {
this.remove(new LambdaQueryWrapper<SysMenu>()
boolean result = this.remove(new LambdaQueryWrapper<SysMenu>()
.eq(SysMenu::getId, id)
.or()
.apply("CONCAT (',',tree_path,',') LIKE CONCAT('%,',{0},',%')", id));
// 刷新角色权限缓存
if (result) {
roleMenuService.refreshRolePermsCache();
}
return true;
return result;
}

View File

@ -1,19 +1,100 @@
package com.youlai.system.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.common.constant.SecurityConstants;
import com.youlai.system.mapper.SysRoleMenuMapper;
import com.youlai.system.model.bo.RolePermsBO;
import com.youlai.system.model.entity.SysRoleMenu;
import com.youlai.system.service.SysRoleMenuService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
/**
* 角色菜单业务实现类
*/
@Service
@RequiredArgsConstructor
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {
private final RedisTemplate<String, Object> redisTemplate;
/**
* 初始化权限缓存
*/
@PostConstruct
public void initRolePermsCache() {
refreshRolePermsCache();
}
/**
* 刷新权限缓存
*/
@Override
public void refreshRolePermsCache() {
// 清理权限缓存
redisTemplate.opsForHash().delete(SecurityConstants.ROLE_PERMS_PREFIX, "*");
List<RolePermsBO> list = this.baseMapper.getRolePermsList(null);
if (CollectionUtil.isNotEmpty(list)) {
list.forEach(item -> {
String roleCode = item.getRoleCode();
Set<String> perms = item.getPerms();
redisTemplate.opsForHash().put(SecurityConstants.ROLE_PERMS_PREFIX, roleCode, perms);
});
}
}
/**
* 刷新权限缓存
*/
@Override
public void refreshRolePermsCache(String roleCode) {
// 清理权限缓存
redisTemplate.opsForHash().delete(SecurityConstants.ROLE_PERMS_PREFIX, roleCode);
List<RolePermsBO> list = this.baseMapper.getRolePermsList(roleCode);
if (CollectionUtil.isNotEmpty(list)) {
RolePermsBO rolePerms = list.get(0);
if (rolePerms == null) {
return;
}
Set<String> perms = rolePerms.getPerms();
redisTemplate.opsForHash().put(SecurityConstants.ROLE_PERMS_PREFIX, roleCode, perms);
}
}
/**
* 刷新权限缓存 (角色编码变更时调用)
*/
@Override
public void refreshRolePermsCache(String oldRoleCode, String newRoleCode) {
// 清理旧角色权限缓存
redisTemplate.opsForHash().delete(SecurityConstants.ROLE_PERMS_PREFIX, oldRoleCode);
// 添加新角色权限缓存
List<RolePermsBO> list =this.baseMapper.getRolePermsList(newRoleCode);
if (CollectionUtil.isNotEmpty(list)) {
RolePermsBO rolePerms = list.get(0);
if (rolePerms == null) {
return;
}
Set<String> perms = rolePerms.getPerms();
redisTemplate.opsForHash().put(SecurityConstants.ROLE_PERMS_PREFIX, newRoleCode, perms);
}
}
/**
* 获取角色拥有的菜单ID集合
*

View File

@ -2,6 +2,7 @@ package com.youlai.system.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
@ -39,15 +40,15 @@ import java.util.stream.Collectors;
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
private final SysRoleMenuService sysRoleMenuService;
private final SysUserRoleService sysUserRoleService;
private final SysRoleMenuService roleMenuService;
private final SysUserRoleService userRoleService;
private final RoleConverter roleConverter;
/**
* 角色分页列表
*
* @param queryParams
* @return
* @param queryParams 角色查询参数
* @return {@link Page<RolePageVO>} 角色分页列表
*/
@Override
public Page<RolePageVO> getRolePage(RolePageQuery queryParams) {
@ -76,7 +77,7 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
/**
* 角色下拉列表
*
* @return
* @return {@link List<Option>} 角色下拉列表
*/
@Override
public List<Option> listRoleOptions() {
@ -94,26 +95,44 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
/**
* 保存角色
*
* @param roleForm
* @return
* @param roleForm 角色表单数据
* @return {@link Boolean}
*/
@Override
public boolean saveRole(RoleForm roleForm) {
Long roleId = roleForm.getId();
String roleCode = roleForm.getCode();
// 编辑角色时判断角色是否存在
SysRole oldRole = null;
if (roleId != null) {
oldRole = this.getById(roleId);
Assert.isTrue(oldRole != null, "角色不存在");
}
String roleCode = roleForm.getCode();
long count = this.count(new LambdaQueryWrapper<SysRole>()
.ne(roleId != null, SysRole::getId, roleId)
.and(wrapper ->
wrapper.eq(SysRole::getCode, roleCode).or().eq(SysRole::getName, roleCode)
wrapper.eq(SysRole::getCode, roleCode).or().eq(SysRole::getName, roleForm.getName())
));
Assert.isTrue(count == 0, "角色名称或角色编码重复,请检查!");
Assert.isTrue(count == 0, "角色名称或角色编码已存在,请修改后重试");
// 实体转换
SysRole role = roleConverter.form2Entity(roleForm);
return this.saveOrUpdate(role);
boolean result = this.saveOrUpdate(role);
if (result) {
// 判断角色编码或状态是否修改修改了则刷新权限缓存
if (oldRole != null
&& (
!StrUtil.equals(oldRole.getCode(), roleCode) ||
!ObjectUtil.equals(oldRole.getStatus(), roleForm.getStatus())
)) {
roleMenuService.refreshRolePermsCache(oldRole.getCode(), roleCode);
}
}
return result;
}
/**
@ -125,8 +144,7 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
@Override
public RoleForm getRoleForm(Long roleId) {
SysRole entity = this.getById(roleId);
RoleForm roleForm = roleConverter.entity2Form(entity);
return roleForm;
return roleConverter.entity2Form(entity);
}
/**
@ -138,9 +156,16 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
*/
@Override
public boolean updateRoleStatus(Long roleId, Integer status) {
boolean result = this.update(new LambdaUpdateWrapper<SysRole>()
.eq(SysRole::getId, roleId)
.set(SysRole::getStatus, status));
SysRole role = this.getById(roleId);
Assert.isTrue(role != null, "角色不存在");
role.setStatus(status);
boolean result = this.updateById(role);
if (result) {
// 刷新角色的权限缓存
roleMenuService.refreshRolePermsCache(role.getCode());
}
return result;
}
@ -152,17 +177,25 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
*/
@Override
public boolean deleteRoles(String ids) {
List<Long> roleIds = Arrays.asList(ids.split(",")).stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
Optional.ofNullable(roleIds)
.orElse(new ArrayList<>())
.forEach(id -> {
long count = sysUserRoleService.count(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRoleId, id));
Assert.isTrue(count <= 0, "该角色已分配用户,无法删除");
sysRoleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
});
List<Long> roleIds = Arrays.stream(ids.split(","))
.map(Long::parseLong)
.toList();
for (Long roleId : roleIds) {
SysRole role = this.getById(roleId);
Assert.isTrue(role != null, "角色不存在");
return this.removeByIds(roleIds);
// 判断角色是否被用户关联
boolean isRoleAssigned = userRoleService.hasAssignedUsers(roleId);
Assert.isTrue(!isRoleAssigned, "角色【{}】已分配用户,请先解除关联后删除", role.getName());
boolean deleteResult = this.removeById(roleId);
if (deleteResult) {
// 删除成功刷新权限缓存
roleMenuService.refreshRolePermsCache(role.getCode());
}
}
return true;
}
/**
@ -173,29 +206,36 @@ public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> impl
*/
@Override
public List<Long> getRoleMenuIds(Long roleId) {
return sysRoleMenuService.listMenuIdsByRoleId(roleId);
return roleMenuService.listMenuIdsByRoleId(roleId);
}
/**
* 修改角色的资源权限
* 分配角色资源权限
*
* @param roleId
* @param menuIds
* @return
* @param roleId 角色ID
* @param menuIds 菜单ID集合
* @return {@link Boolean}
*/
@Override
@Transactional
@CacheEvict(cacheNames = "system", key = "'routes'")
public boolean updateRoleMenus(Long roleId, List<Long> menuIds) {
@CacheEvict(cacheNames = "menu", key = "'routes'")
public boolean assignMenusToRole(Long roleId, List<Long> menuIds) {
SysRole role = this.getById(roleId);
Assert.isTrue(role != null, "角色不存在");
// 删除角色菜单
sysRoleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
roleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
// 新增角色菜单
if (CollectionUtil.isNotEmpty(menuIds)) {
List<SysRoleMenu> roleMenus = menuIds.stream()
.map(menuId -> new SysRoleMenu(roleId, menuId))
.collect(Collectors.toList());
sysRoleMenuService.saveBatch(roleMenus);
roleMenuService.saveBatch(roleMenus);
}
// 刷新角色的权限缓存
roleMenuService.refreshRolePermsCache(role.getCode());
return true;
}

View File

@ -67,4 +67,16 @@ public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUs
return true;
}
/**
* 判断角色是否存在绑定的用户
*
* @param roleId 角色ID
* @return true已分配 false未分配
*/
@Override
public boolean hasAssignedUsers(Long roleId) {
int count = this.baseMapper.countUsersForRole(roleId);
return count > 0;
}
}

View File

@ -10,6 +10,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.common.constant.SecurityConstants;
import com.youlai.common.constant.SystemConstants;
import com.youlai.common.security.service.PermissionService;
import com.youlai.common.security.util.SecurityUtils;
import com.youlai.system.converter.UserConverter;
import com.youlai.system.dto.UserAuthInfo;
@ -56,15 +57,17 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
private final UserConverter userConverter;
private final RedisTemplate redisTemplate;
private final RedisTemplate<String,Object> redisTemplate;
private final SysMenuService menuService;
private final PermissionService permissionService;
/**
* 获取用户分页列表
*
* @param queryParams
* @return
* @param queryParams 查询参数
* @return {@link UserPageVO}
*/
@Override
public IPage<UserPageVO> getUserPage(UserPageQuery queryParams) {
@ -86,8 +89,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
/**
* 获取用户详情
*
* @param userId
* @return
* @param userId 用户ID
* @return {@link UserForm}
*/
@Override
public UserForm getUserFormData(Long userId) {
@ -101,7 +104,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
* 新增用户
*
* @param userForm 用户表单对象
* @return
* @return true|false
*/
@Override
public boolean saveUser(UserForm userForm) {
@ -220,8 +223,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
/**
* 获取导出用户列表
*
* @param queryParams
* @return
* @param queryParams 查询参数
* @return {@link UserExportVO}
*/
@Override
public List<UserExportVO> listExportUsers(UserPageQuery queryParams) {
@ -232,10 +235,10 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
/**
* 获取登录用户信息
*
* @return
* @return {@link UserInfoVO} 用户信息
*/
@Override
public UserInfoVO getUserLoginInfo() {
public UserInfoVO getCurrentUserInfo() {
// 登录用户entity
SysUser user = this.getOne(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getUsername, SecurityUtils.getUsername())
@ -253,8 +256,10 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
userInfoVO.setRoles(roles);
// 用户权限集合
Set<String> perms = (Set<String>) redisTemplate.opsForValue().get(SecurityConstants.USER_PERMS_CACHE_KEY_PREFIX + user.getId());
if (CollectionUtil.isNotEmpty(roles)) {
Set<String> perms = permissionService.getRolePermsFormCache(roles);
userInfoVO.setPerms(perms);
}
return userInfoVO;
}
@ -262,7 +267,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
/**
* 注销登出
*
* @return
* @return true|false
*/
@Override
public boolean logout() {
@ -272,11 +277,13 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
long currentTime = System.currentTimeMillis() / 1000;// 当前时间单位
if (expireTime != null) {
if (expireTime > currentTime) { // token未过期添加至缓存作为黑名单限制访问缓存时间为token过期剩余时间
redisTemplate.opsForValue().set(SecurityConstants.BLACKLIST_TOKEN_PREFIX + jti, null, (expireTime - currentTime), TimeUnit.SECONDS);
if (expireTime > currentTime) {
// token未过期添加至缓存作为黑名单限制访问缓存时间为token过期剩余时间
redisTemplate.opsForValue().set(SecurityConstants.TOKEN_BLACKLIST_PREFIX + jti, null, (expireTime - currentTime), TimeUnit.SECONDS);
}
} else { // token 永不过期则永久加入黑名单一般不会有
redisTemplate.opsForValue().set(SecurityConstants.BLACKLIST_TOKEN_PREFIX + jti, null);
} else {
// token 永不过期则永久加入黑名单
redisTemplate.opsForValue().set(SecurityConstants.TOKEN_BLACKLIST_PREFIX + jti, null);
}
return true;
}

View File

@ -14,4 +14,28 @@
WHERE
rm.role_id = #{roleId}
</select>
<!-- 权限和拥有权限的角色集合的Map -->
<resultMap id="PremRolesMap" type="com.youlai.system.model.bo.RolePermsBO">
<result property="roleCode" column="role_code"/>
<collection property="perms" ofType="string" javaType="java.util.Set">
<result column="perm"/>
</collection>
</resultMap>
<!-- 获取权限和拥有权限的角色列表 -->
<select id="getRolePermsList" resultMap="PremRolesMap">
SELECT
t2.`code` role_code,
t3.perm
FROM
`sys_role_menu` t1
INNER JOIN sys_role t2 ON t1.role_id = t2.id AND t2.deleted = 0 AND t2.`status` = 1
INNER JOIN sys_menu t3 ON t1.menu_id = t3.id
WHERE
type = '${@com.youlai.system.common.enums.MenuTypeEnum@BUTTON.getValue()}'
<if test="roleCode!=null and roleCode.trim() neq ''">
AND t2.`code` = #{roleCode}
</if>
</select>
</mapper>

View File

@ -13,4 +13,18 @@
WHERE
user_id = #{userId}
</select>
<!-- 获取角色绑定的用户数 -->
<select id="countUsersForRole" resultType="java.lang.Integer">
SELECT
COUNT(*)
FROM
sys_user_role t1
INNER JOIN sys_role t2 ON t1.role_id = t2.id AND t2.deleted = 0
INNER JOIN sys_user t3 ON t1.user_id = t3.id
AND t3.deleted = 0
WHERE
t1.role_id = #{roleId}
</select>
</mapper>