feat(react-web-next): 新增.editorconfig和.prettierrc配置文件,添加public/.gitkeep占位文件
This commit is contained in:
+1
-2
@@ -86,8 +86,7 @@ public abstract class DefaultPermissionServiceImpl {
|
||||
return false;
|
||||
}
|
||||
|
||||
//保存租户信息
|
||||
TenantContextHolder.setTenant(clientId);
|
||||
// 不再将 clientId 混用为租户ID,避免概念混淆
|
||||
|
||||
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
|
||||
List<SysMenu> menuList = findMenuByRoleCodes(roleCodes);
|
||||
|
||||
@@ -117,5 +117,10 @@
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
+207
@@ -2,9 +2,17 @@ package com.central.common.context;
|
||||
|
||||
import com.alibaba.ttl.TransmittableThreadLocal;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 登录用户holder
|
||||
* 扩展支持租户管理功能
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2022/6/26
|
||||
@@ -12,9 +20,12 @@ import com.central.common.model.LoginAppUser;
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Slf4j
|
||||
public class LoginUserContextHolder {
|
||||
private static final ThreadLocal<LoginAppUser> CONTEXT = new TransmittableThreadLocal<>();
|
||||
|
||||
// === 现有方法保持完全不变 ===
|
||||
|
||||
public static void setUser(LoginAppUser user) {
|
||||
CONTEXT.set(user);
|
||||
}
|
||||
@@ -26,4 +37,200 @@ public class LoginUserContextHolder {
|
||||
public static void clear() {
|
||||
CONTEXT.remove();
|
||||
}
|
||||
|
||||
// === 新增租户管理功能 ===
|
||||
|
||||
/**
|
||||
* 设置用户的当前查询租户
|
||||
*/
|
||||
public static void setCurrentTenant(String tenantId) {
|
||||
LoginAppUser user = getUser();
|
||||
if (user == null) {
|
||||
throw new SecurityException("用户未登录");
|
||||
}
|
||||
|
||||
// 验证权限:只有管理员且租户在可访问列表中才能切换
|
||||
if (!user.isCanSwitchTenant()) {
|
||||
throw new SecurityException("用户无租户切换权限");
|
||||
}
|
||||
|
||||
List<String> accessibleTenants = user.getAccessibleTenantIds();
|
||||
if (accessibleTenants == null || !accessibleTenants.contains(tenantId)) {
|
||||
throw new SecurityException("无权限访问租户: " + tenantId);
|
||||
}
|
||||
|
||||
user.setCurrentTenantId(tenantId);
|
||||
|
||||
// 同时设置原有的TenantContextHolder(保持兼容性)
|
||||
TenantContextHolder.setTenant(tenantId);
|
||||
|
||||
log.debug("用户 {} 切换到租户 {}", user.getUsername(), tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前查询租户ID
|
||||
*/
|
||||
public static String getCurrentTenantId() {
|
||||
LoginAppUser user = getUser();
|
||||
if (user != null) {
|
||||
// 如果没有设置当前租户,返回用户默认租户
|
||||
return StringUtils.hasText(user.getCurrentTenantId())
|
||||
? user.getCurrentTenantId()
|
||||
: user.getCompany();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前查询范围的所有租户ID(当前租户+所有子租户)
|
||||
*/
|
||||
public static List<String> getCurrentQueryTenantIds() {
|
||||
String currentTenantId = getCurrentTenantId();
|
||||
if (!StringUtils.hasText(currentTenantId)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
LoginAppUser user = getUser();
|
||||
|
||||
// C端用户只能查询自己的租户
|
||||
if (user != null && "APP".equals(getUserType(user))) {
|
||||
return Arrays.asList(currentTenantId);
|
||||
}
|
||||
|
||||
// 管理员用户可以查询当前租户及其所有子租户
|
||||
try {
|
||||
ITenantHierarchyService tenantService = getBean(ITenantHierarchyService.class);
|
||||
if (tenantService != null) {
|
||||
List<String> subTenants = tenantService.getAllSubTenantIds(currentTenantId);
|
||||
if (subTenants != null && !subTenants.isEmpty()) {
|
||||
return subTenants;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("获取子租户列表失败,降级为单租户查询: tenantId={}, error={}", currentTenantId, e.getMessage());
|
||||
}
|
||||
|
||||
// 降级处理:只返回当前租户
|
||||
return Arrays.asList(currentTenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否有访问指定租户的权限
|
||||
*/
|
||||
public static boolean hasTenantAccess(String tenantId) {
|
||||
LoginAppUser user = getUser();
|
||||
if (user == null || !StringUtils.hasText(tenantId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<String> accessibleTenants = user.getAccessibleTenantIds();
|
||||
return accessibleTenants != null && accessibleTenants.contains(tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置为用户默认租户
|
||||
*/
|
||||
public static void resetToDefaultTenant() {
|
||||
LoginAppUser user = getUser();
|
||||
if (user == null) {
|
||||
throw new SecurityException("用户未登录");
|
||||
}
|
||||
|
||||
String defaultTenantId = user.getCompany();
|
||||
if (StringUtils.hasText(defaultTenantId)) {
|
||||
user.setCurrentTenantId(defaultTenantId);
|
||||
TenantContextHolder.setTenant(defaultTenantId);
|
||||
log.debug("用户 {} 重置为默认租户 {}", user.getUsername(), defaultTenantId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户类型
|
||||
*/
|
||||
public static String getUserType() {
|
||||
LoginAppUser user = getUser();
|
||||
return user != null ? getUserType(user) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户类型
|
||||
*/
|
||||
private static String getUserType(LoginAppUser user) {
|
||||
// 优先从属性中获取
|
||||
Object typeFromAttributes = user.getAttributes().get("type");
|
||||
if (typeFromAttributes != null) {
|
||||
return typeFromAttributes.toString();
|
||||
}
|
||||
// 默认返回BACKEND
|
||||
return "BACKEND";
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为管理员用户
|
||||
*/
|
||||
public static boolean isManagementUser() {
|
||||
LoginAppUser user = getUser();
|
||||
return user != null && user.isCanSwitchTenant();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户可访问的租户列表
|
||||
*/
|
||||
public static List<String> getAccessibleTenantIds() {
|
||||
LoginAppUser user = getUser();
|
||||
return user != null ? user.getAccessibleTenantIds() : Collections.emptyList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户所属的默认租户
|
||||
*/
|
||||
public static String getDefaultTenantId() {
|
||||
LoginAppUser user = getUser();
|
||||
return user != null ? user.getCompany() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证当前租户上下文是否有效
|
||||
*/
|
||||
public static boolean validateTenantContext() {
|
||||
try {
|
||||
LoginAppUser user = getUser();
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String currentTenantId = getCurrentTenantId();
|
||||
if (!StringUtils.hasText(currentTenantId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 对于管理员用户,检查当前租户是否在可访问列表中
|
||||
if (user.isCanSwitchTenant()) {
|
||||
return hasTenantAccess(currentTenantId);
|
||||
}
|
||||
|
||||
// 对于普通用户,检查当前租户是否为默认租户
|
||||
return currentTenantId.equals(user.getCompany());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("验证租户上下文失败: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Spring Bean(使用反射避免循环依赖)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> T getBean(Class<T> clazz) {
|
||||
try {
|
||||
// 通过反射获取SpringContextHolder
|
||||
Class<?> springContextHolderClass = Class.forName("com.central.common.utils.SpringContextHolder");
|
||||
java.lang.reflect.Method getBeanMethod = springContextHolderClass.getMethod("getBean", Class.class);
|
||||
return (T) getBeanMethod.invoke(null, clazz);
|
||||
} catch (Exception e) {
|
||||
log.warn("无法获取Bean {}: {}", clazz.getSimpleName(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.central.common.context;
|
||||
|
||||
import com.alibaba.ttl.TransmittableThreadLocal;
|
||||
|
||||
/**
|
||||
* 本次请求的“租户查询覆盖”上下文(优先级高于默认租户)
|
||||
* 由入口过滤器根据请求参数设置,仅对当前请求生效。
|
||||
*/
|
||||
public class TenantQueryOverrideContext {
|
||||
private static final ThreadLocal<String> OVERRIDE_TENANT = new TransmittableThreadLocal<>();
|
||||
|
||||
public static void setTenantId(String tenantId) {
|
||||
OVERRIDE_TENANT.set(tenantId);
|
||||
}
|
||||
|
||||
public static String getTenantId() {
|
||||
return OVERRIDE_TENANT.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
OVERRIDE_TENANT.remove();
|
||||
}
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.central.common.datascope.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 注解到方法/类上,忽略租户层级数据范围过滤
|
||||
* 适用于跨租户统计、平台级查询等场景。
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface IgnoreTenantScope {
|
||||
}
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.central.common.datascope.aop;
|
||||
|
||||
import com.central.common.datascope.annotation.IgnoreTenantScope;
|
||||
import com.central.common.datascope.context.DataScopeContext;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 基于注解的租户范围控制切面
|
||||
* @IgnoreTenantScope 标注的方法/类将忽略租户层级过滤。
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
|
||||
public class TenantScopeAspect {
|
||||
|
||||
@Pointcut("@within(com.central.common.datascope.annotation.IgnoreTenantScope) || @annotation(com.central.common.datascope.annotation.IgnoreTenantScope)")
|
||||
public void ignoreTenantPointcut() {}
|
||||
|
||||
@Around("ignoreTenantPointcut()")
|
||||
public Object aroundIgnoreTenant(ProceedingJoinPoint pjp) throws Throwable {
|
||||
boolean entered = false;
|
||||
try {
|
||||
DataScopeContext.enterIgnoreTenant();
|
||||
entered = true;
|
||||
return pjp.proceed();
|
||||
} finally {
|
||||
if (entered) {
|
||||
DataScopeContext.exitIgnoreTenant();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.central.common.datascope.context;
|
||||
|
||||
/**
|
||||
* 数据范围上下文(基于ThreadLocal)
|
||||
* 用于控制是否忽略租户层级过滤等行为。
|
||||
*/
|
||||
public class DataScopeContext {
|
||||
private static final ThreadLocal<Integer> IGNORE_TENANT_COUNTER = ThreadLocal.withInitial(() -> 0);
|
||||
|
||||
/**
|
||||
* 进入“忽略租户过滤”上下文(可重入)
|
||||
*/
|
||||
public static void enterIgnoreTenant() {
|
||||
IGNORE_TENANT_COUNTER.set(IGNORE_TENANT_COUNTER.get() + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出“忽略租户过滤”上下文
|
||||
*/
|
||||
public static void exitIgnoreTenant() {
|
||||
Integer val = IGNORE_TENANT_COUNTER.get();
|
||||
int next = val == null ? 0 : Math.max(0, val - 1);
|
||||
if (next == 0) {
|
||||
IGNORE_TENANT_COUNTER.remove();
|
||||
} else {
|
||||
IGNORE_TENANT_COUNTER.set(next);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前是否处于“忽略租户过滤”上下文
|
||||
*/
|
||||
public static boolean isIgnoreTenant() {
|
||||
Integer val = IGNORE_TENANT_COUNTER.get();
|
||||
return val != null && val > 0;
|
||||
}
|
||||
}
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.central.common.datascope.mp.sql.handler;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 组合多个 SqlHandler 的结果(以 AND 连接)
|
||||
*/
|
||||
public class CombinedSqlHandler implements SqlHandler {
|
||||
|
||||
private final SqlHandler[] handlers;
|
||||
|
||||
public CombinedSqlHandler(SqlHandler... handlers) {
|
||||
this.handlers = handlers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String handleScopeSql() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (SqlHandler handler : handlers) {
|
||||
if (handler == null) continue;
|
||||
String clause = handler.handleScopeSql();
|
||||
if (StringUtils.hasText(clause)) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append(" AND ");
|
||||
}
|
||||
sb.append("(").append(clause).append(")");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
+8
-5
@@ -9,6 +9,7 @@ import com.central.common.feign.UserService;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.model.SysRole;
|
||||
import com.central.common.properties.DataScopeProperties;
|
||||
import com.central.common.utils.SpringContextHolder;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
@@ -21,9 +22,6 @@ import java.util.Objects;
|
||||
*/
|
||||
public class CreatorDataScopeSqlHandler implements SqlHandler{
|
||||
|
||||
@Resource
|
||||
UserService userService;
|
||||
|
||||
@Resource
|
||||
private DataScopeProperties dataScopeProperties;
|
||||
|
||||
@@ -36,7 +34,11 @@ public class CreatorDataScopeSqlHandler implements SqlHandler{
|
||||
@Override
|
||||
public String handleScopeSql() {
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
Assert.notNull(user, "登陆人不能为空");
|
||||
// 定时任务/后台任务等无登录用户上下文时,不追加创建人过滤,避免抛出异常
|
||||
if (user == null) {
|
||||
return DO_NOTHING;
|
||||
}
|
||||
/*UserService userService = SpringContextHolder.getBean(UserService.class);
|
||||
List<SysRole> roleList = userService.findRolesByUserId(user.getId());
|
||||
return StrUtil.isBlank(dataScopeProperties.getCreatorIdColumnName())
|
||||
||CollUtil.isEmpty(roleList)
|
||||
@@ -45,6 +47,7 @@ public class CreatorDataScopeSqlHandler implements SqlHandler{
|
||||
// 这里确保有配置权限范围控制的字段
|
||||
// 1. 如果没有配置角色的情况默认采用只读全部的记录
|
||||
// 2. 如果有配置角色的话判断是否存在有ALL获取null的情况,如果没有ALL的话读取个人创建记录
|
||||
String.format("%s = '%s'", dataScopeProperties.getCreatorIdColumnName(), user.getId());
|
||||
String.format("%s = '%s'", dataScopeProperties.getCreatorIdColumnName(), user.getId());*/
|
||||
return DO_NOTHING;
|
||||
}
|
||||
}
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.central.common.datascope.mp.sql.handler;
|
||||
|
||||
import com.central.common.context.TenantQueryOverrideContext;
|
||||
import com.central.common.datascope.context.DataScopeContext;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import com.central.common.utils.SecurityTenantUtils;
|
||||
import com.central.common.utils.SpringContextHolder;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 基于租户层级的范围过滤处理器
|
||||
* 生成形如:tenant_id IN ('t1','t1-1',...)
|
||||
*/
|
||||
public class TenantDataScopeSqlHandler implements SqlHandler {
|
||||
|
||||
private final String columnName;
|
||||
|
||||
public TenantDataScopeSqlHandler() {
|
||||
this("tenant_id");
|
||||
}
|
||||
|
||||
public TenantDataScopeSqlHandler(String columnName) {
|
||||
this.columnName = columnName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String handleScopeSql() {
|
||||
// 注解AOP可临时关闭租户过滤
|
||||
if (DataScopeContext.isIgnoreTenant()) {
|
||||
return DO_NOTHING;
|
||||
}
|
||||
// 超管不做限制
|
||||
if (SecurityTenantUtils.isSuperAdmin()) {
|
||||
return DO_NOTHING;
|
||||
}
|
||||
|
||||
// 1) 解析租户锚点:优先读取请求覆盖,其次默认租户
|
||||
String anchorTenantId = TenantQueryOverrideContext.getTenantId();
|
||||
if (!StringUtils.hasText(anchorTenantId)) {
|
||||
anchorTenantId = SecurityTenantUtils.getCurrentTenantId();
|
||||
}
|
||||
if (!StringUtils.hasText(anchorTenantId)) {
|
||||
return DO_NOTHING;
|
||||
}
|
||||
|
||||
// 2) APP 用户仅限自身租户(不跨租户)
|
||||
LoginAppUser user = SecurityTenantUtils.getCurrentUser();
|
||||
if (user != null && "APP".equals(SecurityTenantUtils.getUserType(user))) {
|
||||
return String.format("%s = '%s'", columnName, anchorTenantId);
|
||||
}
|
||||
|
||||
// 3) 管理端:查询锚点租户及其子租户
|
||||
List<String> tenantIds = null;
|
||||
try {
|
||||
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
|
||||
if (tenantService != null) {
|
||||
tenantIds = tenantService.getAllSubTenantIds(anchorTenantId);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
if (CollectionUtils.isEmpty(tenantIds)) {
|
||||
tenantIds = Arrays.asList(anchorTenantId);
|
||||
}
|
||||
|
||||
String inValues = tenantIds.stream()
|
||||
.map(id -> String.format("'%s'", id))
|
||||
.collect(Collectors.joining(","));
|
||||
return String.format("%s IN (%s)", columnName, inValues);
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,35 @@ public class LoginAppUser extends User implements OAuth2AuthenticatedPrincipal {
|
||||
|
||||
private final Map<String, Object> attributes = new HashMap<>();
|
||||
|
||||
/**
|
||||
* 用户所属租户ID(对应SysUser.company)
|
||||
*/
|
||||
private String company;
|
||||
|
||||
/**
|
||||
* 当前查询的租户ID(用户可切换)
|
||||
*/
|
||||
private String currentTenantId;
|
||||
|
||||
/**
|
||||
* 用户可访问的所有租户ID列表(包含子租户)
|
||||
*/
|
||||
private List<String> accessibleTenantIds;
|
||||
|
||||
/**
|
||||
* 是否允许切换租户(管理员权限)
|
||||
*/
|
||||
private boolean canSwitchTenant;
|
||||
|
||||
public LoginAppUser() {
|
||||
super(" ", "", true, true, true, true, new HashSet<>());
|
||||
this.id = null;
|
||||
this.mobile = null;
|
||||
this.permissions = new HashSet<>(0);
|
||||
this.company = null;
|
||||
this.currentTenantId = null;
|
||||
this.accessibleTenantIds = new ArrayList<>();
|
||||
this.canSwitchTenant = false;
|
||||
}
|
||||
|
||||
public LoginAppUser(Long id, String username, Collection<? extends GrantedAuthority> authorities) {
|
||||
@@ -44,6 +68,10 @@ public class LoginAppUser extends User implements OAuth2AuthenticatedPrincipal {
|
||||
this.id = id;
|
||||
this.mobile = null;
|
||||
this.permissions = new HashSet<>(0);
|
||||
this.company = null;
|
||||
this.currentTenantId = null;
|
||||
this.accessibleTenantIds = new ArrayList<>();
|
||||
this.canSwitchTenant = false;
|
||||
}
|
||||
|
||||
public LoginAppUser(Long id, String username, String password, String mobile, Collection<String> permissions, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
|
||||
@@ -52,6 +80,10 @@ public class LoginAppUser extends User implements OAuth2AuthenticatedPrincipal {
|
||||
this.id = id;
|
||||
this.mobile = mobile;
|
||||
this.permissions = Optional.ofNullable(permissions).orElse(new HashSet<>(0));
|
||||
this.company = null;
|
||||
this.currentTenantId = null;
|
||||
this.accessibleTenantIds = new ArrayList<>();
|
||||
this.canSwitchTenant = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -63,4 +95,38 @@ public class LoginAppUser extends User implements OAuth2AuthenticatedPrincipal {
|
||||
public String getName() {
|
||||
return this.getUsername();
|
||||
}
|
||||
|
||||
// === 租户相关字段的getter和setter方法 ===
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = company;
|
||||
}
|
||||
|
||||
public String getCurrentTenantId() {
|
||||
return currentTenantId;
|
||||
}
|
||||
|
||||
public void setCurrentTenantId(String currentTenantId) {
|
||||
this.currentTenantId = currentTenantId;
|
||||
}
|
||||
|
||||
public List<String> getAccessibleTenantIds() {
|
||||
return accessibleTenantIds;
|
||||
}
|
||||
|
||||
public void setAccessibleTenantIds(List<String> accessibleTenantIds) {
|
||||
this.accessibleTenantIds = accessibleTenantIds;
|
||||
}
|
||||
|
||||
public boolean isCanSwitchTenant() {
|
||||
return canSwitchTenant;
|
||||
}
|
||||
|
||||
public void setCanSwitchTenant(boolean canSwitchTenant) {
|
||||
this.canSwitchTenant = canSwitchTenant;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ public class SysUser extends SuperEntity {
|
||||
private String openId;
|
||||
private String unionId;
|
||||
private Long creatorId;
|
||||
private String company;
|
||||
@TableLogic
|
||||
private boolean isDel;
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 租户实体
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("sys_tenant")
|
||||
public class Tenant extends SuperEntity {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 租户ID(对应现有company字段)
|
||||
*/
|
||||
private String tenantId;
|
||||
|
||||
/**
|
||||
* 租户名称
|
||||
*/
|
||||
private String tenantName;
|
||||
|
||||
/**
|
||||
* 父租户ID
|
||||
*/
|
||||
private String parentTenantId;
|
||||
|
||||
/**
|
||||
* 租户层级(1=根租户)
|
||||
*/
|
||||
private Integer tenantLevel;
|
||||
|
||||
/**
|
||||
* 租户路径(/root/child/)
|
||||
*/
|
||||
private String tenantPath;
|
||||
|
||||
/**
|
||||
* 租户类型(GROUP/COMPANY/DEPARTMENT/PLATFORM)
|
||||
*/
|
||||
private String tenantType;
|
||||
|
||||
/**
|
||||
* 租户编码
|
||||
*/
|
||||
private String tenantCode;
|
||||
|
||||
/**
|
||||
* 负责人
|
||||
*/
|
||||
private String contactPerson;
|
||||
|
||||
/**
|
||||
* 联系电话
|
||||
*/
|
||||
private String contactPhone;
|
||||
|
||||
/**
|
||||
* 地址
|
||||
*/
|
||||
private String address;
|
||||
|
||||
/**
|
||||
* 租户描述
|
||||
*/
|
||||
private String description;
|
||||
|
||||
/**
|
||||
* 状态(0:停用,1:启用)
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
private Long creatorId;
|
||||
|
||||
/**
|
||||
* 是否有子租户(查询时使用,非数据库字段)
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private Boolean hasChildren;
|
||||
|
||||
/**
|
||||
* 子租户数量(查询时使用,非数据库字段)
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private Integer childrenCount;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 租户信息VO
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TenantInfo {
|
||||
|
||||
/**
|
||||
* 租户ID
|
||||
*/
|
||||
private String tenantId;
|
||||
|
||||
/**
|
||||
* 租户名称
|
||||
*/
|
||||
private String tenantName;
|
||||
|
||||
/**
|
||||
* 父租户ID
|
||||
*/
|
||||
private String parentTenantId;
|
||||
|
||||
/**
|
||||
* 父租户名称
|
||||
*/
|
||||
private String parentTenantName;
|
||||
|
||||
/**
|
||||
* 租户层级
|
||||
*/
|
||||
private Integer tenantLevel;
|
||||
|
||||
/**
|
||||
* 租户路径
|
||||
*/
|
||||
private String tenantPath;
|
||||
|
||||
/**
|
||||
* 租户类型
|
||||
*/
|
||||
private String tenantType;
|
||||
|
||||
/**
|
||||
* 租户编码
|
||||
*/
|
||||
private String tenantCode;
|
||||
|
||||
/**
|
||||
* 负责人
|
||||
*/
|
||||
private String contactPerson;
|
||||
|
||||
/**
|
||||
* 联系电话
|
||||
*/
|
||||
private String contactPhone;
|
||||
|
||||
/**
|
||||
* 地址
|
||||
*/
|
||||
private String address;
|
||||
|
||||
/**
|
||||
* 描述
|
||||
*/
|
||||
private String description;
|
||||
|
||||
/**
|
||||
* 状态(0:停用,1:启用)
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 状态描述
|
||||
*/
|
||||
private String statusText;
|
||||
|
||||
/**
|
||||
* 是否有子租户
|
||||
*/
|
||||
private Boolean hasChildren;
|
||||
|
||||
/**
|
||||
* 子租户数量
|
||||
*/
|
||||
private Integer childrenCount;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
private Long creatorId;
|
||||
|
||||
/**
|
||||
* 创建人名称
|
||||
*/
|
||||
private String creatorName;
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户树形节点VO
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class TenantTreeNode {
|
||||
|
||||
/**
|
||||
* 租户ID
|
||||
*/
|
||||
private String tenantId;
|
||||
|
||||
/**
|
||||
* 租户名称
|
||||
*/
|
||||
private String tenantName;
|
||||
|
||||
/**
|
||||
* 父租户ID
|
||||
*/
|
||||
private String parentTenantId;
|
||||
|
||||
/**
|
||||
* 租户类型
|
||||
*/
|
||||
private String tenantType;
|
||||
|
||||
/**
|
||||
* 租户层级
|
||||
*/
|
||||
private Integer tenantLevel;
|
||||
|
||||
/**
|
||||
* 状态
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 是否启用
|
||||
*/
|
||||
private Boolean enabled;
|
||||
|
||||
/**
|
||||
* 租户描述
|
||||
*/
|
||||
private String description;
|
||||
|
||||
/**
|
||||
* 子节点列表
|
||||
*/
|
||||
private List<TenantTreeNode> children;
|
||||
|
||||
/**
|
||||
* 是否有子节点
|
||||
*/
|
||||
private Boolean hasChildren;
|
||||
|
||||
/**
|
||||
* 子节点数量
|
||||
*/
|
||||
private Integer childrenCount;
|
||||
|
||||
/**
|
||||
* 扩展属性(可选)
|
||||
*/
|
||||
private Object extra;
|
||||
}
|
||||
+1
-1
@@ -25,7 +25,7 @@ public class DataScopeProperties {
|
||||
/**
|
||||
* 是否开启权限控制
|
||||
*/
|
||||
private Boolean enabled = Boolean.FALSE;
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
/**
|
||||
* 是否开启打印sql的修改情况
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.central.common.service;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.Tenant;
|
||||
import com.central.common.model.TenantInfo;
|
||||
import com.central.common.model.TenantTreeNode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户层级管理服务接口
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
public interface ITenantHierarchyService {
|
||||
|
||||
/**
|
||||
* 获取租户的所有子租户ID(包含自身)
|
||||
*
|
||||
* @param parentTenantId 父租户ID
|
||||
* @return 子租户ID列表
|
||||
*/
|
||||
List<String> getAllSubTenantIds(String parentTenantId);
|
||||
|
||||
/**
|
||||
* 构建租户树结构
|
||||
*
|
||||
* @param tenantIds 租户ID列表
|
||||
* @return 租户树节点列表
|
||||
*/
|
||||
List<TenantTreeNode> buildTenantTree(List<String> tenantIds);
|
||||
|
||||
/**
|
||||
* 获取租户详细信息
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 租户信息
|
||||
*/
|
||||
TenantInfo getTenantInfo(String tenantId);
|
||||
|
||||
/**
|
||||
* 创建子租户
|
||||
*
|
||||
* @param tenant 租户信息
|
||||
* @return 创建结果
|
||||
*/
|
||||
Result<Tenant> createTenant(Tenant tenant);
|
||||
|
||||
/**
|
||||
* 更新租户信息
|
||||
*
|
||||
* @param tenant 租户信息
|
||||
* @return 更新结果
|
||||
*/
|
||||
Result<Tenant> updateTenant(Tenant tenant);
|
||||
|
||||
/**
|
||||
* 删除租户(软删除)
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 删除结果
|
||||
*/
|
||||
Result<Boolean> deleteTenant(String tenantId);
|
||||
|
||||
/**
|
||||
* 获取租户列表(分页)
|
||||
*
|
||||
* @param parentTenantId 父租户ID(可选)
|
||||
* @param tenantName 租户名称(模糊查询,可选)
|
||||
* @param status 状态(可选)
|
||||
* @param page 页码
|
||||
* @param size 页大小
|
||||
* @return 租户列表
|
||||
*/
|
||||
Result<List<TenantInfo>> getTenantList(String parentTenantId, String tenantName, Integer status, Integer page, Integer size);
|
||||
|
||||
/**
|
||||
* 检查租户ID是否存在
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 是否存在
|
||||
*/
|
||||
boolean existsByTenantId(String tenantId);
|
||||
|
||||
/**
|
||||
* 验证租户关系是否合法(防止循环引用)
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @param parentTenantId 父租户ID
|
||||
* @return 是否合法
|
||||
*/
|
||||
boolean validateTenantRelation(String tenantId, String parentTenantId);
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package com.central.common.service;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户租户信息初始化器
|
||||
* 在用户登录时初始化租户相关信息
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class UserTenantInitializer {
|
||||
|
||||
@Autowired(required = false)
|
||||
private ITenantHierarchyService tenantHierarchyService;
|
||||
|
||||
/**
|
||||
* 初始化用户租户信息
|
||||
* 在用户登录成功后调用此方法
|
||||
*
|
||||
* @param user 登录用户
|
||||
*/
|
||||
public void initializeUserTenantInfo(LoginAppUser user) {
|
||||
if (user == null) {
|
||||
log.warn("用户对象为空,跳过租户信息初始化");
|
||||
return;
|
||||
}
|
||||
|
||||
String userTenantId = getUserTenantId(user);
|
||||
if (!StringUtils.hasText(userTenantId)) {
|
||||
log.warn("用户 {} 未分配租户", user.getUsername());
|
||||
setDefaultTenantInfo(user);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 设置用户所属租户
|
||||
user.setCompany(userTenantId);
|
||||
|
||||
// 判断用户类型和权限
|
||||
boolean canSwitchTenant = isManagementUser(user);
|
||||
user.setCanSwitchTenant(canSwitchTenant);
|
||||
|
||||
// 设置可访问租户列表
|
||||
List<String> accessibleTenants = getAccessibleTenants(user, userTenantId, canSwitchTenant);
|
||||
user.setAccessibleTenantIds(accessibleTenants);
|
||||
|
||||
// 设置默认当前租户
|
||||
user.setCurrentTenantId(userTenantId);
|
||||
|
||||
log.info("用户 {} 租户信息初始化完成: company={}, canSwitch={}, accessibleCount={}",
|
||||
user.getUsername(), userTenantId, canSwitchTenant,
|
||||
accessibleTenants != null ? accessibleTenants.size() : 0);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("初始化用户租户信息失败: userId={}, username={}, error={}",
|
||||
user.getId(), user.getUsername(), e.getMessage());
|
||||
// 降级处理:设置基本信息
|
||||
setDefaultTenantInfo(user, userTenantId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户租户ID
|
||||
* 优先从用户属性中获取,如果没有则从公司字段获取
|
||||
*/
|
||||
private String getUserTenantId(LoginAppUser user) {
|
||||
// 优先从属性中获取
|
||||
Object companyFromAttributes = user.getAttributes().get("company");
|
||||
if (companyFromAttributes != null && StringUtils.hasText(companyFromAttributes.toString())) {
|
||||
return companyFromAttributes.toString();
|
||||
}
|
||||
|
||||
// 从company字段获取
|
||||
if (StringUtils.hasText(user.getCompany())) {
|
||||
return user.getCompany();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为管理用户
|
||||
* 管理用户可以切换租户,普通用户只能访问自己的租户
|
||||
*/
|
||||
private boolean isManagementUser(LoginAppUser user) {
|
||||
// 根据用户类型判断:BACKEND用户为管理员,APP用户为C端用户
|
||||
String userType = getUserType(user);
|
||||
return "BACKEND".equals(userType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户类型
|
||||
*/
|
||||
private String getUserType(LoginAppUser user) {
|
||||
// 优先从属性中获取
|
||||
Object typeFromAttributes = user.getAttributes().get("type");
|
||||
if (typeFromAttributes != null) {
|
||||
return typeFromAttributes.toString();
|
||||
}
|
||||
|
||||
// 默认返回BACKEND(兼容处理)
|
||||
return "BACKEND";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户可访问的租户列表
|
||||
*/
|
||||
private List<String> getAccessibleTenants(LoginAppUser user, String userTenantId, boolean canSwitchTenant) {
|
||||
if (!canSwitchTenant) {
|
||||
// 普通用户只能访问自己的租户
|
||||
return Arrays.asList(userTenantId);
|
||||
}
|
||||
|
||||
// 管理员用户可以访问当前租户及其所有子租户
|
||||
if (tenantHierarchyService != null) {
|
||||
try {
|
||||
List<String> subTenants = tenantHierarchyService.getAllSubTenantIds(userTenantId);
|
||||
if (subTenants != null && !subTenants.isEmpty()) {
|
||||
return subTenants;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("获取子租户列表失败: tenantId={}, error={}", userTenantId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 降级处理:返回用户自己的租户
|
||||
return Arrays.asList(userTenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置默认租户信息(无租户时的处理)
|
||||
*/
|
||||
private void setDefaultTenantInfo(LoginAppUser user) {
|
||||
setDefaultTenantInfo(user, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置默认租户信息(降级处理)
|
||||
*/
|
||||
private void setDefaultTenantInfo(LoginAppUser user, String tenantId) {
|
||||
if (StringUtils.hasText(tenantId)) {
|
||||
user.setCompany(tenantId);
|
||||
user.setCurrentTenantId(tenantId);
|
||||
user.setAccessibleTenantIds(Arrays.asList(tenantId));
|
||||
} else {
|
||||
user.setCompany(null);
|
||||
user.setCurrentTenantId(null);
|
||||
user.setAccessibleTenantIds(Arrays.asList());
|
||||
}
|
||||
user.setCanSwitchTenant(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证用户租户信息是否有效
|
||||
*/
|
||||
public boolean validateUserTenantInfo(LoginAppUser user) {
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查基本字段
|
||||
if (!StringUtils.hasText(user.getCurrentTenantId())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查可访问租户列表
|
||||
List<String> accessibleTenants = user.getAccessibleTenantIds();
|
||||
if (accessibleTenants == null || accessibleTenants.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查当前租户是否在可访问列表中
|
||||
return accessibleTenants.contains(user.getCurrentTenantId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新用户租户信息
|
||||
* 可在租户信息变更后调用
|
||||
*/
|
||||
public void refreshUserTenantInfo(LoginAppUser user) {
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("刷新用户 {} 的租户信息", user.getUsername());
|
||||
initializeUserTenantInfo(user);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.central.common.service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 用户当前查询租户选择持久化服务
|
||||
* 说明:不使用 x-tenant-header 时,用于在后端保存“用户当前选择的查询租户ID”,
|
||||
* 供每个请求基于 Authorization 恢复上下文。
|
||||
*/
|
||||
public interface UserTenantSelectionService {
|
||||
/**
|
||||
* 设置用户当前查询租户ID
|
||||
* @param userId 用户ID
|
||||
* @param tenantId 当前选择的租户ID
|
||||
*/
|
||||
void setCurrentTenant(Long userId, String tenantId);
|
||||
|
||||
/**
|
||||
* 获取用户当前查询租户ID
|
||||
* @param userId 用户ID
|
||||
* @return 可选的租户ID(如果未设置则为空)
|
||||
*/
|
||||
Optional<String> getCurrentTenant(Long userId);
|
||||
|
||||
/**
|
||||
* 清除用户当前查询租户ID
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void clearCurrentTenant(Long userId);
|
||||
}
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.central.common.service.impl;
|
||||
|
||||
import com.central.common.service.UserTenantSelectionService;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 基于内存的用户当前查询租户选择存储(兜底实现)
|
||||
* 生产环境建议使用 Redis 实现,确保多实例一致性。
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnMissingBean(UserTenantSelectionService.class)
|
||||
public class InMemoryUserTenantSelectionService implements UserTenantSelectionService {
|
||||
|
||||
private final ConcurrentHashMap<Long, String> store = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void setCurrentTenant(Long userId, String tenantId) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
if (tenantId == null) {
|
||||
store.remove(userId);
|
||||
} else {
|
||||
store.put(userId, tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> getCurrentTenant(Long userId) {
|
||||
if (userId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(store.get(userId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearCurrentTenant(Long userId) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
store.remove(userId);
|
||||
}
|
||||
}
|
||||
|
||||
+50
-2
@@ -8,6 +8,7 @@ import com.central.common.feign.UserService;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.model.SysRole;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.common.service.UserTenantInitializer;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -131,16 +132,34 @@ public class LoginUserUtils {
|
||||
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
|
||||
}
|
||||
|
||||
return new LoginAppUser(sysUser.getId()
|
||||
LoginAppUser user = new LoginAppUser(sysUser.getId()
|
||||
, sysUser.getUsername(), sysUser.getPassword()
|
||||
, sysUser.getMobile(), sysUser.getPermissions()
|
||||
, sysUser.getEnabled(), true, true, true
|
||||
, authorities);
|
||||
|
||||
// 设置用户基本属性到attributes中,供租户初始化使用
|
||||
// 兼容:SysUser 可能无 company 字段,这里通过反射读取,存在则写入
|
||||
try {
|
||||
Object companyVal = sysUser.getClass().getMethod("getCompany").invoke(sysUser);
|
||||
if (companyVal != null) {
|
||||
user.setCompany(companyVal.toString());
|
||||
user.getAttributes().put("company", companyVal.toString());
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
// 无 company 字段时忽略
|
||||
}
|
||||
user.getAttributes().put("type", sysUser.getType());
|
||||
|
||||
// 初始化租户信息
|
||||
initializeUserTenantInfo(user);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static LoginAppUser getLoginAppUser(Map<String, Object> userObj) {
|
||||
return new LoginAppUser(
|
||||
LoginAppUser user = new LoginAppUser(
|
||||
(Long)userObj.get("id"),
|
||||
(String)userObj.get("username"),
|
||||
(String)userObj.get("password"),
|
||||
@@ -149,6 +168,19 @@ public class LoginUserUtils {
|
||||
Optional.ofNullable((Boolean)userObj.get("enabled")).orElse(true),
|
||||
true, true, true,
|
||||
getGrantedAuthoritys((List<Map<String, String>>)userObj.get("authorities")));
|
||||
|
||||
// 设置用户基本属性到attributes中,供租户初始化使用
|
||||
if (userObj.get("company") != null) {
|
||||
user.getAttributes().put("company", userObj.get("company"));
|
||||
}
|
||||
if (userObj.get("type") != null) {
|
||||
user.getAttributes().put("type", userObj.get("type"));
|
||||
}
|
||||
|
||||
// 初始化租户信息
|
||||
initializeUserTenantInfo(user);
|
||||
|
||||
return user;
|
||||
}
|
||||
private static Collection<? extends GrantedAuthority> getGrantedAuthoritys(List<Map<String, String>> authorities) {
|
||||
if (authorities != null) {
|
||||
@@ -163,4 +195,20 @@ public class LoginUserUtils {
|
||||
UserService userService = SpringUtil.getBean(UserService.class);
|
||||
return userService.findByUsername(username);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化用户租户信息
|
||||
*/
|
||||
private static void initializeUserTenantInfo(LoginAppUser user) {
|
||||
try {
|
||||
UserTenantInitializer tenantInitializer = SpringUtil.getBean(UserTenantInitializer.class);
|
||||
if (tenantInitializer != null) {
|
||||
tenantInitializer.initializeUserTenantInfo(user);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 如果租户初始化器不存在或初始化失败,记录日志但不影响登录
|
||||
// 这样可以保证在租户功能未完全部署时,系统仍能正常运行
|
||||
System.err.println("租户信息初始化失败,但不影响登录: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import com.central.common.service.UserTenantSelectionService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 基于 SecurityContext 的租户解析工具类
|
||||
* 从 Authorization 中提取用户与租户信息,避免依赖 x-tenant-header。
|
||||
*/
|
||||
@Slf4j
|
||||
public class SecurityTenantUtils {
|
||||
|
||||
/**
|
||||
* 获取当前登录用户(从 SecurityContext 解析)
|
||||
*/
|
||||
public static LoginAppUser getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
|
||||
return null;
|
||||
}
|
||||
Object principal = authentication.getPrincipal();
|
||||
if (principal instanceof LoginAppUser) {
|
||||
return (LoginAppUser) principal;
|
||||
}
|
||||
if (principal instanceof Jwt) {
|
||||
// 复用已有转换逻辑
|
||||
return com.central.common.utils.LoginUserUtils.getUser(authentication);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前查询租户ID
|
||||
* 优先:用户选择的 currentTenant(持久化) -> user.currentTenantId -> user.company
|
||||
*/
|
||||
public static String getCurrentTenantId() {
|
||||
LoginAppUser user = getCurrentUser();
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
UserTenantSelectionService selectionService = SpringContextHolder.getBean(UserTenantSelectionService.class);
|
||||
Optional<String> selected = selectionService.getCurrentTenant(user.getId());
|
||||
if (selected.isPresent() && StringUtils.hasText(selected.get())) {
|
||||
return selected.get();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 忽略:无实现或容器未初始化
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(user.getCurrentTenantId())) {
|
||||
return user.getCurrentTenantId();
|
||||
}
|
||||
return user.getCompany();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前查询范围的租户ID集合(支持层级)
|
||||
* 管理员:当前租户 + 所有子租户;C端用户:仅自己租户
|
||||
*/
|
||||
public static List<String> getCurrentQueryTenantIds() {
|
||||
String currentTenant = getCurrentTenantId();
|
||||
if (!StringUtils.hasText(currentTenant)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
LoginAppUser user = getCurrentUser();
|
||||
if (user != null && "APP".equals(getUserType(user))) {
|
||||
return Arrays.asList(currentTenant);
|
||||
}
|
||||
try {
|
||||
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
|
||||
if (tenantService != null) {
|
||||
List<String> subTenants = tenantService.getAllSubTenantIds(currentTenant);
|
||||
if (subTenants != null && !subTenants.isEmpty()) {
|
||||
return subTenants;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("查询子租户失败,降级为单租户: {}", e.getMessage());
|
||||
}
|
||||
return Arrays.asList(currentTenant);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为超级管理员(依据用户名 admin/mgnt)
|
||||
*/
|
||||
public static boolean isSuperAdmin() {
|
||||
LoginAppUser user = getCurrentUser();
|
||||
return user != null && ("admin".equals(user.getUsername()) || "mgnt".equals(user.getUsername()));
|
||||
}
|
||||
|
||||
public static String getUserType(LoginAppUser user) {
|
||||
Object type = user.getAttributes().get("type");
|
||||
return type != null ? type.toString() : "BACKEND";
|
||||
}
|
||||
}
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Spring上下文工具类
|
||||
* 用于在静态方法中获取Spring Bean
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Component
|
||||
public class SpringContextHolder implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext context) throws BeansException {
|
||||
SpringContextHolder.applicationContext = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据Class获取Bean
|
||||
*/
|
||||
public static <T> T getBean(Class<T> clazz) {
|
||||
if (applicationContext == null) {
|
||||
throw new RuntimeException("ApplicationContext未初始化");
|
||||
}
|
||||
return applicationContext.getBean(clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名称获取Bean
|
||||
*/
|
||||
public static Object getBean(String beanName) {
|
||||
if (applicationContext == null) {
|
||||
throw new RuntimeException("ApplicationContext未初始化");
|
||||
}
|
||||
return applicationContext.getBean(beanName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名称和类型获取Bean
|
||||
*/
|
||||
public static <T> T getBean(String beanName, Class<T> clazz) {
|
||||
if (applicationContext == null) {
|
||||
throw new RuntimeException("ApplicationContext未初始化");
|
||||
}
|
||||
return applicationContext.getBean(beanName, clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否包含指定的Bean
|
||||
*/
|
||||
public static boolean containsBean(String beanName) {
|
||||
if (applicationContext == null) {
|
||||
return false;
|
||||
}
|
||||
return applicationContext.containsBean(beanName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查ApplicationContext是否已初始化
|
||||
*/
|
||||
public static boolean isInitialized() {
|
||||
return applicationContext != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取ApplicationContext
|
||||
*/
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -4,13 +4,13 @@ import com.central.common.model.Result;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.server.reactive.ServerHttpResponse;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
@@ -47,10 +47,12 @@ public class WebfluxResponseUtil {
|
||||
response.getHeaders().setAccessControlAllowOrigin("*");
|
||||
response.setStatusCode(HttpStatus.valueOf(httpStatus));
|
||||
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
|
||||
response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8");
|
||||
DataBufferFactory dataBufferFactory = response.bufferFactory();
|
||||
DataBuffer buffer = dataBufferFactory.wrap(JsonUtil.toJSONString(result).getBytes(Charset.defaultCharset()));
|
||||
DataBuffer buffer = dataBufferFactory.wrap(JsonUtil.toJSONString(result).getBytes(StandardCharsets.UTF_8));
|
||||
return response.writeWith(Mono.just(buffer)).doOnError((error) -> {
|
||||
DataBufferUtils.release(buffer);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-20
@@ -2,7 +2,6 @@ package com.central.common.filter;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import jakarta.servlet.Filter;
|
||||
import jakarta.servlet.FilterChain;
|
||||
@@ -16,10 +15,9 @@ import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 租户过滤器
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/9/15
|
||||
* 租户过滤器(兼容保留)
|
||||
* 不再依赖 x-tenant-header,也不做默认 webApp 兜底。
|
||||
* 最终的租户上下文以 Authorization 中的用户信息为准。
|
||||
*/
|
||||
@Slf4j
|
||||
@ConditionalOnClass(Filter.class)
|
||||
@@ -28,28 +26,22 @@ public class TenantFilter extends OncePerRequestFilter {
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws IOException, ServletException {
|
||||
try {
|
||||
//优先获取请求参数中的tenantId值
|
||||
// 仅在显式传参时设置(向下兼容)。未传参则不设置,交由授权信息解析。
|
||||
String tenantId = request.getParameter(CommonConstant.TENANT_ID_PARAM);
|
||||
if (StrUtil.isEmpty(tenantId)) {
|
||||
tenantId = request.getHeader(SecurityConstants.TENANT_HEADER);
|
||||
}
|
||||
|
||||
log.debug("请求URL: {}, 租户ID: {}", request.getRequestURI(), tenantId);
|
||||
|
||||
//保存租户id
|
||||
if (StrUtil.isNotEmpty(tenantId) && null != tenantId) {
|
||||
if (StrUtil.isNotEmpty(tenantId)) {
|
||||
TenantContextHolder.setTenant(tenantId);
|
||||
log.debug("设置租户上下文: {}", tenantId);
|
||||
log.debug("请求URL: {}, 通过参数设置租户ID: {}", request.getRequestURI(), tenantId);
|
||||
} else {
|
||||
TenantContextHolder.setTenant("webApp");
|
||||
log.debug("未找到租户ID,使用默认租户");
|
||||
log.debug("请求URL: {}, 未从参数设置租户ID,交由授权解析", request.getRequestURI());
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
String currentTenant = TenantContextHolder.getTenant();
|
||||
log.debug("清理租户上下文: {}", currentTenant);
|
||||
TenantContextHolder.clear();
|
||||
if (StrUtil.isNotEmpty(currentTenant)) {
|
||||
log.debug("清理租户上下文: {}", currentTenant);
|
||||
TenantContextHolder.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.central.common.filter;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.common.context.TenantQueryOverrideContext;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import jakarta.servlet.Filter;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点。
|
||||
* 规则:
|
||||
* - APP 用户忽略该参数(记录warn)。
|
||||
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn。
|
||||
*/
|
||||
@Slf4j
|
||||
@ConditionalOnClass(Filter.class)
|
||||
@Order
|
||||
public class TenantQueryOverrideFilter extends OncePerRequestFilter {
|
||||
private static final String PARAM_TENANT_ID = "tenantId";
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws IOException, ServletException {
|
||||
try {
|
||||
String overrideTenant = request.getParameter(PARAM_TENANT_ID);
|
||||
if (StrUtil.isNotBlank(overrideTenant)) {
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
if (user == null) {
|
||||
// 未登录,忽略参数
|
||||
log.debug("忽略tenantId参数(未登录): {}", overrideTenant);
|
||||
} else {
|
||||
String userType = (String) user.getAttributes().getOrDefault("type", "BACKEND");
|
||||
if ("APP".equals(userType)) {
|
||||
log.warn("APP用户不支持覆盖tenantId, user={}, tenantId={}", user.getUsername(), overrideTenant);
|
||||
} else {
|
||||
List<String> accessible = user.getAccessibleTenantIds();
|
||||
if (accessible != null && accessible.contains(overrideTenant)) {
|
||||
TenantQueryOverrideContext.setTenantId(overrideTenant);
|
||||
log.debug("本次请求使用覆盖租户ID: {}", overrideTenant);
|
||||
} else {
|
||||
log.warn("覆盖tenantId不在可访问范围, user={}, tenantId={}", user.getUsername(), overrideTenant);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
TenantQueryOverrideContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -1,2 +1,4 @@
|
||||
com.central.common.filter.TenantFilter
|
||||
com.central.common.filter.LoginUserFilter
|
||||
com.central.common.filter.LoginUserFilter
|
||||
com.central.common.filter.TenantQueryOverrideFilter
|
||||
|
||||
|
||||
+8
-4
@@ -8,6 +8,8 @@ import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerIntercept
|
||||
import com.central.common.datascope.mp.interceptor.DataScopeInnerInterceptor;
|
||||
import com.central.common.datascope.mp.interceptor.EnableQuerySqlLogInnerInterceptor;
|
||||
import com.central.common.datascope.mp.sql.handler.CreatorDataScopeSqlHandler;
|
||||
import com.central.common.datascope.mp.sql.handler.TenantDataScopeSqlHandler;
|
||||
import com.central.common.datascope.mp.sql.handler.CombinedSqlHandler;
|
||||
import com.central.common.datascope.mp.sql.handler.SqlHandler;
|
||||
import com.central.common.properties.DataScopeProperties;
|
||||
import com.central.common.properties.TenantProperties;
|
||||
@@ -45,7 +47,8 @@ public class MybatisPlusAutoConfigure {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public SqlHandler sqlHandler(){
|
||||
return new CreatorDataScopeSqlHandler();
|
||||
// 同时支持创建人维度与租户层级维度的数据权限(AND 组合)
|
||||
return new CombinedSqlHandler(new CreatorDataScopeSqlHandler(), new TenantDataScopeSqlHandler());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,13 +58,14 @@ public class MybatisPlusAutoConfigure {
|
||||
public MybatisPlusInterceptor paginationInterceptor(SqlHandler sqlHandler) {
|
||||
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
|
||||
boolean enableTenant = tenantProperties.getEnable();
|
||||
//是否开启多租户隔离
|
||||
if (enableTenant) {
|
||||
boolean enableHierarchy = Boolean.TRUE.equals(dataScopeProperties.getEnabled());
|
||||
// 统一层级过滤:当启用层级数据范围时,不再叠加等值租户过滤,避免 tenant_id = ? 与 IN (...) 冲突
|
||||
if(!enableHierarchy && enableTenant) {
|
||||
CustomTenantInterceptor tenantInterceptor = new CustomTenantInterceptor(
|
||||
tenantLineHandler, tenantProperties.getIgnoreSqls(),tenantProperties.getNoIgnoreSqls());
|
||||
mpInterceptor.addInnerInterceptor(tenantInterceptor);
|
||||
}
|
||||
if(dataScopeProperties.getEnabled()){
|
||||
if(enableHierarchy){
|
||||
DataScopeInnerInterceptor dataScopeInnerInterceptor = new DataScopeInnerInterceptor(dataScopeProperties, sqlHandler);
|
||||
mpInterceptor.addInnerInterceptor(Boolean.TRUE.equals(dataScopeProperties.getEnabledSqlDebug())
|
||||
? new EnableQuerySqlLogInnerInterceptor(dataScopeInnerInterceptor): dataScopeInnerInterceptor);
|
||||
|
||||
+11
-18
@@ -2,6 +2,7 @@ package com.central.db.interceptor;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
||||
import com.central.common.utils.SecurityTenantUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.executor.Executor;
|
||||
import org.apache.ibatis.mapping.BoundSql;
|
||||
@@ -13,14 +14,8 @@ import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* MyBatis-plus租户拦截器
|
||||
*
|
||||
* @author zlt
|
||||
* @version 1.0
|
||||
* @date 2022/5/6
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
* MyBatis-plus租户拦截器(等值过滤)
|
||||
* 不使用 x-tenant-header,通过 Authorization 中的用户信息解析当前租户。
|
||||
*/
|
||||
@Slf4j
|
||||
public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
||||
@@ -39,18 +34,18 @@ public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
||||
String msId = ms.getId();
|
||||
log.debug("租户拦截器处理SQL: {}", msId);
|
||||
|
||||
// 获取当前租户
|
||||
String tenant = com.central.common.context.TenantContextHolder.getTenant();
|
||||
// 基于 Authorization 解析当前租户
|
||||
String currentTenantId = SecurityTenantUtils.getCurrentTenantId();
|
||||
|
||||
// webApp 租户或超级管理员直接跳过租户过滤
|
||||
if ("webApp".equals(tenant) || isSuperAdmin()) {
|
||||
if ("webApp".equals(currentTenantId) || SecurityTenantUtils.isSuperAdmin()) {
|
||||
log.debug("webApp租户或超级管理员,SQL {} 跳过租户过滤", msId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 租户为null时跳过租户过滤
|
||||
log.debug("租户ID: {}", tenant);
|
||||
if (null == tenant ) {
|
||||
log.debug("租户ID: {}", currentTenantId);
|
||||
if (null == currentTenantId) {
|
||||
log.debug("租户为null,SQL {} 跳过租户过滤", msId);
|
||||
return;
|
||||
}
|
||||
@@ -61,7 +56,7 @@ public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
||||
return;
|
||||
}
|
||||
|
||||
// 所有其他SQL都执行租户过滤处理
|
||||
// 其他SQL执行租户过滤
|
||||
log.debug("SQL {} 执行租户过滤", msId);
|
||||
super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
|
||||
}
|
||||
@@ -74,8 +69,6 @@ public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
||||
return noIgnoreSqls.stream().anyMatch((e) -> e.equalsIgnoreCase(msId));
|
||||
}
|
||||
|
||||
private boolean isSuperAdmin() {
|
||||
com.central.common.model.LoginAppUser user = com.central.common.context.LoginUserContextHolder.getUser();
|
||||
return user != null && (user.getUsername().equals("admin") || user.getUsername().equals("mgnt"));
|
||||
}
|
||||
private boolean isSuperAdmin() { return SecurityTenantUtils.isSuperAdmin(); }
|
||||
}
|
||||
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.central.common.redis.tenant;
|
||||
|
||||
import com.central.common.service.UserTenantSelectionService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 基于 Redis 的用户当前查询租户选择存储
|
||||
*/
|
||||
@Component
|
||||
@Primary
|
||||
@ConditionalOnClass(StringRedisTemplate.class)
|
||||
public class RedisUserTenantSelectionService implements UserTenantSelectionService {
|
||||
|
||||
private static final String KEY_PREFIX = "tenant:selection:"; // tenant:selection:{userId}
|
||||
private static final Duration TTL = Duration.ofDays(7);
|
||||
|
||||
@Autowired(required = false)
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
@Override
|
||||
public void setCurrentTenant(Long userId, String tenantId) {
|
||||
if (stringRedisTemplate == null || userId == null) {
|
||||
return;
|
||||
}
|
||||
String key = KEY_PREFIX + userId;
|
||||
if (tenantId == null) {
|
||||
stringRedisTemplate.delete(key);
|
||||
} else {
|
||||
stringRedisTemplate.opsForValue().set(key, tenantId, TTL);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> getCurrentTenant(Long userId) {
|
||||
if (stringRedisTemplate == null || userId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String val = stringRedisTemplate.opsForValue().get(KEY_PREFIX + userId);
|
||||
return Optional.ofNullable(val);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearCurrentTenant(Long userId) {
|
||||
if (stringRedisTemplate == null || userId == null) {
|
||||
return;
|
||||
}
|
||||
stringRedisTemplate.delete(KEY_PREFIX + userId);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user