refactor: 拆分多租户

This commit is contained in:
Ray.Hao
2025-12-15 08:05:24 +08:00
parent 3f05f77351
commit 5817826bbd
57 changed files with 297 additions and 2291 deletions

View File

@@ -1,21 +1,14 @@
package com.youlai.boot.auth.controller;
import com.youlai.boot.auth.model.vo.CaptchaVO;
import com.youlai.boot.auth.model.vo.ChooseTenantVO;
import com.youlai.boot.auth.model.dto.LoginRequest;
import com.youlai.boot.auth.model.dto.WxMiniAppPhoneLoginDTO;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.config.property.TenantProperties;
import com.youlai.boot.core.web.Result;
import com.youlai.boot.auth.service.AuthService;
import com.youlai.boot.auth.model.dto.WxMiniAppCodeLoginDTO;
import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.core.web.ResultCode;
import com.youlai.boot.security.model.AuthenticationToken;
import com.youlai.boot.system.model.entity.User;
import com.youlai.boot.system.model.vo.TenantVO;
import com.youlai.boot.system.service.TenantService;
import com.youlai.boot.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -25,8 +18,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
@@ -43,9 +34,6 @@ import java.util.stream.Collectors;
public class AuthController {
private final AuthService authService;
private final UserService userService;
private final TenantService tenantService;
private final TenantProperties tenantProperties;
@Operation(summary = "获取验证码")
@GetMapping("/captcha")
@@ -60,59 +48,8 @@ public class AuthController {
public Result<?> login(@RequestBody @Valid LoginRequest request) {
String username = request.getUsername();
String password = request.getPassword();
Long tenantId = request.getTenantId();
// 如果未启用多租户,直接登录
if (tenantProperties == null || !Boolean.TRUE.equals(tenantProperties.getEnabled())) {
AuthenticationToken authenticationToken = authService.login(username, password, null);
return Result.success(authenticationToken);
}
// 多租户模式如果指定了租户ID直接验证该租户下的密码
if (tenantId != null) {
AuthenticationToken authenticationToken = authService.login(username, password, tenantId);
return Result.success(authenticationToken);
}
// 多租户模式未指定租户ID查询该用户名在所有租户下的账户
List<User> users = userService.findUserAcrossAllTenants(username);
if (users.isEmpty()) {
return Result.failed("用户不存在");
}
// 过滤出正常状态的用户
List<User> activeUsers = users.stream()
.filter(user -> user.getStatus() != null && user.getStatus() == 1)
.toList();
if (activeUsers.isEmpty()) {
return Result.failed("用户已被禁用");
}
// 如果只有1个租户尝试验证该租户下的密码兼容性
if (activeUsers.size() == 1) {
User user = activeUsers.get(0);
// 登录Spring Security 会验证密码)
AuthenticationToken authenticationToken = authService.login(username, password, user.getTenantId());
return Result.success(authenticationToken);
}
// 如果多个租户,返回 choose_tenant 响应(含 tenants 列表)
// 注意:此时不验证密码,直接返回租户列表让用户选择
List<TenantVO> tenants = activeUsers.stream()
.map(user -> tenantService.getTenantById(user.getTenantId()))
.filter(tenant -> tenant != null && (tenant.getStatus() == null || tenant.getStatus() == 1))
.distinct() // 去重(理论上不会有重复,但保险起见)
.collect(Collectors.toList());
if (tenants.isEmpty()) {
return Result.failed("用户所属的租户均不可用");
}
// 返回 choose_tenant 响应
ChooseTenantVO chooseTenantVO = new ChooseTenantVO(tenants);
return Result.failed(ResultCode.CHOOSE_TENANT, chooseTenantVO);
AuthenticationToken authenticationToken = authService.login(username, password);
return Result.success(authenticationToken);
}
@Operation(summary = "短信验证码登录")

View File

@@ -28,8 +28,5 @@ public class LoginRequest {
@Schema(description = "验证码", example = "1234")
private String captchaCode;
@Schema(description = "租户ID可选多租户模式下用于指定租户", example = "1")
private Long tenantId;
}

View File

@@ -1,27 +0,0 @@
package com.youlai.boot.auth.model.vo;
import com.youlai.boot.system.model.vo.TenantVO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
/**
* 选择租户响应VO
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "选择租户响应")
public class ChooseTenantVO implements Serializable {
@Schema(description = "租户列表")
private List<TenantVO> tenants;
}

View File

@@ -18,10 +18,9 @@ public interface AuthService {
*
* @param username 用户名
* @param password 密码
* @param tenantId 租户ID可选多租户模式下用于指定租户
* @return 登录结果
*/
AuthenticationToken login(String username, String password, Long tenantId);
AuthenticationToken login(String username, String password);
/**
* 登出

View File

@@ -21,7 +21,6 @@ import com.youlai.boot.security.model.WxMiniAppCodeAuthenticationToken;
import com.youlai.boot.security.model.WxMiniAppPhoneAuthenticationToken;
import com.youlai.boot.security.token.TokenManager;
import com.youlai.boot.security.util.SecurityUtils;
import com.youlai.boot.common.tenant.TenantContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
@@ -62,16 +61,10 @@ public class AuthServiceImpl implements AuthService {
*
* @param username 用户名
* @param password 密码
* @param tenantId 租户ID可选多租户模式下用于指定租户
* @return 访问令牌
*/
@Override
public AuthenticationToken login(String username, String password, Long tenantId) {
// 如果指定了租户ID需要先设置租户上下文以便查询该租户下的用户
if (tenantId != null) {
com.youlai.boot.common.tenant.TenantContextHolder.setTenantId(tenantId);
}
public AuthenticationToken login(String username, String password) {
// 1. 创建用于密码认证的令牌(未认证)
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(username.trim(), password);

View File

@@ -1,22 +0,0 @@
package com.youlai.boot.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 忽略多租户注解
* <p>
* 标注在方法或类上,表示该方法或类下的所有方法忽略多租户过滤
* 适用于系统管理、租户管理等不需要租户隔离的场景
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreTenant {
}

View File

@@ -13,7 +13,6 @@ import java.time.LocalDateTime;
* 基础实体类
*
* <p>实体类的基类,包含了实体类的公共属性,如创建时间、更新时间、逻辑删除标识等</p>
* <p>多租户模式下,会自动添加 tenant_id 字段(通过 MyMetaObjectHandler 自动填充)</p>
*
* @author Ray
* @since 2024/6/23
@@ -30,26 +29,6 @@ public class BaseEntity implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
/**
* 租户ID多租户模式
* <p>
* 注意:此字段仅在启用多租户时生效
* 通过 MyMetaObjectHandler 自动填充,无需手动设置
* 如果不需要多租户,可以通过配置 youlai.tenant.enabled=false 禁用
* </p>
* <p>
* 重要说明:
* 1. 默认使用 exist = false 标记字段不存在于数据库,避免单租户模式下报错
* 2. 在启用多租户时,需要确保数据库表中有 tenant_id 字段
* 3. 多租户的数据隔离主要通过 TenantLineHandler 自动添加 WHERE 条件实现
* 4. 如果需要在 INSERT 时写入 tenant_id请将 exist 改为 true 或移除 exist 属性
* 5. 或者执行 add_tenant_column.sql 脚本为表添加 tenant_id 字段
* </p>
*/
@TableField(value = "tenant_id", exist = false)
@JsonInclude(value = JsonInclude.Include.NON_NULL)
private Long tenantId;
/**
* 创建时间
*/

View File

@@ -35,11 +35,6 @@ public interface JwtClaimConstants {
*/
String AUTHORITIES = "authorities";
/**
* 租户ID
*/
String TENANT_ID = "tenantId";
/**
* 安全版本号,用于按用户失效历史令牌
*/

View File

@@ -1,83 +0,0 @@
package com.youlai.boot.common.tenant;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.extern.slf4j.Slf4j;
/**
* 租户上下文工具类
* <p>
* 使用 TransmittableThreadLocal 存储当前线程的租户ID确保线程安全
* 支持异步任务、线程池、消息队列等场景的上下文传递
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Slf4j
public class TenantContextHolder {
/**
* 租户ID线程本地变量
* 使用 TransmittableThreadLocal 支持父子线程和线程池场景的值传递
*/
private static final TransmittableThreadLocal<Long> TENANT_ID_HOLDER = new TransmittableThreadLocal<>();
/**
* 忽略租户标志(用于某些场景下临时跳过租户过滤)
*/
private static final TransmittableThreadLocal<Boolean> IGNORE_TENANT_HOLDER = new TransmittableThreadLocal<>();
/**
* 设置当前租户ID
*
* @param tenantId 租户ID
*/
public static void setTenantId(Long tenantId) {
if (tenantId != null) {
TENANT_ID_HOLDER.set(tenantId);
log.debug("设置当前租户ID: {}", tenantId);
}
}
/**
* 获取当前租户ID
*
* @return 租户ID如果未设置则返回 null
*/
public static Long getTenantId() {
return TENANT_ID_HOLDER.get();
}
/**
* 设置忽略租户标志
*
* @param ignore 是否忽略
*/
public static void setIgnoreTenant(boolean ignore) {
IGNORE_TENANT_HOLDER.set(ignore);
log.debug("设置忽略租户标志: {}", ignore);
}
/**
* 是否忽略租户
*
* @return true-忽略false-不忽略
*/
public static boolean isIgnoreTenant() {
Boolean ignore = IGNORE_TENANT_HOLDER.get();
return ignore != null && ignore;
}
/**
* 清除当前线程的租户上下文
* <p>
* 必须在请求结束时调用,避免线程池复用导致的数据泄露
* </p>
*/
public static void clear() {
TENANT_ID_HOLDER.remove();
IGNORE_TENANT_HOLDER.remove();
log.debug("清除租户上下文");
}
}

View File

@@ -5,11 +5,8 @@ import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.youlai.boot.config.property.TenantProperties;
import com.youlai.boot.plugin.mybatis.MyDataPermissionHandler;
import com.youlai.boot.plugin.mybatis.MyMetaObjectHandler;
import com.youlai.boot.plugin.mybatis.MyTenantLineHandler;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.springframework.beans.factory.annotation.Autowired;
@@ -33,27 +30,13 @@ public class MybatisConfig {
@Value("${app.db-type:mysql}")
private String dbType;
@Autowired(required = false)
private MyTenantLineHandler myTenantLineHandler;
@Autowired(required = false)
private TenantProperties tenantProperties;
/**
* 分页插件和数据权限插件
* <p>
* 如果启用了多租户,则添加多租户插件(必须在最前面)
* </p>
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 多租户插件(如果启用,必须在最前面)
if (tenantProperties != null && Boolean.TRUE.equals(tenantProperties.getEnabled()) && myTenantLineHandler != null) {
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(myTenantLineHandler));
}
// 数据权限
interceptor.addInnerInterceptor(new DataPermissionInterceptor(new MyDataPermissionHandler()));

View File

@@ -1,76 +0,0 @@
package com.youlai.boot.config;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.youlai.boot.config.property.TenantProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.List;
/**
* 多租户动态字段配置
* <p>
* 在多租户模式启用时,动态修改 BaseEntity 中 tenant_id 字段的 exist 属性为 true
* 这样可以实现:
* - 单租户模式tenant_id exist=false不映射该字段兼容没有该字段的表
* - 多租户模式tenant_id exist=true自动填充租户ID到INSERT/UPDATE语句
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true")
public class TenantDynamicFieldConfig implements InitializingBean {
private final TenantProperties tenantProperties;
@Override
public void afterPropertiesSet() {
log.info("多租户模式已启用,开始动态配置 tenant_id 字段映射...");
int modifiedCount = 0;
List<TableInfo> tableInfos = TableInfoHelper.getTableInfos();
for (TableInfo tableInfo : tableInfos) {
// 检查是否是忽略的表
String tableName = tableInfo.getTableName();
if (tenantProperties.getIgnoreTables().contains(tableName)) {
log.debug("表 {} 在忽略列表中,跳过 tenant_id 字段配置", tableName);
continue;
}
// 查找 tenant_id 字段
TableFieldInfo tenantField = tableInfo.getFieldList().stream()
.filter(field -> tenantProperties.getColumn().equals(field.getColumn()))
.findFirst()
.orElse(null);
if (tenantField != null) {
try {
// 通过反射修改 exist 属性为 true
Field existField = TableFieldInfo.class.getDeclaredField("exist");
existField.setAccessible(true);
existField.set(tenantField, true);
modifiedCount++;
log.debug("已为表 {} 启用 tenant_id 字段映射", tableName);
} catch (NoSuchFieldException | IllegalAccessException e) {
log.warn("修改表 {} 的 tenant_id 字段配置失败: {}", tableName, e.getMessage());
}
} else {
log.warn("表 {} 未找到 tenant_id 字段,请检查实体类是否继承 BaseEntity", tableName);
}
}
log.info("多租户字段配置完成,共修改 {} 张表", modifiedCount);
}
}

View File

@@ -1,52 +0,0 @@
package com.youlai.boot.config.property;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 多租户配置属性
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@Component
@ConfigurationProperties(prefix = "youlai.tenant")
public class TenantProperties {
/**
* 是否启用多租户功能
* 默认false不启用
*/
private Boolean enabled = false;
/**
* 租户字段名
* 默认tenant_id
*/
private String column = "tenant_id";
/**
* 默认租户ID用于兼容旧数据tenant_id 为 NULL 时使用)
* 默认1
*/
private Long defaultTenantId = 1L;
/**
* 忽略多租户过滤的表名列表
* 系统表、租户表等不需要租户隔离的表
*/
private List<String> ignoreTables = new ArrayList<>();
/**
* 请求头中的租户ID字段名
* 默认tenant-id
*/
private String headerName = "tenant-id";
}

View File

@@ -1,46 +0,0 @@
package com.youlai.boot.core.aspect;
import com.youlai.boot.common.annotation.IgnoreTenant;
import com.youlai.boot.common.tenant.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 多租户切面
* <p>
* 处理 @IgnoreTenant 注解,临时跳过租户过滤
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Aspect
@Component
@Order(1)
@Slf4j
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class TenantAspect {
/**
* 环绕通知:处理 @IgnoreTenant 注解
*/
@Around("@annotation(ignoreTenant) || @within(ignoreTenant)")
public Object around(ProceedingJoinPoint joinPoint, IgnoreTenant ignoreTenant) throws Throwable {
try {
// 设置忽略租户标志
TenantContextHolder.setIgnoreTenant(true);
log.debug("方法 {} 忽略多租户过滤", joinPoint.getSignature().getName());
// 执行原方法
return joinPoint.proceed();
} finally {
// 恢复租户过滤
TenantContextHolder.setIgnoreTenant(false);
}
}
}

View File

@@ -6,7 +6,7 @@ import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.core.web.ResultCode;
import com.youlai.boot.common.util.IPUtils;
import com.youlai.boot.core.web.WebResponseHelper;
import com.youlai.boot.core.web.WebResponseWriter;
import com.youlai.boot.system.service.ConfigService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@@ -88,7 +88,7 @@ public class RateLimiterFilter extends OncePerRequestFilter {
// 判断是否限流
if (rateLimit(ip)) {
// 返回限流错误信息
WebResponseHelper.writeError(response, ResultCode.REQUEST_CONCURRENCY_LIMIT_EXCEEDED);
WebResponseWriter.writeError(response, ResultCode.REQUEST_CONCURRENCY_LIMIT_EXCEEDED);
return;
}

View File

@@ -1,97 +0,0 @@
package com.youlai.boot.core.filter;
import com.youlai.boot.common.constant.SecurityConstants;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.config.property.TenantProperties;
import com.youlai.boot.security.model.SysUserDetails;
import com.youlai.boot.security.token.TokenManager;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 租户上下文过滤器
* <p>
* 从请求头中获取租户ID设置到线程上下文
* 请求结束时自动清除上下文,避免线程池复用导致的数据泄露
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Slf4j
@Component
@Order(1) // 确保在其他过滤器之前执行
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class TenantContextFilter extends OncePerRequestFilter {
private final TenantProperties tenantProperties;
private final TokenManager tokenManager;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
// 1) 优先从已认证用户中获取租户ID
Long tenantId = resolveTenantFromAuthentication(SecurityContextHolder.getContext().getAuthentication());
// 2) 如果尚未获取到,尝试从 Token 中解析
if (tenantId == null) {
tenantId = resolveTenantFromToken(request);
}
// 3) 仍为空则使用默认租户
if (tenantId == null) {
Long defaultTenantId = tenantProperties.getDefaultTenantId();
if (defaultTenantId != null) {
tenantId = defaultTenantId;
}
}
if (tenantId != null) {
TenantContextHolder.setTenantId(tenantId);
log.debug("TenantContextFilter set tenantId: {}", tenantId);
}
filterChain.doFilter(request, response);
} finally {
TenantContextHolder.clear();
}
}
private Long resolveTenantFromAuthentication(Authentication authentication) {
if (authentication == null) {
return null;
}
Object principal = authentication.getPrincipal();
if (principal instanceof SysUserDetails details) {
return details.getTenantId();
}
return null;
}
private Long resolveTenantFromToken(HttpServletRequest request) {
String authHeader = request.getHeader("Authorization");
if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(SecurityConstants.BEARER_TOKEN_PREFIX)) {
return null;
}
String token = authHeader.substring(SecurityConstants.BEARER_TOKEN_PREFIX.length());
Authentication authentication = tokenManager.parseToken(token);
return resolveTenantFromAuthentication(authentication);
}
}

View File

@@ -76,9 +76,6 @@ public enum ResultCode implements IResultCode, Serializable {
USER_VERIFICATION_CODE_ATTEMPT_LIMIT_EXCEEDED("A0241", "用户验证码尝试次数超限"),
USER_VERIFICATION_CODE_EXPIRED("A0242", "用户验证码过期"),
// 多租户登录
CHOOSE_TENANT("A0250", "请选择登录租户"),
/** 二级宏观错误码 */
ACCESS_PERMISSION_EXCEPTION("A0300", "访问权限异常"),
ACCESS_UNAUTHORIZED("A0301", "访问未授权"),

View File

@@ -1,77 +0,0 @@
package com.youlai.boot.core.web;
import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import java.nio.charset.StandardCharsets;
/**
* Web响应辅助类
* <p>
* 用于在过滤器、处理器等无法使用 @RestControllerAdvice 的场景中统一处理响应
*
* @author Ray.Hao
* @since 2.0.0
*/
@Slf4j
public class WebResponseHelper {
/**
* 写入错误响应
*
* @param response HttpServletResponse
* @param resultCode 响应结果码
*/
public static void writeError(HttpServletResponse response, ResultCode resultCode) {
writeError(response, resultCode, null);
}
/**
* 写入错误响应(带自定义消息)
*
* @param response HttpServletResponse
* @param resultCode 响应结果码
* @param message 自定义消息
*/
public static void writeError(HttpServletResponse response, ResultCode resultCode, String message) {
try {
// 设置HTTP状态码
int httpStatus = mapHttpStatus(resultCode);
response.setStatus(httpStatus);
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
// 构建响应对象
Result<?> result = message == null
? Result.failed(resultCode)
: Result.failed(resultCode, message);
// 写入响应
JakartaServletUtil.write(response,
JSONUtil.toJsonStr(result),
MediaType.APPLICATION_JSON_VALUE
);
} catch (Exception e) {
log.error("写入错误响应失败: resultCode={}, message={}", resultCode, message, e);
}
}
/**
* 根据业务结果码映射HTTP状态码
*
* @param resultCode 业务结果码
* @return HTTP状态码
*/
private static int mapHttpStatus(ResultCode resultCode) {
return switch (resultCode) {
case ACCESS_UNAUTHORIZED,
ACCESS_TOKEN_INVALID,
REFRESH_TOKEN_INVALID -> HttpStatus.UNAUTHORIZED.value();
default -> HttpStatus.BAD_REQUEST.value();
};
}
}

View File

@@ -0,0 +1,122 @@
package com.youlai.boot.core.web;
import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import java.nio.charset.StandardCharsets;
/**
* Web响应写入器
* <p>
* 用于在过滤器、Security处理器等无法使用 @RestControllerAdvice 的场景中统一写入HTTP响应。
* 支持写入成功响应和错误响应。
* 此类为工具类,所有方法均为静态方法,禁止实例化。
*
* @author Ray.Hao
* @since 2.0.0
*/
@Slf4j
public final class WebResponseWriter {
/**
* 私有构造函数,防止实例化
*/
private WebResponseWriter() {
throw new UnsupportedOperationException("工具类不允许实例化");
}
/**
* 写入成功响应
*
* @param response HttpServletResponse
* @param data 响应数据(可选)
*/
public static void writeSuccess(HttpServletResponse response, Object data) {
writeResult(response, Result.success(data), HttpStatus.OK.value());
}
/**
* 写入成功响应(无数据)
*
* @param response HttpServletResponse
*/
public static void writeSuccess(HttpServletResponse response) {
writeSuccess(response, null);
}
/**
* 写入错误响应
*
* @param response HttpServletResponse
* @param resultCode 响应结果码
*/
public static void writeError(HttpServletResponse response, ResultCode resultCode) {
writeError(response, resultCode, null);
}
/**
* 写入错误响应(带自定义消息)
*
* @param response HttpServletResponse
* @param resultCode 响应结果码
* @param message 自定义消息(可选,为 null 时使用 resultCode 的默认消息)
*/
public static void writeError(HttpServletResponse response, ResultCode resultCode, String message) {
Result<?> result = message == null
? Result.failed(resultCode)
: Result.failed(resultCode, message);
int httpStatus = mapHttpStatus(resultCode);
writeResult(response, result, httpStatus);
}
/**
* 写入响应结果(通用方法)
*
* @param response HttpServletResponse
* @param result 响应结果对象
* @param httpStatus HTTP状态码
*/
private static void writeResult(HttpServletResponse response, Result<?> result, int httpStatus) {
try {
// 设置HTTP状态码
response.setStatus(httpStatus);
// 设置响应编码和内容类型
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
// 写入响应
JakartaServletUtil.write(response,
JSONUtil.toJsonStr(result),
MediaType.APPLICATION_JSON_VALUE
);
} catch (Exception e) {
log.error("写入响应时发生未知异常: httpStatus={}, result={}", httpStatus, result, e);
}
}
/**
* 根据业务结果码映射HTTP状态码
*
* @param resultCode 业务结果码
* @return HTTP状态码
*/
private static int mapHttpStatus(ResultCode resultCode) {
return switch (resultCode) {
case ACCESS_UNAUTHORIZED,
ACCESS_TOKEN_INVALID,
REFRESH_TOKEN_INVALID -> HttpStatus.UNAUTHORIZED.value();
default -> HttpStatus.BAD_REQUEST.value();
};
}
}

View File

@@ -1,8 +1,6 @@
package com.youlai.boot.plugin.mybatis;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.config.property.TenantProperties;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
@@ -13,7 +11,7 @@ import java.time.LocalDateTime;
/**
* mybatis-plus 字段自动填充
* <p>
* 支持自动填充创建时间、更新时间和租户ID
* 支持自动填充创建时间、更新时间
* </p>
*
* @author Ray.Hao
@@ -23,15 +21,8 @@ import java.time.LocalDateTime;
@RequiredArgsConstructor
public class MyMetaObjectHandler implements MetaObjectHandler {
@Autowired(required = false)
private TenantProperties tenantProperties;
/**
* 新增填充创建时间、更新时间和租户ID
* <p>
* 多租户模式下tenant_id 字段的 exist 属性会被 TenantDynamicFieldConfig 动态设置为 true
* 因此这里的 strictInsertFill 可以正常工作
* </p>
* 新增填充创建时间、更新时间
*
* @param metaObject 元数据
*/
@@ -39,21 +30,6 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
// 如果启用了多租户自动填充租户ID
if (tenantProperties != null && Boolean.TRUE.equals(tenantProperties.getEnabled())) {
Long tenantId = TenantContextHolder.getTenantId();
if (tenantId == null) {
// 如果上下文中没有租户ID使用默认租户ID
tenantId = tenantProperties.getDefaultTenantId();
}
if (tenantId != null) {
// 使用 strictInsertFill 自动填充租户ID
// 注意:由于 TenantDynamicFieldConfig 已将 exist 设置为 true这里可以正常填充
Long finalTenantId = tenantId;
this.strictInsertFill(metaObject, "tenantId", () -> finalTenantId, Long.class);
}
}
}
/**

View File

@@ -1,90 +0,0 @@
package com.youlai.boot.plugin.mybatis;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.config.property.TenantProperties;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* MyBatis-Plus 多租户处理器
* <p>
* 实现 TenantLineHandler 接口,自动为 SQL 添加租户过滤条件
* 仅在启用多租户时注册(通过 @ConditionalOnProperty 控制)
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class MyTenantLineHandler implements TenantLineHandler {
private final TenantProperties tenantProperties;
/**
* 获取租户ID表达式
* <p>
* 从 TenantContextHolder 获取当前租户ID
* 如果未设置或忽略租户,返回 NULL不添加租户条件
* </p>
*
* @return 租户ID表达式
*/
@Override
public Expression getTenantId() {
// 如果设置了忽略租户标志,返回 NULL不添加租户条件
if (TenantContextHolder.isIgnoreTenant()) {
return new NullValue();
}
// 获取当前租户ID
Long tenantId = TenantContextHolder.getTenantId();
// 如果未设置租户ID使用默认租户ID
if (tenantId == null) {
tenantId = tenantProperties.getDefaultTenantId();
}
return new LongValue(tenantId);
}
/**
* 获取租户字段名
*
* @return 租户字段名
*/
@Override
public String getTenantIdColumn() {
return tenantProperties.getColumn();
}
/**
* 判断表是否忽略多租户过滤
* <p>
* 系统表、租户表等不需要租户隔离的表应返回 true
* </p>
*
* @param tableName 表名
* @return true-忽略false-不忽略
*/
@Override
public boolean ignoreTable(String tableName) {
List<String> ignoreTables = tenantProperties.getIgnoreTables();
if (ignoreTables == null || ignoreTables.isEmpty()) {
return false;
}
// 忽略表名匹配(不区分大小写)
return ignoreTables.stream()
.anyMatch(ignoreTable -> ignoreTable.equalsIgnoreCase(tableName));
}
}

View File

@@ -7,7 +7,7 @@ import cn.hutool.json.JSONUtil;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.constant.SecurityConstants;
import com.youlai.boot.core.web.ResultCode;
import com.youlai.boot.core.web.WebResponseHelper;
import com.youlai.boot.core.web.WebResponseWriter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
@@ -61,7 +61,7 @@ public class CaptchaValidationFilter extends OncePerRequestFilter {
// 仅支持 JSON 登录
String contentType = request.getContentType();
if (contentType == null || !contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
WebResponseHelper.writeError(response, ResultCode.USER_VERIFICATION_CODE_ERROR);
WebResponseWriter.writeError(response, ResultCode.USER_VERIFICATION_CODE_ERROR);
return;
}
@@ -80,7 +80,7 @@ public class CaptchaValidationFilter extends OncePerRequestFilter {
}
if (StrUtil.isBlank(captchaCode) || StrUtil.isBlank(captchaId)) {
WebResponseHelper.writeError(response, ResultCode.USER_VERIFICATION_CODE_ERROR);
WebResponseWriter.writeError(response, ResultCode.USER_VERIFICATION_CODE_ERROR);
return;
}
@@ -88,7 +88,7 @@ public class CaptchaValidationFilter extends OncePerRequestFilter {
StrUtil.format(RedisConstants.Captcha.IMAGE_CODE, captchaId)
);
if (cacheVerifyCode == null) {
WebResponseHelper.writeError(response, ResultCode.USER_VERIFICATION_CODE_EXPIRED);
WebResponseWriter.writeError(response, ResultCode.USER_VERIFICATION_CODE_EXPIRED);
return;
}
@@ -96,7 +96,7 @@ public class CaptchaValidationFilter extends OncePerRequestFilter {
HttpServletRequest repeatableRequest = new RepeatableReadRequestWrapper(requestWrapper, bodyBytes);
chain.doFilter(repeatableRequest, response);
} else {
WebResponseHelper.writeError(response, ResultCode.USER_VERIFICATION_CODE_ERROR);
WebResponseWriter.writeError(response, ResultCode.USER_VERIFICATION_CODE_ERROR);
}
}

View File

@@ -3,7 +3,7 @@ package com.youlai.boot.security.filter;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.common.constant.SecurityConstants;
import com.youlai.boot.core.web.ResultCode;
import com.youlai.boot.core.web.WebResponseHelper;
import com.youlai.boot.core.web.WebResponseWriter;
import com.youlai.boot.security.token.TokenManager;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@@ -52,7 +52,7 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
// 执行令牌有效性检查(包含密码学验签和过期时间验证)
boolean isValidToken = tokenManager.validateToken(rawToken);
if (!isValidToken) {
WebResponseHelper.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
WebResponseWriter.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
return;
}
@@ -63,7 +63,7 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
} catch (Exception ex) {
// 安全上下文清除保障(防止上下文残留)
SecurityContextHolder.clearContext();
WebResponseHelper.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
WebResponseWriter.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
return;
}

View File

@@ -1,7 +1,7 @@
package com.youlai.boot.security.handler;
import com.youlai.boot.core.web.ResultCode;
import com.youlai.boot.core.web.WebResponseHelper;
import com.youlai.boot.core.web.WebResponseWriter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
@@ -20,7 +20,7 @@ public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) {
WebResponseHelper.writeError(response, ResultCode.ACCESS_UNAUTHORIZED);
WebResponseWriter.writeError(response, ResultCode.ACCESS_UNAUTHORIZED);
}
}

View File

@@ -1,7 +1,7 @@
package com.youlai.boot.security.handler;
import com.youlai.boot.core.web.ResultCode;
import com.youlai.boot.core.web.WebResponseHelper;
import com.youlai.boot.core.web.WebResponseWriter;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
@@ -32,13 +32,13 @@ public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
if (authException instanceof BadCredentialsException) {
// 用户名或密码错误
WebResponseHelper.writeError(response, ResultCode.USER_PASSWORD_ERROR);
WebResponseWriter.writeError(response, ResultCode.USER_PASSWORD_ERROR);
} else if(authException instanceof InsufficientAuthenticationException){
// 请求头缺失Authorization、Token格式错误、Token过期、签名验证失败
WebResponseHelper.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
WebResponseWriter.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
} else {
// 其他未明确处理的认证异常(如账户被锁定、账户禁用等)
WebResponseHelper.writeError(response, ResultCode.USER_LOGIN_EXCEPTION, authException.getMessage());
WebResponseWriter.writeError(response, ResultCode.USER_LOGIN_EXCEPTION, authException.getMessage());
}
}
}

View File

@@ -38,11 +38,6 @@ public class OnlineUser {
*/
private Integer dataScope;
/**
* 租户ID
*/
private Long tenantId;
/**
* 角色权限集合
*/

View File

@@ -56,11 +56,6 @@ public class SysUserDetails implements UserDetails {
*/
private Integer dataScope;
/**
* 租户ID
*/
private Long tenantId;
/**
* 用户角色权限集合
*/
@@ -78,7 +73,6 @@ public class SysUserDetails implements UserDetails {
this.enabled = ObjectUtil.equal(user.getStatus(), 1);
this.deptId = user.getDeptId();
this.dataScope = user.getDataScope();
this.tenantId = user.getTenantId();
// 初始化角色权限集合
this.authorities = CollectionUtil.isNotEmpty(user.getRoles())

View File

@@ -54,9 +54,4 @@ public class UserAuthCredentials {
*/
private Integer dataScope;
/**
* 租户ID从登录上下文中获取
*/
private Long tenantId;
}

View File

@@ -3,8 +3,6 @@ package com.youlai.boot.security.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
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.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -26,7 +24,6 @@ import java.util.*;
public class PermissionService {
private final RedisTemplate<String, Object> redisTemplate;
private final TenantProperties tenantProperties;
/**
* 判断当前登录用户是否拥有操作权限
@@ -70,20 +67,7 @@ public class PermissionService {
/**
* 构建租户权限缓存key
*
* @param tenantId 租户ID
* @return 缓存key
*/
private String buildRolePermsCacheKey(Long tenantId) {
if (!tenantProperties.getEnabled() || tenantId == null) {
return RedisConstants.System.ROLE_PERMS;
}
return RedisConstants.System.ROLE_PERMS + ":" + tenantId;
}
/**
* 从缓存中获取角色权限列表(兼容单租户和多租户)
* 从缓存中获取角色权限列表
*
* @param roleCodes 角色编码集合
* @return 角色权限列表
@@ -93,9 +77,8 @@ public class PermissionService {
return Collections.emptySet();
}
// 获取当前租户ID并构建缓存Key
Long tenantId = TenantContextHolder.getTenantId();
String cacheKey = buildRolePermsCacheKey(tenantId);
// 构建缓存Key
String cacheKey = RedisConstants.System.ROLE_PERMS;
Set<String> perms = new HashSet<>();
Collection<Object> roleCodesAsObjects = new ArrayList<>(roleCodes);

View File

@@ -1,6 +1,5 @@
package com.youlai.boot.security.service;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.security.model.SysUserDetails;
import com.youlai.boot.security.model.UserAuthCredentials;
import com.youlai.boot.system.service.UserService;
@@ -38,8 +37,6 @@ public class SysUserDetailsService implements UserDetailsService {
if (userAuthCredentials == null) {
throw new UsernameNotFoundException(username);
}
// 将当前上下文中的租户ID写入认证凭证便于后续 Token 携带租户信息
userAuthCredentials.setTenantId(TenantContextHolder.getTenantId());
return new SysUserDetails(userAuthCredentials);
} catch (Exception e) {
// 记录异常日志

View File

@@ -91,7 +91,6 @@ public class JwtTokenManager implements TokenManager {
userDetails.setUserId(payloads.getLong(JwtClaimConstants.USER_ID)); // 用户ID
userDetails.setDeptId(payloads.getLong(JwtClaimConstants.DEPT_ID)); // 部门ID
userDetails.setDataScope(payloads.getInt(JwtClaimConstants.DATA_SCOPE)); // 数据权限范围
userDetails.setTenantId(payloads.getLong(JwtClaimConstants.TENANT_ID)); // 租户ID
userDetails.setUsername(payloads.getStr(JWTPayload.SUBJECT)); // 用户名
// 角色集合
@@ -276,7 +275,6 @@ public class JwtTokenManager implements TokenManager {
payload.put(JwtClaimConstants.USER_ID, userDetails.getUserId()); // 用户ID
payload.put(JwtClaimConstants.DEPT_ID, userDetails.getDeptId()); // 部门ID
payload.put(JwtClaimConstants.DATA_SCOPE, userDetails.getDataScope()); // 数据权限范围
payload.put(JwtClaimConstants.TENANT_ID, userDetails.getTenantId()); // 租户ID
// claims 中添加角色信息
Set<String> roles = authentication.getAuthorities().stream()

View File

@@ -61,7 +61,6 @@ public class RedisTokenManager implements TokenManager {
user.getUsername(),
user.getDeptId(),
user.getDataScope(),
user.getTenantId(),
user.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toSet())
@@ -269,7 +268,6 @@ public class RedisTokenManager implements TokenManager {
userDetails.setUsername(onlineUser.getUsername());
userDetails.setDeptId(onlineUser.getDeptId());
userDetails.setDataScope(onlineUser.getDataScope());
userDetails.setTenantId(onlineUser.getTenantId());
userDetails.setAuthorities(authorities);
return userDetails;
}

View File

@@ -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);
}
}

View File

@@ -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> {
}

View File

@@ -13,11 +13,6 @@ import java.util.Set;
@Data
public class RolePermsBO {
/**
* 租户ID
*/
private Long tenantId;
/**
* 角色编码
*/

View File

@@ -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;

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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;

View File

@@ -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;

View File

@@ -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;
}

View File

@@ -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-保密)
*/

View File

@@ -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;

View File

@@ -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;
}

View File

@@ -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);
}

View File

@@ -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);
/**
* 获取导出用户列表

View File

@@ -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);
}

View File

@@ -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);
}
/**

View File

@@ -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);
}
}
}

View File

@@ -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获取用户认证信息