65 lines
3.1 KiB
Java
65 lines
3.1 KiB
Java
package com.guo.learningprogresstracker.config;
|
|
|
|
import cn.dev33.satoken.stp.StpUtil;
|
|
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
|
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
|
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
|
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
|
import com.guo.learningprogresstracker.common.TenantContext;
|
|
import java.util.Arrays;
|
|
import java.util.List;
|
|
import net.sf.jsqlparser.expression.Expression;
|
|
import net.sf.jsqlparser.expression.StringValue;
|
|
import org.springframework.context.annotation.Bean;
|
|
import org.springframework.context.annotation.Configuration;
|
|
|
|
/**
|
|
* MyBatis-Plus 多租户配置
|
|
* 利用 TenantLineInnerInterceptor 自动在 SELECT/UPDATE/DELETE 语句中
|
|
* 注入 WHERE created_by = #{当前登录用户},实现行级数据隔离。
|
|
*/
|
|
@Configuration
|
|
public class MybatisPlusConfig {
|
|
|
|
/**
|
|
* 不需要租户过滤的表(仅排除不含 created_by 或不该按 created_by 过滤的表)
|
|
*
|
|
* <p>{@code ai_usage_records} 是系统级表:记录由 lpt-ai 通过内部接口上报,请求里没有登录用户,
|
|
* created_by 只是审计列;用量又是运维口径——管理员要看的是**全部**调用。
|
|
* 若按 created_by 过滤,每个人只能看到自己触发的那几次调用,面板等于永远空的。</p>
|
|
*/
|
|
private static final List<String> EXCLUDE_TABLES = Arrays.asList(
|
|
"user", "flyway_schema_history", "databasechangelog", "databasechangeloglock", "ai_usage_records");
|
|
|
|
@Bean
|
|
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
|
// 顺序很重要:MyBatis-Plus 要求「多租户 → 分页」。
|
|
// 分页的 count 语句是从「当前已处理的 SQL」派生的;若分页先注册,
|
|
// count 会在租户条件追加之前就派生出来,导致 total 把其他用户的行也算进去
|
|
// (records 仍然正确,只有分页总数跨租户,极难发现)。
|
|
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
|
|
@Override
|
|
public Expression getTenantId() {
|
|
// 后台执行线程(AI 任务、定时收敛)通过 TenantContext 显式声明身份;
|
|
// 请求线程没有设置,仍走 StpUtil,行为完全不变
|
|
TenantContext.Identity identity = TenantContext.get();
|
|
return new StringValue(identity != null ? identity.loginId() : StpUtil.getLoginIdAsString());
|
|
}
|
|
|
|
@Override
|
|
public String getTenantIdColumn() {
|
|
return "created_by";
|
|
}
|
|
|
|
@Override
|
|
public boolean ignoreTable(String tableName) {
|
|
return EXCLUDE_TABLES.contains(tableName.toLowerCase());
|
|
}
|
|
}));
|
|
// 分页拦截器必须注册,否则 selectPage 不会生成 LIMIT / COUNT
|
|
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
|
|
return interceptor;
|
|
}
|
|
}
|