refactor: 拆分多租户
This commit is contained in:
@@ -1,116 +0,0 @@
|
||||
package com.youlai.boot.system.controller;
|
||||
|
||||
import com.youlai.boot.common.tenant.TenantContextHolder;
|
||||
import com.youlai.boot.core.web.Result;
|
||||
import com.youlai.boot.security.util.SecurityUtils;
|
||||
import com.youlai.boot.system.model.vo.TenantVO;
|
||||
import com.youlai.boot.system.service.TenantService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户管理控制器
|
||||
* <p>
|
||||
* 提供租户切换、查询等功能
|
||||
* </p>
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Tag(name = "租户管理接口")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/tenants")
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||
public class TenantController {
|
||||
|
||||
private final TenantService tenantService;
|
||||
|
||||
/**
|
||||
* 获取当前用户的租户列表
|
||||
* <p>
|
||||
* 根据当前登录用户查询其所属的所有租户
|
||||
* </p>
|
||||
*
|
||||
* @return 租户列表
|
||||
*/
|
||||
@Operation(summary = "获取当前用户可访问的租户列表")
|
||||
@GetMapping
|
||||
public Result<List<TenantVO>> getAccessibleTenants() {
|
||||
Long userId = SecurityUtils.getUserId();
|
||||
List<TenantVO> tenantList = tenantService.getAccessibleTenants(userId);
|
||||
log.debug("用户 {} 可访问 {} 个租户", userId, tenantList.size());
|
||||
return Result.success(tenantList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前租户信息
|
||||
*
|
||||
* @return 当前租户信息
|
||||
*/
|
||||
@Operation(summary = "获取当前租户信息")
|
||||
@GetMapping("/current")
|
||||
public Result<TenantVO> getCurrentTenant() {
|
||||
Long tenantId = TenantContextHolder.getTenantId();
|
||||
if (tenantId == null) {
|
||||
return Result.success(null);
|
||||
}
|
||||
TenantVO tenant = tenantService.getTenantById(tenantId);
|
||||
return Result.success(tenant);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换租户
|
||||
* <p>
|
||||
* 切换当前用户的租户上下文,需要验证用户是否有权限访问该租户
|
||||
* </p>
|
||||
*
|
||||
* @param tenantId 目标租户ID
|
||||
* @return 切换结果
|
||||
*/
|
||||
@Operation(summary = "切换租户")
|
||||
@PostMapping("/{tenantId}/switch")
|
||||
public Result<TenantVO> switchTenant(
|
||||
@Parameter(description = "租户ID") @PathVariable Long tenantId,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
Long userId = SecurityUtils.getUserId();
|
||||
Long fromTenantId = TenantContextHolder.getTenantId();
|
||||
|
||||
log.info("用户 {} 请求切换租户:{} -> {}", userId, fromTenantId, tenantId);
|
||||
|
||||
// 验证用户是否可以访问该租户
|
||||
if (!tenantService.canAccessTenant(userId, tenantId)) {
|
||||
log.warn("用户 {} 无权访问租户 {}", userId, tenantId);
|
||||
return Result.failed("无权访问该租户");
|
||||
}
|
||||
|
||||
// 验证租户是否存在且正常
|
||||
TenantVO tenant = tenantService.getTenantById(tenantId);
|
||||
if (tenant == null) {
|
||||
log.warn("用户 {} 尝试切换到不存在的租户 {}", userId, tenantId);
|
||||
return Result.failed("租户不存在");
|
||||
}
|
||||
if (tenant.getStatus() == null || tenant.getStatus() != 1) {
|
||||
log.warn("用户 {} 尝试切换到已禁用的租户 {}", userId, tenantId);
|
||||
return Result.failed("租户已禁用");
|
||||
}
|
||||
|
||||
// 设置新的租户上下文
|
||||
TenantContextHolder.setTenantId(tenantId);
|
||||
|
||||
log.info("用户 {} 成功切换租户:{} -> {}", userId, fromTenantId, tenantId);
|
||||
|
||||
return Result.success(tenant);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.youlai.boot.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.youlai.boot.system.model.entity.Tenant;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 租户 Mapper
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Mapper
|
||||
public interface TenantMapper extends BaseMapper<Tenant> {
|
||||
}
|
||||
|
||||
@@ -13,11 +13,6 @@ import java.util.Set;
|
||||
@Data
|
||||
public class RolePermsBO {
|
||||
|
||||
/**
|
||||
* 租户ID
|
||||
*/
|
||||
private Long tenantId;
|
||||
|
||||
/**
|
||||
* 角色编码
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.youlai.boot.common.enums.LogModuleEnum;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -107,5 +108,4 @@ public class Log implements Serializable {
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 租户实体
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_tenant")
|
||||
public class Tenant extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 租户名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 租户编码(唯一)
|
||||
*/
|
||||
private String code;
|
||||
|
||||
/**
|
||||
* 联系人姓名
|
||||
*/
|
||||
private String contactName;
|
||||
|
||||
/**
|
||||
* 联系人电话
|
||||
*/
|
||||
private String contactPhone;
|
||||
|
||||
/**
|
||||
* 联系人邮箱
|
||||
*/
|
||||
private String contactEmail;
|
||||
|
||||
/**
|
||||
* 租户域名(用于域名识别)
|
||||
*/
|
||||
private String domain;
|
||||
|
||||
/**
|
||||
* 租户Logo
|
||||
*/
|
||||
private String logo;
|
||||
|
||||
/**
|
||||
* 状态(1-正常 0-禁用)
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 过期时间(NULL表示永不过期)
|
||||
*/
|
||||
private LocalDateTime expireTime;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@@ -18,13 +20,11 @@ public class User extends BaseEntity {
|
||||
*/
|
||||
private String username;
|
||||
|
||||
|
||||
/**
|
||||
* 昵称
|
||||
*/
|
||||
private String nickname;
|
||||
|
||||
|
||||
/**
|
||||
* 性别((1-男 2-女 0-保密)
|
||||
*/
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.youlai.boot.system.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 租户VO
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "租户信息")
|
||||
public class TenantVO implements Serializable {
|
||||
|
||||
@Schema(description = "租户ID")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "租户名称")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "租户编码")
|
||||
private String code;
|
||||
|
||||
@Schema(description = "租户状态(1-正常 0-禁用)")
|
||||
private Integer status;
|
||||
|
||||
@Schema(description = "联系人姓名")
|
||||
private String contactName;
|
||||
|
||||
@Schema(description = "联系人电话")
|
||||
private String contactPhone;
|
||||
|
||||
@Schema(description = "联系人邮箱")
|
||||
private String contactEmail;
|
||||
|
||||
@Schema(description = "租户域名")
|
||||
private String domain;
|
||||
|
||||
@Schema(description = "租户Logo")
|
||||
private String logo;
|
||||
|
||||
@Schema(description = "是否默认租户")
|
||||
private Boolean isDefault;
|
||||
}
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.youlai.boot.system.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.youlai.boot.system.model.entity.Tenant;
|
||||
import com.youlai.boot.system.model.vo.TenantVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户服务接口
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
public interface TenantService extends IService<Tenant> {
|
||||
|
||||
/**
|
||||
* 获取用户可访问的租户列表
|
||||
* <p>
|
||||
* 通过用户名查询该用户在所有租户下的账户,返回可访问的租户列表
|
||||
* </p>
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 可访问的租户列表
|
||||
*/
|
||||
List<TenantVO> getAccessibleTenants(Long userId);
|
||||
|
||||
/**
|
||||
* 根据租户ID查询租户信息
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 租户信息
|
||||
*/
|
||||
TenantVO getTenantById(Long tenantId);
|
||||
|
||||
/**
|
||||
* 根据域名查询租户ID
|
||||
*
|
||||
* @param domain 域名
|
||||
* @return 租户ID
|
||||
*/
|
||||
Long getTenantIdByDomain(String domain);
|
||||
|
||||
/**
|
||||
* 检查用户是否可以访问指定租户
|
||||
* <p>
|
||||
* 验证该用户名在目标租户下是否存在账户
|
||||
* </p>
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param tenantId 租户ID
|
||||
* @return true-可访问,false-不可访问
|
||||
*/
|
||||
boolean canAccessTenant(Long userId, Long tenantId);
|
||||
}
|
||||
@@ -73,26 +73,6 @@ public interface UserService extends IService<User> {
|
||||
*/
|
||||
UserAuthCredentials getAuthCredentialsByUsername(String username);
|
||||
|
||||
/**
|
||||
* 根据用户名和租户ID获取认证信息(用于多租户登录)
|
||||
*
|
||||
* @param username 用户名
|
||||
* @param tenantId 租户ID
|
||||
* @return {@link UserAuthCredentials}
|
||||
*/
|
||||
UserAuthCredentials getAuthCredentialsByUsernameAndTenant(String username, Long tenantId);
|
||||
|
||||
/**
|
||||
* 跨租户查询用户账户列表
|
||||
* <p>
|
||||
* 查询该用户名在所有租户下的账户记录,用于多租户登录时判断是否需要选择租户
|
||||
* </p>
|
||||
*
|
||||
* @param username 用户名
|
||||
* @return 用户账户列表(每个租户一条记录)
|
||||
*/
|
||||
List<User> findUserAcrossAllTenants(String username);
|
||||
|
||||
|
||||
/**
|
||||
* 获取导出用户列表
|
||||
|
||||
@@ -157,7 +157,31 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements Me
|
||||
.orderByAsc(Menu::getSort)
|
||||
);
|
||||
} else {
|
||||
// 普通用户:通过角色获取菜单(权限控制已过滤)
|
||||
menuList = this.baseMapper.getMenusByRoleCodes(roleCodes);
|
||||
|
||||
// 双重保障:动态查询"平台管理"目录,过滤其子菜单
|
||||
// 通过路由路径识别平台管理目录,避免硬编码
|
||||
Menu platformMenu = this.getOne(new LambdaQueryWrapper<Menu>()
|
||||
.eq(Menu::getRoutePath, "/platform")
|
||||
.eq(Menu::getParentId, SystemConstants.ROOT_NODE_ID)
|
||||
.eq(Menu::getType, MenuTypeEnum.CATALOG.getValue())
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
|
||||
if (platformMenu != null) {
|
||||
final Long platformMenuId = platformMenu.getId();
|
||||
menuList = menuList.stream()
|
||||
.filter(menu -> {
|
||||
String treePath = menu.getTreePath();
|
||||
// 排除平台管理目录及其子菜单
|
||||
// treePath 格式:0,1 或 0,1,110 等
|
||||
return treePath == null ||
|
||||
(!treePath.startsWith("0," + platformMenuId + ",") &&
|
||||
!treePath.equals("0," + platformMenuId));
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
return buildRoutes(SystemConstants.ROOT_NODE_ID, menuList);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@ package com.youlai.boot.system.service.impl;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.youlai.boot.common.constant.RedisConstants;
|
||||
import com.youlai.boot.common.tenant.TenantContextHolder;
|
||||
import com.youlai.boot.config.property.TenantProperties;
|
||||
import com.youlai.boot.system.mapper.RoleMenuMapper;
|
||||
import com.youlai.boot.system.model.bo.RolePermsBO;
|
||||
import com.youlai.boot.system.model.entity.RoleMenu;
|
||||
@@ -19,7 +17,7 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 角色菜单服务实现类(多租户优化版)
|
||||
* 角色菜单服务实现类
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 2.5.0
|
||||
@@ -30,25 +28,6 @@ import java.util.Set;
|
||||
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {
|
||||
|
||||
private final RedisTemplate<String, Object> redisTemplate;
|
||||
private final TenantProperties tenantProperties;
|
||||
|
||||
/**
|
||||
* 构建租户权限缓存key
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 缓存key
|
||||
* - 多租户开启: system:role:perms:{tenantId}
|
||||
* - 多租户关闭: system:role:perms
|
||||
*/
|
||||
private String buildRolePermsCacheKey(Long tenantId) {
|
||||
// 判断是否启用多租户
|
||||
if (!tenantProperties.getEnabled() || tenantId == null) {
|
||||
// 单租户模式或多租户未开启:使用原有Key
|
||||
return RedisConstants.System.ROLE_PERMS;
|
||||
}
|
||||
// 多租户模式开启:Key按租户隔离
|
||||
return RedisConstants.System.ROLE_PERMS + ":" + tenantId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动时初始化权限缓存
|
||||
@@ -64,50 +43,30 @@ public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> i
|
||||
return;
|
||||
}
|
||||
|
||||
if (tenantProperties.getEnabled()) {
|
||||
// 多租户模式:按租户分组缓存
|
||||
allRolePermsList.forEach(rolePerms -> {
|
||||
Long tenantId = rolePerms.getTenantId();
|
||||
if (tenantId == null) {
|
||||
log.warn("多租户模式下,角色[{}]缺少tenantId,跳过", rolePerms.getRoleCode());
|
||||
return;
|
||||
}
|
||||
String cacheKey = RedisConstants.System.ROLE_PERMS + ":" + tenantId;
|
||||
String roleCode = rolePerms.getRoleCode();
|
||||
Set<String> perms = rolePerms.getPerms();
|
||||
|
||||
if (CollectionUtil.isNotEmpty(perms)) {
|
||||
redisTemplate.opsForHash().put(cacheKey, roleCode, perms);
|
||||
}
|
||||
});
|
||||
log.info("权限缓存初始化完成(多租户模式),共{}条数据", allRolePermsList.size());
|
||||
} else {
|
||||
// 单租户模式:所有数据统一缓存
|
||||
String cacheKey = RedisConstants.System.ROLE_PERMS;
|
||||
allRolePermsList.forEach(rolePerms -> {
|
||||
String roleCode = rolePerms.getRoleCode();
|
||||
Set<String> perms = rolePerms.getPerms();
|
||||
|
||||
if (CollectionUtil.isNotEmpty(perms)) {
|
||||
redisTemplate.opsForHash().put(cacheKey, roleCode, perms);
|
||||
}
|
||||
});
|
||||
log.info("权限缓存初始化完成(单租户模式),共{}条数据", allRolePermsList.size());
|
||||
}
|
||||
// 所有数据统一缓存
|
||||
String cacheKey = RedisConstants.System.ROLE_PERMS;
|
||||
allRolePermsList.forEach(rolePerms -> {
|
||||
String roleCode = rolePerms.getRoleCode();
|
||||
Set<String> perms = rolePerms.getPerms();
|
||||
|
||||
if (CollectionUtil.isNotEmpty(perms)) {
|
||||
redisTemplate.opsForHash().put(cacheKey, roleCode, perms);
|
||||
}
|
||||
});
|
||||
log.info("权限缓存初始化完成,共{}条数据", allRolePermsList.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新当前租户权限缓存
|
||||
* 刷新权限缓存
|
||||
*/
|
||||
@Override
|
||||
public void refreshRolePermsCache() {
|
||||
Long tenantId = TenantContextHolder.getTenantId();
|
||||
String cacheKey = buildRolePermsCacheKey(tenantId);
|
||||
String cacheKey = RedisConstants.System.ROLE_PERMS;
|
||||
|
||||
// 清理当前租户权限缓存
|
||||
// 清理权限缓存
|
||||
redisTemplate.delete(cacheKey);
|
||||
|
||||
// 重新加载当前租户权限
|
||||
// 重新加载权限
|
||||
List<RolePermsBO> list = this.baseMapper.getRolePermsList(null);
|
||||
if (CollectionUtil.isNotEmpty(list)) {
|
||||
list.forEach(item -> {
|
||||
@@ -119,11 +78,7 @@ public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> i
|
||||
});
|
||||
}
|
||||
|
||||
if (tenantId == null) {
|
||||
log.info("权限缓存刷新完成(单租户模式)");
|
||||
} else {
|
||||
log.info("租户[{}]权限缓存刷新完成", tenantId);
|
||||
}
|
||||
log.info("权限缓存刷新完成");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,8 +86,7 @@ public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> i
|
||||
*/
|
||||
@Override
|
||||
public void refreshRolePermsCache(String roleCode) {
|
||||
Long tenantId = TenantContextHolder.getTenantId();
|
||||
String cacheKey = buildRolePermsCacheKey(tenantId);
|
||||
String cacheKey = RedisConstants.System.ROLE_PERMS;
|
||||
|
||||
// 清理指定角色缓存
|
||||
redisTemplate.opsForHash().delete(cacheKey, roleCode);
|
||||
@@ -149,11 +103,7 @@ public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> i
|
||||
}
|
||||
}
|
||||
|
||||
if (tenantId == null) {
|
||||
log.info("角色[{}]权限缓存刷新完成(单租户模式)", roleCode);
|
||||
} else {
|
||||
log.info("租户[{}]角色[{}]权限缓存刷新完成", tenantId, roleCode);
|
||||
}
|
||||
log.info("角色[{}]权限缓存刷新完成", roleCode);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,8 +111,7 @@ public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> i
|
||||
*/
|
||||
@Override
|
||||
public void refreshRolePermsCache(String oldRoleCode, String newRoleCode) {
|
||||
Long tenantId = TenantContextHolder.getTenantId();
|
||||
String cacheKey = buildRolePermsCacheKey(tenantId);
|
||||
String cacheKey = RedisConstants.System.ROLE_PERMS;
|
||||
|
||||
// 清理旧角色权限缓存
|
||||
redisTemplate.opsForHash().delete(cacheKey, oldRoleCode);
|
||||
@@ -179,11 +128,7 @@ public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> i
|
||||
}
|
||||
}
|
||||
|
||||
if (tenantId == null) {
|
||||
log.info("角色编码变更: {} -> {},权限缓存已更新(单租户模式)", oldRoleCode, newRoleCode);
|
||||
} else {
|
||||
log.info("租户[{}]角色编码变更: {} -> {},权限缓存已更新", tenantId, oldRoleCode, newRoleCode);
|
||||
}
|
||||
log.info("角色编码变更: {} -> {},权限缓存已更新", oldRoleCode, newRoleCode);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
package com.youlai.boot.system.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.youlai.boot.common.tenant.TenantContextHolder;
|
||||
import com.youlai.boot.system.mapper.TenantMapper;
|
||||
import com.youlai.boot.system.mapper.UserMapper;
|
||||
import com.youlai.boot.system.model.entity.Tenant;
|
||||
import com.youlai.boot.system.model.entity.User;
|
||||
import com.youlai.boot.system.model.vo.TenantVO;
|
||||
import com.youlai.boot.system.service.TenantService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* 租户服务实现类
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
|
||||
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@Override
|
||||
public List<TenantVO> getAccessibleTenants(Long userId) {
|
||||
// 临时忽略租户过滤,查询所有租户
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
// 先根据用户ID查询用户信息(获取 username)
|
||||
User user = userMapper.selectById(userId);
|
||||
if (user == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 通过 username 查询该用户在所有租户下的记录,获取租户ID列表
|
||||
List<User> users = userMapper.selectList(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, user.getUsername())
|
||||
.eq(User::getIsDeleted, 0)
|
||||
);
|
||||
|
||||
if (users.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 提取租户ID列表(去重)
|
||||
List<Long> tenantIds = users.stream()
|
||||
.map(User::getTenantId)
|
||||
.filter(tenantId -> tenantId != null)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (tenantIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 查询租户信息
|
||||
List<Tenant> tenants = this.list(
|
||||
new LambdaQueryWrapper<Tenant>()
|
||||
.in(Tenant::getId, tenantIds)
|
||||
.eq(Tenant::getStatus, 1) // 只查询正常状态的租户
|
||||
.orderByDesc(Tenant::getId)
|
||||
);
|
||||
|
||||
// 转换为VO,第一个租户作为默认租户
|
||||
return IntStream.range(0, tenants.size())
|
||||
.mapToObj(index -> {
|
||||
Tenant tenant = tenants.get(index);
|
||||
TenantVO vo = new TenantVO();
|
||||
BeanUtils.copyProperties(tenant, vo);
|
||||
// 第一个租户作为默认租户
|
||||
if (index == 0) {
|
||||
vo.setIsDefault(true);
|
||||
}
|
||||
return vo;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TenantVO getTenantById(Long tenantId) {
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
Tenant tenant = this.getById(tenantId);
|
||||
if (tenant == null) {
|
||||
return null;
|
||||
}
|
||||
TenantVO vo = new TenantVO();
|
||||
BeanUtils.copyProperties(tenant, vo);
|
||||
return vo;
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getTenantIdByDomain(String domain) {
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
Tenant tenant = this.getOne(
|
||||
new LambdaQueryWrapper<Tenant>()
|
||||
.eq(Tenant::getDomain, domain)
|
||||
.eq(Tenant::getStatus, 1)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
return tenant != null ? tenant.getId() : null;
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canAccessTenant(Long userId, Long tenantId) {
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
// 先根据用户ID查询用户信息(获取 username)
|
||||
User user = userMapper.selectById(userId);
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查该 username 在指定租户下是否存在用户记录
|
||||
User tenantUser = userMapper.selectOne(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, user.getUsername())
|
||||
.eq(User::getTenantId, tenantId)
|
||||
.eq(User::getIsDeleted, 0)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
return tenantUser != null;
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import com.youlai.boot.security.model.UserAuthCredentials;
|
||||
import com.youlai.boot.security.service.PermissionService;
|
||||
import com.youlai.boot.security.token.TokenManager;
|
||||
import com.youlai.boot.security.util.SecurityUtils;
|
||||
import com.youlai.boot.common.tenant.TenantContextHolder;
|
||||
import com.youlai.boot.platform.mail.service.MailService;
|
||||
import com.youlai.boot.system.converter.UserConverter;
|
||||
import com.youlai.boot.system.enums.DictCodeEnum;
|
||||
@@ -77,8 +76,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
|
||||
private final UserConverter userConverter;
|
||||
|
||||
private final com.youlai.boot.config.property.TenantProperties tenantProperties;
|
||||
|
||||
|
||||
/**
|
||||
* 获取用户分页列表
|
||||
@@ -130,22 +127,15 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
// 实体转换 form->entity
|
||||
User entity = userConverter.toEntity(userForm);
|
||||
|
||||
// 获取当前操作员的租户ID(新增用户时,租户ID由 MyMetaObjectHandler 自动填充)
|
||||
Long tenantId = TenantContextHolder.getTenantId();
|
||||
Assert.notNull(tenantId, "租户ID不能为空");
|
||||
|
||||
// 检查同一租户下用户名是否已存在(新设计:用户名在租户内唯一)
|
||||
// 检查用户名是否已存在
|
||||
long count = this.count(new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getTenantId, tenantId));
|
||||
Assert.isTrue(count == 0, "该租户下用户名已存在");
|
||||
.eq(User::getUsername, username));
|
||||
Assert.isTrue(count == 0, "用户名已存在");
|
||||
|
||||
// 设置默认加密密码
|
||||
String defaultEncryptPwd = passwordEncoder.encode(SystemConstants.DEFAULT_PASSWORD);
|
||||
entity.setPassword(defaultEncryptPwd);
|
||||
entity.setCreateBy(SecurityUtils.getUserId());
|
||||
|
||||
// 注意:租户ID由 MyMetaObjectHandler.insertFill() 自动填充,无需手动设置
|
||||
|
||||
// 新增用户
|
||||
boolean result = this.save(entity);
|
||||
@@ -173,28 +163,17 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
// 获取原用户信息
|
||||
User oldUser = this.getById(userId);
|
||||
Assert.notNull(oldUser, "用户不存在");
|
||||
|
||||
Long oldTenantId = oldUser.getTenantId();
|
||||
Long currentTenantId = TenantContextHolder.getTenantId();
|
||||
|
||||
// 验证:只能修改当前租户下的用户(防止跨租户修改)
|
||||
Assert.isTrue(oldTenantId != null && oldTenantId.equals(currentTenantId),
|
||||
"只能修改当前租户下的用户");
|
||||
|
||||
// 检查同一租户下用户名是否已存在(排除当前用户)
|
||||
// 检查用户名是否已存在(排除当前用户)
|
||||
long count = this.count(new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getTenantId, currentTenantId)
|
||||
.ne(User::getId, userId)
|
||||
);
|
||||
Assert.isTrue(count == 0, "该租户下用户名已存在");
|
||||
Assert.isTrue(count == 0, "用户名已存在");
|
||||
|
||||
// form -> entity
|
||||
User entity = userConverter.toEntity(userForm);
|
||||
entity.setUpdateBy(SecurityUtils.getUserId());
|
||||
|
||||
// 保持租户ID不变(不允许跨租户修改用户)
|
||||
entity.setTenantId(oldTenantId);
|
||||
|
||||
// 修改用户
|
||||
boolean result = this.updateById(entity);
|
||||
@@ -222,9 +201,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
.collect(Collectors.toList());
|
||||
|
||||
boolean result = this.removeByIds(ids);
|
||||
|
||||
// 新设计:用户删除时,tenant_id 字段会随用户记录一起逻辑删除,无需额外处理
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -246,45 +222,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
return userAuthCredentials;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserAuthCredentials getAuthCredentialsByUsernameAndTenant(String username, Long tenantId) {
|
||||
// 临时忽略租户过滤,查询指定租户下的用户
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
// 先查询用户
|
||||
User user = this.getOne(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getTenantId, tenantId)
|
||||
.eq(User::getIsDeleted, 0)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
// 设置租户上下文,然后查询认证信息(这样会包含该租户下的角色)
|
||||
TenantContextHolder.setTenantId(tenantId);
|
||||
return getAuthCredentialsByUsername(username);
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findUserAcrossAllTenants(String username) {
|
||||
// 临时忽略租户过滤,查询该用户名在所有租户下的账户记录
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
return this.list(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getIsDeleted, 0)
|
||||
.orderByAsc(User::getTenantId)
|
||||
);
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据OpenID获取用户认证信息
|
||||
|
||||
Reference in New Issue
Block a user