feat(react-web-next): 新增.editorconfig和.prettierrc配置文件,添加public/.gitkeep占位文件
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Read(/F:\\project\\go-fly-platform-services\\zlt-doc/**)",
|
||||
"Bash(mvn compile:*)",
|
||||
"Bash(java:*)",
|
||||
"Bash(mvn spring-boot:run:*)",
|
||||
"Bash(mvn clean:*)",
|
||||
"Bash(npm install:*)",
|
||||
"Bash(lsof:*)",
|
||||
"Bash(findstr:*)",
|
||||
"Bash(npm run start:*)",
|
||||
"Bash(npm start)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
# 仓库指南(Repository Guidelines)
|
||||
|
||||
## 语言与注释规范(Agent 专用)
|
||||
- 所有交互回答必须使用中文(简体),包括解释、建议与错误信息。
|
||||
- 代码片段中的注释、日志消息、文档内容与示例说明均应为中文;编程语言关键字与三方 API 标识符保持原文。
|
||||
- 提交信息(commit)、合并请求(PR)描述与 Issue 标题/内容默认使用中文;涉及外部专有名词可保留英文缩写。
|
||||
|
||||
## 权限与执行策略
|
||||
- 默认权限:Codex 在本仓库内可直接读取与编辑文件,无需额外审批。
|
||||
- 命令执行:在具备网络访问权限时,可直接执行包含网络的命令(如依赖下载、API 请求、构建/测试脚本)。
|
||||
- 安全边界:遵循最小影响原则,避免破坏性操作(如强制删除、重置历史、批量改名)。如确需此类操作,请在回复中明确风险与范围,并征得用户同意。
|
||||
- 可追溯性:在回复或提交说明中简要标注关键命令、影响模块与文件路径,便于审计。
|
||||
- Git 操作限制:除非用户明确要求,否则不要执行任何 Git 相关操作(包括但不限于 `commit`、`push`、`pull`、`merge`、`rebase`、`tag`、`branch`、`reset` 等)。如需读取 Git 元数据(如 `git log`、`git status`),也需先获得用户确认。
|
||||
|
||||
## 项目结构与模块组织
|
||||
- 父聚合工程:`pom.xml`(Java 17,Spring Boot 3.1,Spring Cloud 2022)。
|
||||
- 核心模块:
|
||||
- `zlt-commons`(公共 starter、工具)
|
||||
- `zlt-uaa`(认证),`zlt-gateway/sc-gateway`(API 网关)
|
||||
- `zlt-business/*`(业务服务:用户/文件/订单等)
|
||||
- `zlt-monitor/sc-admin`(监控),`zlt-config`(配置),`zlt-web/*`(前端)
|
||||
- 标准目录:`src/main/java`、`src/main/resources`,单测放在 `src/test/java`。
|
||||
|
||||
## 构建、测试与本地运行
|
||||
- 全量构建:`mvn -q -DskipTests clean package`
|
||||
- 全量测试:`mvn -q test`
|
||||
- 指定模块构建+测试:`mvn -pl zlt-business/user-center -am clean verify`
|
||||
- 本地运行示例:
|
||||
- 网关:`mvn -pl zlt-gateway/sc-gateway -am spring-boot:run`
|
||||
- 认证:`mvn -pl zlt-uaa -am spring-boot:run`
|
||||
- 从 JAR 运行:`java -jar zlt-gateway/sc-gateway/target/*.jar`
|
||||
先决条件:JDK 17、Maven 3.8+。
|
||||
|
||||
## 编码风格与命名约定
|
||||
- Java 使用 4 空格缩进、UTF-8、同一行左大括号。
|
||||
- 包名使用 `com.central.*`;模块名称以 `zlt-*` 为前缀。
|
||||
- 已使用处优先采用 Lombok 注解(如 `@Data`、`@Slf4j`)。
|
||||
- 方法/字段使用 lowerCamelCase;类名使用 PascalCase。
|
||||
|
||||
## 测试规范
|
||||
- 测试框架:JUnit 4 与 JUnit 5(按模块而定)。
|
||||
- 用例命名以 `*Test.java` 结尾,放在 `src/test/java`。
|
||||
- 为新增逻辑与关键路径补充单测;保持可重复、相互独立。
|
||||
- 提 PR 前执行:`mvn -pl <module> -am test`。
|
||||
|
||||
## 提交与合并请求规范
|
||||
- 采用约定式提交:`type(scope): 简要说明`,示例:`fix(订单中心): 修复事件处理逻辑`。
|
||||
- 常见类型:`feat`、`fix`、`docs`、`refactor`、`test`、`chore`。
|
||||
- 小步且描述清晰;必要时关联 Issue。
|
||||
- PR 需包含:目的/影响、涉及模块、测试说明;前端改动请附截图(`zlt-web/*`)。
|
||||
|
||||
## 安全与配置提示
|
||||
- 多模块使用 Nacos。请在本地提供 `spring.cloud.nacos.server-addr`,或在 `bootstrap.yml` 注释相关配置以单机运行。
|
||||
- 外部依赖常见:MySQL/Redis/Elasticsearch。按模块检查 `application.yml` 的端口/连接串。
|
||||
- 禁止提交密钥与凭据;使用环境变量或本地覆盖配置。
|
||||
@@ -0,0 +1,45 @@
|
||||
# 贡献指南 (Contributing Guide)
|
||||
|
||||
## 快速开始
|
||||
- Fork 本仓库(GitHub/Gitee),克隆到本地:`git clone <your_fork_url>`。
|
||||
- 目标分支:优先提交到 `develop`(如无则 `master`)。
|
||||
- 创建特性分支:`git checkout -b feature/<简要描述>`(缺陷用 `bugfix/`,文档用 `docs/`)。
|
||||
- 环境要求:JDK 17,Maven 3.8+。
|
||||
|
||||
## 构建与本地运行
|
||||
- 全量构建:`mvn -q -DskipTests clean package`
|
||||
- 全量测试:`mvn -q test`
|
||||
- 指定模块构建+测试:`mvn -pl zlt-business/user-center -am clean verify`
|
||||
- 本地运行示例:
|
||||
- 网关:`mvn -pl zlt-gateway/sc-gateway -am spring-boot:run`
|
||||
- 认证:`mvn -pl zlt-uaa -am spring-boot:run`
|
||||
- 从 JAR 运行:`java -jar zlt-gateway/sc-gateway/target/*.jar`
|
||||
|
||||
## 代码风格
|
||||
- Java:4 空格缩进、UTF-8、左大括号同行。
|
||||
- 包命名:`com.central.*`;模块命名:`zlt-*`。
|
||||
- 项目已使用 Lombok(如 `@Data`、`@Slf4j`),保持一致。
|
||||
|
||||
## 测试要求
|
||||
- 测试框架:JUnit 4/5(按模块而定)。
|
||||
- 测试类放在 `src/test/java`,命名以 `*Test.java` 结尾。
|
||||
- 为新增/变更逻辑补充单测;尽量使用 mock,避免依赖真实外部服务。
|
||||
- 提交前运行:`mvn -pl <module> -am test`,确保通过。
|
||||
|
||||
## 提交规范(Conventional Commits)
|
||||
- 格式:`type(scope): 简要说明`,示例:`fix(订单中心): 修复事件处理逻辑`。
|
||||
- 常用类型:`feat`、`fix`、`docs`、`refactor`、`test`、`chore`。
|
||||
- 正文可描述动机/实现要点;页脚关联问题:`Closes #123`。
|
||||
|
||||
## Pull Request 规范
|
||||
- 内容包含:变更目的与影响、涉及模块、测试方式与结果;前端改动(`zlt-web/*`)请附截图。
|
||||
- 保持 PR 粒度清晰、可审查;避免混入无关格式化改动。
|
||||
- 确保构建与测试通过,冲突已解决。
|
||||
|
||||
## 配置与安全
|
||||
- 多模块使用 Nacos;本地可提供 `spring.cloud.nacos.server-addr`,或在 `bootstrap.yml` 注释相关配置以单机运行。
|
||||
- 常见外部依赖:MySQL/Redis/Elasticsearch。按模块检查 `application.yml`。
|
||||
- 禁止提交密钥、证书与账户;使用环境变量或本地覆盖配置。
|
||||
|
||||
## 问题反馈
|
||||
- 提交 Issue 时请附:期望/实际结果、复现步骤、相关日志与环境信息(模块名、版本、OS、JDK)。
|
||||
@@ -0,0 +1 @@
|
||||
/* Go-Fly Admin 鐜颁唬绉戞妧鎰熶富棰?*//* CSS鍙橀噺瀹氫箟 */:root { /* 涓昏壊璋?*/ --primary-color: #1677ff; --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --tech-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* 鑳屾櫙鑹?*/ --bg-primary: #0f1419; --bg-secondary: #1a1d23; --bg-tertiary: #21252b; --bg-card: rgba(255, 255, 255, 0.05); --bg-glass: rgba(255, 255, 255, 0.08); /* 鏂囧瓧棰滆壊 */ --text-primary: #ffffff; --text-secondary: #a0a6b8; --text-tertiary: #6c7293; /* 杈规鍜屽垎鍓茬嚎 */ --border-color: rgba(255, 255, 255, 0.1); --divider-color: rgba(255, 255, 255, 0.08); /* 闃村奖 */ --shadow-card: 0 8px 32px rgba(0, 0, 0, 0.3); --shadow-hover: 0 12px 48px rgba(0, 0, 0, 0.4); --shadow-glow: 0 0 20px rgba(102, 126, 234, 0.3); /* 鍔ㄧ敾鏇茬嚎 */ --ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); --ease-in-out-back: cubic-bezier(0.68, -0.55, 0.265, 1.55);}/* 鍏ㄥ眬鏍峰紡閲嶇疆 */body { background: var(--bg-primary); color: var(--text-primary); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;}/* 鐜荤拑璐ㄦ劅鏁堟灉 */.glass-effect { background: var(--bg-glass); backdrop-filter: blur(10px); border: 1px solid var(--border-color); border-radius: 12px;}/* 鍗$墖鎮仠鏁堟灉 */.modern-card { background: var(--bg-card); border-radius: 16px; padding: 24px; box-shadow: var(--shadow-card); border: 1px solid var(--border-color); transition: all 0.3s var(--ease-out-quart); &:hover { transform: translateY(-4px); box-shadow: var(--shadow-hover); border-color: var(--primary-color); }}/* 绉戞妧鎰熸寜閽?*/.tech-button { background: var(--tech-gradient); border: none; border-radius: 8px; color: white; font-weight: 500; transition: all 0.3s var(--ease-out-quart); position: relative; overflow: hidden; &::before { content: ''; position: absolute;
|
||||
@@ -116,11 +116,11 @@
|
||||
<artifactId>spring-boot-autoconfigure</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- <dependency>
|
||||
<dependency>
|
||||
<groupId>com.trip</groupId>
|
||||
<artifactId>tourop</artifactId>
|
||||
<version>1.1</version>
|
||||
</dependency>-->
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -1,101 +1,101 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://${zlt.datasource.ip}/file-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
username: ${zlt.datasource.username}
|
||||
password: ${zlt.datasource.password}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
#实体扫描,多个package用逗号或者分号分隔
|
||||
typeAliasesPackage: com.central.common.model
|
||||
global-config:
|
||||
db-config:
|
||||
id-type: INPUT
|
||||
|
||||
springdoc:
|
||||
group-configs:
|
||||
- group: 'default'
|
||||
paths-to-match: '/**'
|
||||
packages-to-scan: com.central.file.controller
|
||||
|
||||
knife4j:
|
||||
enable: true
|
||||
setting:
|
||||
swagger-model-name: 文件中心接口文档
|
||||
|
||||
zlt:
|
||||
file-server:
|
||||
type: oss # 主存储类型(用于文件上传)
|
||||
s3:
|
||||
enabled: true # 启用S3服务(用于冷数据存储)
|
||||
access-key: ${zlt.s3.access-key}
|
||||
accessKeySecret: ${zlt.s3.accessKeySecret}
|
||||
endpoint: ${zlt.s3.endpoint}
|
||||
bucketName: ${zlt.s3.bucketName}
|
||||
region: ${zlt.s3.region:us-east-1}
|
||||
cos:
|
||||
secretId: ${zlt.cos.secretId}
|
||||
secretKey: ${zlt.cos.secretKey}
|
||||
endpoint: ${zlt.cos.endpoint}
|
||||
region: ${zlt.cos.region}
|
||||
bucketName: ${zlt.cos.bucketName}
|
||||
oss:
|
||||
secretId: ${zlt.oss.secretId}
|
||||
secretKey: ${zlt.oss.secretKey}
|
||||
endpoint: ${zlt.oss.endpoint}
|
||||
bucketName: ${zlt.oss.bucketName}
|
||||
# 时间窗口存储配置
|
||||
storage:
|
||||
enable-time-window: true # 启用时间窗口智能存储
|
||||
hot-data-days: 30 # 热数据保留天数
|
||||
migration:
|
||||
enable-verification: true # 启用迁移验证
|
||||
delete-source: false # 迁移后是否删除源文件
|
||||
batch-size: 100 # 迁移批次大小
|
||||
hot-sync:
|
||||
enabled: true # 启用热数据同步
|
||||
batch-size: 100 # 批次大小
|
||||
interval-minutes: 30 # 同步间隔
|
||||
access-threshold: 10 # 访问次数阈值
|
||||
max-threads: 5 # 最大线程数
|
||||
|
||||
sync:
|
||||
schedule:
|
||||
enabled: true # 启用定时任务
|
||||
cron: "0 0 2 * * ?" # 每日同步时间
|
||||
status-check:
|
||||
cron: "0 0 * * * ?" # 状态检查时间
|
||||
#多租户配置
|
||||
tenant:
|
||||
enable: false
|
||||
|
||||
#fastDFS配置
|
||||
#fdfs:
|
||||
# soTimeout: 1500
|
||||
# connectTimeout: 600
|
||||
# trackerList: ${zlt.fdfs.trackerList}
|
||||
|
||||
# CDN配置示例
|
||||
aliyun:
|
||||
cdn:
|
||||
# 是否启用CDN功能
|
||||
enabled: true
|
||||
# 阿里云AccessKey ID(建议使用环境变量配置)
|
||||
access-key-id: ${zlt.oss.secretId:LTAI5tSNV1RvexXpMMCZhxSe}
|
||||
# 阿里云AccessKey Secret(建议使用环境变量配置)
|
||||
access-key-secret: ${zlt.oss.secretKey:XocJRWU8emwjjvYLTrc04l91VZMkQK}
|
||||
# 地域ID
|
||||
region-id: cn-beijing
|
||||
# 默认域名
|
||||
domain: cdn.goflytec.com
|
||||
# 默认批次大小
|
||||
default-batch-size: 100
|
||||
# 任务等待超时时间(秒)
|
||||
task-timeout: 300
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
level:
|
||||
com.central.file.service.impl.CdnServiceImpl: DEBUG
|
||||
com.central.file.schedule.CdnScheduleTask: INFO
|
||||
#spring:
|
||||
# datasource:
|
||||
# url: jdbc:mysql://${zlt.datasource.ip}/file-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# username: ${zlt.datasource.username}
|
||||
# password: ${zlt.datasource.password}
|
||||
# driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
#
|
||||
#mybatis-plus:
|
||||
# mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
# #实体扫描,多个package用逗号或者分号分隔
|
||||
# typeAliasesPackage: com.central.common.model
|
||||
# global-config:
|
||||
# db-config:
|
||||
# id-type: INPUT
|
||||
#
|
||||
#springdoc:
|
||||
# group-configs:
|
||||
# - group: 'default'
|
||||
# paths-to-match: '/**'
|
||||
# packages-to-scan: com.central.file.controller
|
||||
#
|
||||
#knife4j:
|
||||
# enable: true
|
||||
# setting:
|
||||
# swagger-model-name: 文件中心接口文档
|
||||
#
|
||||
#zlt:
|
||||
# file-server:
|
||||
# type: oss # 主存储类型(用于文件上传)
|
||||
# s3:
|
||||
# enabled: true # 启用S3服务(用于冷数据存储)
|
||||
# access-key: ${zlt.s3.access-key}
|
||||
# accessKeySecret: ${zlt.s3.accessKeySecret}
|
||||
# endpoint: ${zlt.s3.endpoint}
|
||||
# bucketName: ${zlt.s3.bucketName}
|
||||
# region: ${zlt.s3.region:us-east-1}
|
||||
# cos:
|
||||
# secretId: ${zlt.cos.secretId}
|
||||
# secretKey: ${zlt.cos.secretKey}
|
||||
# endpoint: ${zlt.cos.endpoint}
|
||||
# region: ${zlt.cos.region}
|
||||
# bucketName: ${zlt.cos.bucketName}
|
||||
# oss:
|
||||
# secretId: ${zlt.oss.secretId}
|
||||
# secretKey: ${zlt.oss.secretKey}
|
||||
# endpoint: ${zlt.oss.endpoint}
|
||||
# bucketName: ${zlt.oss.bucketName}
|
||||
# # 时间窗口存储配置
|
||||
# storage:
|
||||
# enable-time-window: true # 启用时间窗口智能存储
|
||||
# hot-data-days: 30 # 热数据保留天数
|
||||
# migration:
|
||||
# enable-verification: true # 启用迁移验证
|
||||
# delete-source: false # 迁移后是否删除源文件
|
||||
# batch-size: 100 # 迁移批次大小
|
||||
# hot-sync:
|
||||
# enabled: true # 启用热数据同步
|
||||
# batch-size: 100 # 批次大小
|
||||
# interval-minutes: 30 # 同步间隔
|
||||
# access-threshold: 10 # 访问次数阈值
|
||||
# max-threads: 5 # 最大线程数
|
||||
#
|
||||
# sync:
|
||||
# schedule:
|
||||
# enabled: true # 启用定时任务
|
||||
# cron: "0 0 2 * * ?" # 每日同步时间
|
||||
# status-check:
|
||||
# cron: "0 0 * * * ?" # 状态检查时间
|
||||
# #多租户配置
|
||||
# tenant:
|
||||
# enable: false
|
||||
#
|
||||
##fastDFS配置
|
||||
##fdfs:
|
||||
## soTimeout: 1500
|
||||
## connectTimeout: 600
|
||||
## trackerList: ${zlt.fdfs.trackerList}
|
||||
#
|
||||
## CDN配置示例
|
||||
#aliyun:
|
||||
# cdn:
|
||||
# # 是否启用CDN功能
|
||||
# enabled: true
|
||||
# # 阿里云AccessKey ID(建议使用环境变量配置)
|
||||
# access-key-id: ${zlt.oss.secretId:LTAI5tSNV1RvexXpMMCZhxSe}
|
||||
# # 阿里云AccessKey Secret(建议使用环境变量配置)
|
||||
# access-key-secret: ${zlt.oss.secretKey:XocJRWU8emwjjvYLTrc04l91VZMkQK}
|
||||
# # 地域ID
|
||||
# region-id: cn-beijing
|
||||
# # 默认域名
|
||||
# domain: cdn.goflytec.com
|
||||
# # 默认批次大小
|
||||
# default-batch-size: 100
|
||||
# # 任务等待超时时间(秒)
|
||||
# task-timeout: 300
|
||||
#
|
||||
## 日志配置
|
||||
#logging:
|
||||
# level:
|
||||
# com.central.file.service.impl.CdnServiceImpl: DEBUG
|
||||
# com.central.file.schedule.CdnScheduleTask: INFO
|
||||
|
||||
@@ -4,10 +4,10 @@ server:
|
||||
spring:
|
||||
application:
|
||||
name: file-center
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
ip: 119.45.169.13
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
# ip: 119.45.169.13
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 20MB
|
||||
|
||||
@@ -5,6 +5,8 @@ import com.central.search.annotation.EnableSearchClient;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
/**
|
||||
@@ -14,6 +16,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
@EnableSearchClient
|
||||
@EnableTransactionManagement
|
||||
@EnableFeignInterceptor
|
||||
@EnableFeignClients(basePackages = {"com.central.**"})
|
||||
@SpringBootApplication
|
||||
public class OrderCenterApp {
|
||||
public static void main(String[] args) {
|
||||
|
||||
+2
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.central.common.datascope.annotation.IgnoreTenantScope;
|
||||
import com.central.common.exception.BusinessException;
|
||||
import com.central.common.model.PageResult;
|
||||
import com.central.order.constants.EditTaskStatus;
|
||||
@@ -166,6 +167,7 @@ public class EditTaskServiceImpl extends ServiceImpl<EditTaskMapper, EditTask> i
|
||||
}
|
||||
|
||||
@Override
|
||||
@IgnoreTenantScope
|
||||
public List<EditTask> getProcessingTasks() {
|
||||
try {
|
||||
LambdaQueryWrapper<EditTask> wrapper = new LambdaQueryWrapper<>();
|
||||
|
||||
@@ -1,150 +1,150 @@
|
||||
spring:
|
||||
datasource:
|
||||
# url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
url: jdbc:mysql://${zlt.datasource.ip}/order-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowMultiQueries=true
|
||||
username: ${zlt.datasource.username}
|
||||
password: ${zlt.datasource.password}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
#实体扫描,多个package用逗号或者分号分隔
|
||||
typeAliasesPackage: com.central.order.model
|
||||
# configuration:
|
||||
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
global-config:
|
||||
db-config:
|
||||
id-type: auto
|
||||
|
||||
springdoc:
|
||||
group-configs:
|
||||
- group: 'default'
|
||||
paths-to-match: '/**'
|
||||
packages-to-scan: com.central.order.controller
|
||||
|
||||
knife4j:
|
||||
enable: true
|
||||
setting:
|
||||
swagger-model-name: 订单中心接口文档
|
||||
zlt:
|
||||
#多租户配置
|
||||
tenant:
|
||||
enable: true
|
||||
ignoreTables:
|
||||
- edit_task
|
||||
- home_carousel
|
||||
- sys_message
|
||||
- wx_message_record
|
||||
- wx_subscribe_status
|
||||
- video_template
|
||||
- profit_sharing
|
||||
- order_statistics
|
||||
- orders_refund
|
||||
ignoreSqls:
|
||||
# 移除所有ignoreSqls配置,让所有SQL都经过租户过滤处理
|
||||
# 这样webApp租户的特殊处理逻辑才能生效
|
||||
# 该接口是白名单接口查询中的逻辑,来例如:机库直接创建数据没有携带租户ID
|
||||
- com.central.order.mapper.OrderMapper.getOrderByNumber
|
||||
- com.central.order.mapper.OrderMapper.getOrdersByStatus
|
||||
- com.central.order.mapper.RefundMapper.selectOne
|
||||
# update和delete类型的操作mybatisPlus不支持,原因是数据隔离级别
|
||||
# - com.central.order.mapper.OrderMapper.updateOrderStatus
|
||||
# 微信支付商户号
|
||||
tencent:
|
||||
merchantId: ${zlt.wxpay.merchantId}
|
||||
# 微信支付商户密钥
|
||||
merchantSerialNumber: ${zlt.wxpay.merchantSerialNumber}
|
||||
# 微信支付申请的应用ID
|
||||
appId: ${zlt.wxpay.appId}
|
||||
# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
|
||||
notifyUrl: ${zlt.wxpay.notifyUrl}
|
||||
# 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径)
|
||||
privateKeyPath: ${zlt.wxpay.privateKeyPath}
|
||||
apiV3Key: ${zlt.wxpay.apiV3Key}
|
||||
appSecret: ${zlt.security.tencent.app-secret}
|
||||
accessTokenUrl: ${zlt.security.tencent.accessTokenUrl}
|
||||
getwxacodeUrl: https://api.weixin.qq.com/wxa/getwxacode?access_token=
|
||||
# 微信退款通知地址
|
||||
refund-notify-url: ${zlt.wxrefund.notifyUrl}
|
||||
notification:
|
||||
app-id:
|
||||
app-secret:
|
||||
token:
|
||||
encoding-aes-key:
|
||||
pay:
|
||||
profit-sharing:
|
||||
enabled: true
|
||||
max-retry-times: 3
|
||||
retry-interval: 300000
|
||||
platform-rate: 30
|
||||
timeout: 1800000
|
||||
async-enabled: true
|
||||
async-pool-size: 5
|
||||
api:
|
||||
profit-sharing-url: https://api.mch.weixin.qq.com/v3/profitsharing/orders
|
||||
|
||||
|
||||
file:
|
||||
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
|
||||
cdn-url: cdn.goflytec.com
|
||||
style: image/resize,m_mfit,w_218,h_288
|
||||
#审计日志
|
||||
# audit-log:
|
||||
#spring:
|
||||
# datasource:
|
||||
## url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# url: jdbc:mysql://${zlt.datasource.ip}/order-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowMultiQueries=true
|
||||
# username: ${zlt.datasource.username}
|
||||
# password: ${zlt.datasource.password}
|
||||
# driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
#
|
||||
#mybatis-plus:
|
||||
# mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
# #实体扫描,多个package用逗号或者分号分隔
|
||||
# typeAliasesPackage: com.central.order.model
|
||||
## configuration:
|
||||
## log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
# global-config:
|
||||
# db-config:
|
||||
# id-type: auto
|
||||
#
|
||||
#springdoc:
|
||||
# group-configs:
|
||||
# - group: 'default'
|
||||
# paths-to-match: '/**'
|
||||
# packages-to-scan: com.central.order.controller
|
||||
#
|
||||
#knife4j:
|
||||
# enable: true
|
||||
# setting:
|
||||
# swagger-model-name: 订单中心接口文档
|
||||
#zlt:
|
||||
# #多租户配置
|
||||
# tenant:
|
||||
# enable: true
|
||||
# ignoreTables:
|
||||
# - edit_task
|
||||
# - home_carousel
|
||||
# - sys_message
|
||||
# - wx_message_record
|
||||
# - wx_subscribe_status
|
||||
# - video_template
|
||||
# - profit_sharing
|
||||
# - order_statistics
|
||||
# - orders_refund
|
||||
# ignoreSqls:
|
||||
# # 移除所有ignoreSqls配置,让所有SQL都经过租户过滤处理
|
||||
# # 这样webApp租户的特殊处理逻辑才能生效
|
||||
# # 该接口是白名单接口查询中的逻辑,来例如:机库直接创建数据没有携带租户ID
|
||||
# - com.central.order.mapper.OrderMapper.getOrderByNumber
|
||||
# - com.central.order.mapper.OrderMapper.getOrdersByStatus
|
||||
# - com.central.order.mapper.RefundMapper.selectOne
|
||||
# # update和delete类型的操作mybatisPlus不支持,原因是数据隔离级别
|
||||
## - com.central.order.mapper.OrderMapper.updateOrderStatus
|
||||
# # 微信支付商户号
|
||||
#tencent:
|
||||
# merchantId: ${zlt.wxpay.merchantId}
|
||||
## 微信支付商户密钥
|
||||
# merchantSerialNumber: ${zlt.wxpay.merchantSerialNumber}
|
||||
## 微信支付申请的应用ID
|
||||
# appId: ${zlt.wxpay.appId}
|
||||
## 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致)
|
||||
# notifyUrl: ${zlt.wxpay.notifyUrl}
|
||||
## 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径)
|
||||
# privateKeyPath: ${zlt.wxpay.privateKeyPath}
|
||||
# apiV3Key: ${zlt.wxpay.apiV3Key}
|
||||
# appSecret: ${zlt.security.tencent.app-secret}
|
||||
# accessTokenUrl: ${zlt.security.tencent.accessTokenUrl}
|
||||
# getwxacodeUrl: https://api.weixin.qq.com/wxa/getwxacode?access_token=
|
||||
## 微信退款通知地址
|
||||
# refund-notify-url: ${zlt.wxrefund.notifyUrl}
|
||||
# notification:
|
||||
# app-id:
|
||||
# app-secret:
|
||||
# token:
|
||||
# encoding-aes-key:
|
||||
# pay:
|
||||
# profit-sharing:
|
||||
# enabled: true
|
||||
# max-retry-times: 3
|
||||
# retry-interval: 300000
|
||||
# platform-rate: 30
|
||||
# timeout: 1800000
|
||||
# async-enabled: true
|
||||
# async-pool-size: 5
|
||||
# api:
|
||||
# profit-sharing-url: https://api.mch.weixin.qq.com/v3/profitsharing/orders
|
||||
#
|
||||
#
|
||||
#file:
|
||||
# oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
|
||||
# cdn-url: cdn.goflytec.com
|
||||
# style: image/resize,m_mfit,w_218,h_288
|
||||
# #审计日志
|
||||
## audit-log:
|
||||
## enabled: true
|
||||
## log-type: db
|
||||
## datasource:
|
||||
## driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
## jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
## username: ${zlt.datasource.username}
|
||||
## password: ${zlt.datasource.password}
|
||||
#
|
||||
#aliyun:
|
||||
# ims:
|
||||
# oss-endpoint: oss-cn-beijing.aliyuncs.com
|
||||
# access-key-id: LTAI5tSNV1RvexXpMMCZhxSe
|
||||
# access-key-secret: XocJRWU8emwjjvYLTrc04l91VZMkQK
|
||||
# endpoint: ice.cn-beijing.aliyuncs.com
|
||||
# region: cn-beijing
|
||||
# bucket: goflyapp # 使用实际存在的bucket名称
|
||||
#
|
||||
#wx:
|
||||
# mp:
|
||||
# app-id: wx0ea85b13966d88e1 # 服务号应用id
|
||||
# secret: a90637566b2b73f41f8b1dabd64dc32b # 服务号应用密钥
|
||||
# template-id:
|
||||
# payment-success: uscmjgLdw0cKBRq8vFyCOPbYj7p-fHuEOIhFwwIAe4A # 支付成功通知模板ID
|
||||
# video-complete: TEMPLATE_ID_2 # 视频完成通知模板ID
|
||||
# video-failure: TEMPLATE_ID_3 # 视频失败通知模板ID
|
||||
#
|
||||
# mini:
|
||||
# app-id: ${zlt.wxpay.appId}
|
||||
# secret: ${zlt.security.tencent.app-secret}
|
||||
# template:
|
||||
# pay-success: nSy7NGq1443YCfhgR81fgkeOVv9cSM5Ysp3nMoQYVpc
|
||||
# service-process: rgQCI3fMKPpgO-9nO3TzP-omohraGxX2suVioq7hQhk
|
||||
# activity-start: lgwkRnbdDc3mEwk3RMob43LpLHnLfglZtTkbFRPsPCA
|
||||
# order-complete: ZeIlAA6ImQLxBiLmo-53lM7wkL4KnuKKTGKWBZwYAdM
|
||||
# video-edit-complete: IXpL-Voztm3GM-zFj3sxA39qy8oRtAcxTiT7_Qsyz9Q
|
||||
#
|
||||
## 订单中心CDN预热配置
|
||||
#cdn:
|
||||
# prefetch:
|
||||
# # 是否启用CDN预热功能
|
||||
# enabled: true
|
||||
# log-type: db
|
||||
# datasource:
|
||||
# driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# username: ${zlt.datasource.username}
|
||||
# password: ${zlt.datasource.password}
|
||||
|
||||
aliyun:
|
||||
ims:
|
||||
oss-endpoint: oss-cn-beijing.aliyuncs.com
|
||||
access-key-id: LTAI5tSNV1RvexXpMMCZhxSe
|
||||
access-key-secret: XocJRWU8emwjjvYLTrc04l91VZMkQK
|
||||
endpoint: ice.cn-beijing.aliyuncs.com
|
||||
region: cn-beijing
|
||||
bucket: goflyapp # 使用实际存在的bucket名称
|
||||
|
||||
wx:
|
||||
mp:
|
||||
app-id: wx0ea85b13966d88e1 # 服务号应用id
|
||||
secret: a90637566b2b73f41f8b1dabd64dc32b # 服务号应用密钥
|
||||
template-id:
|
||||
payment-success: uscmjgLdw0cKBRq8vFyCOPbYj7p-fHuEOIhFwwIAe4A # 支付成功通知模板ID
|
||||
video-complete: TEMPLATE_ID_2 # 视频完成通知模板ID
|
||||
video-failure: TEMPLATE_ID_3 # 视频失败通知模板ID
|
||||
|
||||
mini:
|
||||
app-id: ${zlt.wxpay.appId}
|
||||
secret: ${zlt.security.tencent.app-secret}
|
||||
template:
|
||||
pay-success: nSy7NGq1443YCfhgR81fgkeOVv9cSM5Ysp3nMoQYVpc
|
||||
service-process: rgQCI3fMKPpgO-9nO3TzP-omohraGxX2suVioq7hQhk
|
||||
activity-start: lgwkRnbdDc3mEwk3RMob43LpLHnLfglZtTkbFRPsPCA
|
||||
order-complete: ZeIlAA6ImQLxBiLmo-53lM7wkL4KnuKKTGKWBZwYAdM
|
||||
video-edit-complete: IXpL-Voztm3GM-zFj3sxA39qy8oRtAcxTiT7_Qsyz9Q
|
||||
|
||||
# 订单中心CDN预热配置
|
||||
cdn:
|
||||
prefetch:
|
||||
# 是否启用CDN预热功能
|
||||
enabled: true
|
||||
# 每批次预热的文件数量
|
||||
batch-size: 50
|
||||
# 预热区域:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球
|
||||
area: domestic
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
level:
|
||||
com.central.order.controller.OrderFileController: DEBUG
|
||||
|
||||
# 携程API配置
|
||||
ctrip:
|
||||
aes:
|
||||
key: 087b36ad0dff7942 # 请替换为实际的AES密钥
|
||||
iv: 750e15a31356a99d # 请替换为实际的AES IV
|
||||
sign:
|
||||
key: ce6033ae31124ec5cdab3d2bc79f2622 # 请替换为实际的签名密钥
|
||||
# # 每批次预热的文件数量
|
||||
# batch-size: 50
|
||||
# # 预热区域:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球
|
||||
# area: domestic
|
||||
#
|
||||
## 日志配置
|
||||
#logging:
|
||||
# level:
|
||||
# com.central.order.controller.OrderFileController: DEBUG
|
||||
#
|
||||
## 携程API配置
|
||||
#ctrip:
|
||||
# aes:
|
||||
# key: 087b36ad0dff7942 # 请替换为实际的AES密钥
|
||||
# iv: 750e15a31356a99d # 请替换为实际的AES IV
|
||||
# sign:
|
||||
# key: ce6033ae31124ec5cdab3d2bc79f2622 # 请替换为实际的签名密钥
|
||||
|
||||
@@ -4,10 +4,10 @@ server:
|
||||
spring:
|
||||
application:
|
||||
name: order-center
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
ip: 81.70.164.178
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
# ip: 81.70.164.178
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package com.central.user.controller;
|
||||
|
||||
import com.central.common.model.CodeEnum;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.Tenant;
|
||||
import com.central.common.model.TenantInfo;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 租户层级管理接口
|
||||
* 对应前端 /tenant/hierarchy/* 约定
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/tenant/hierarchy")
|
||||
@Tag(name = "租户层级管理")
|
||||
public class TenantHierarchyController {
|
||||
|
||||
@Autowired
|
||||
private ITenantHierarchyService tenantHierarchyService;
|
||||
|
||||
/**
|
||||
* 创建租户
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@Operation(summary = "创建租户")
|
||||
public Result<TenantInfo> createTenant(@RequestBody TenantInfo body) {
|
||||
if (body == null || !StringUtils.hasText(body.getTenantId())) {
|
||||
return Result.failed("租户ID不能为空");
|
||||
}
|
||||
if (!tenantHierarchyService.validateTenantRelation(body.getTenantId(), body.getParentTenantId())) {
|
||||
return Result.failed("租户关系不合法,检测到可能的循环引用");
|
||||
}
|
||||
Tenant tenant = toTenant(body);
|
||||
Result<Tenant> created = tenantHierarchyService.createTenant(tenant);
|
||||
if (created.getResp_code() != null && created.getResp_code().equals(CodeEnum.SUCCESS.getCode())) {
|
||||
return Result.succeed(toTenantInfo(created.getData()), "创建成功");
|
||||
}
|
||||
return Result.failed(created.getResp_msg() != null ? created.getResp_msg() : "创建失败");
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新租户
|
||||
*/
|
||||
@PutMapping("/update")
|
||||
@Operation(summary = "更新租户")
|
||||
public Result<TenantInfo> updateTenant(@RequestBody TenantInfo body) {
|
||||
if (body == null || !StringUtils.hasText(body.getTenantId())) {
|
||||
return Result.failed("租户ID不能为空");
|
||||
}
|
||||
if (!tenantHierarchyService.validateTenantRelation(body.getTenantId(), body.getParentTenantId())) {
|
||||
return Result.failed("租户关系不合法,检测到可能的循环引用");
|
||||
}
|
||||
Tenant tenant = toTenant(body);
|
||||
Result<Tenant> updated = tenantHierarchyService.updateTenant(tenant);
|
||||
if (updated.getResp_code() != null && updated.getResp_code().equals(CodeEnum.SUCCESS.getCode())) {
|
||||
return Result.succeed(toTenantInfo(updated.getData()), "更新成功");
|
||||
}
|
||||
return Result.failed(updated.getResp_msg() != null ? updated.getResp_msg() : "更新失败");
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除租户(软删除)
|
||||
*/
|
||||
@DeleteMapping("/delete")
|
||||
@Operation(summary = "删除租户(软删除)")
|
||||
public Result<Boolean> deleteTenant(
|
||||
@Parameter(description = "租户ID", required = true)
|
||||
@RequestParam String tenantId) {
|
||||
return tenantHierarchyService.deleteTenant(tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取租户列表(分页)
|
||||
* 前端已将 current/pageSize 转换为 page/size
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
@Operation(summary = "获取租户列表(分页)")
|
||||
public Result<Map<String, Object>> listTenants(
|
||||
@RequestParam(required = false) String parentTenantId,
|
||||
@RequestParam(required = false) String tenantName,
|
||||
@RequestParam(required = false) Integer status,
|
||||
@RequestParam(required = false) Integer page,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
|
||||
Result<List<TenantInfo>> res = tenantHierarchyService.getTenantList(parentTenantId, tenantName, status, page, size);
|
||||
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
List<TenantInfo> list = res.getData();
|
||||
payload.put("data", list);
|
||||
// 由于服务层暂未返回 total,这里先以当前页条目数代替;后续可在服务层补充总数返回
|
||||
payload.put("total", list != null ? list.size() : 0);
|
||||
payload.put("success", res.getResp_code() != null && res.getResp_code().equals(CodeEnum.SUCCESS.getCode()));
|
||||
|
||||
if (payload.get("success").equals(Boolean.TRUE)) {
|
||||
return Result.succeed(payload);
|
||||
}
|
||||
return Result.failed(payload, res.getResp_msg());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取租户详情
|
||||
*/
|
||||
@GetMapping("/detail/{tenantId}")
|
||||
@Operation(summary = "获取租户详情")
|
||||
public Result<TenantInfo> getTenantDetail(
|
||||
@Parameter(description = "租户ID", required = true)
|
||||
@PathVariable("tenantId") String tenantId) {
|
||||
TenantInfo info = tenantHierarchyService.getTenantInfo(tenantId);
|
||||
if (info == null) {
|
||||
return Result.failed("租户不存在");
|
||||
}
|
||||
return Result.succeed(info);
|
||||
}
|
||||
|
||||
// ===== 私有方法:对象转换 =====
|
||||
private Tenant toTenant(TenantInfo info) {
|
||||
if (info == null) return null;
|
||||
Tenant t = new Tenant();
|
||||
t.setTenantId(info.getTenantId());
|
||||
t.setTenantName(info.getTenantName());
|
||||
t.setParentTenantId(info.getParentTenantId());
|
||||
t.setTenantLevel(info.getTenantLevel());
|
||||
t.setTenantPath(info.getTenantPath());
|
||||
t.setTenantType(info.getTenantType());
|
||||
t.setTenantCode(info.getTenantCode());
|
||||
t.setContactPerson(info.getContactPerson());
|
||||
t.setContactPhone(info.getContactPhone());
|
||||
t.setAddress(info.getAddress());
|
||||
t.setDescription(info.getDescription());
|
||||
t.setStatus(info.getStatus());
|
||||
t.setCreatorId(info.getCreatorId());
|
||||
return t;
|
||||
}
|
||||
|
||||
private TenantInfo toTenantInfo(Tenant t) {
|
||||
if (t == null) return null;
|
||||
return TenantInfo.builder()
|
||||
.tenantId(t.getTenantId())
|
||||
.tenantName(t.getTenantName())
|
||||
.parentTenantId(t.getParentTenantId())
|
||||
.tenantLevel(t.getTenantLevel())
|
||||
.tenantPath(t.getTenantPath())
|
||||
.tenantType(t.getTenantType())
|
||||
.tenantCode(t.getTenantCode())
|
||||
.contactPerson(t.getContactPerson())
|
||||
.contactPhone(t.getContactPhone())
|
||||
.address(t.getAddress())
|
||||
.description(t.getDescription())
|
||||
.status(t.getStatus())
|
||||
.creatorId(t.getCreatorId())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package com.central.user.controller;
|
||||
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.TenantInfo;
|
||||
import com.central.common.model.TenantTreeNode;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import com.central.common.service.UserTenantSelectionService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 租户切换管理控制器
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/tenant")
|
||||
@Tag(name = "租户管理")
|
||||
@Slf4j
|
||||
public class TenantSwitchController {
|
||||
|
||||
@Autowired
|
||||
private ITenantHierarchyService tenantHierarchyService;
|
||||
|
||||
@Autowired(required = false)
|
||||
private UserTenantSelectionService userTenantSelectionService;
|
||||
|
||||
/**
|
||||
* 获取用户可访问的租户树
|
||||
*/
|
||||
@GetMapping("/accessible")
|
||||
@Operation(summary = "获取可访问租户列表")
|
||||
public Result<List<TenantTreeNode>> getAccessibleTenants() {
|
||||
try {
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
if (user == null) {
|
||||
return Result.failed("用户未登录");
|
||||
}
|
||||
if (!isCanSwitchTenant(user)) {
|
||||
return Result.failed("用户无租户切换权限");
|
||||
}
|
||||
List<String> accessibleTenantIds = getAccessibleTenantIds(user);
|
||||
if (accessibleTenantIds.isEmpty()) {
|
||||
return Result.failed("用户无可访问的租户");
|
||||
}
|
||||
List<TenantTreeNode> tenantTree = tenantHierarchyService.buildTenantTree(accessibleTenantIds);
|
||||
return Result.succeed(tenantTree);
|
||||
} catch (Exception e) {
|
||||
log.error("获取可访问租户列表失败: {}", e.getMessage());
|
||||
return Result.failed("获取可访问租户列表失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换当前查询租户
|
||||
*/
|
||||
@PostMapping("/switch-query")
|
||||
@Operation(summary = "切换当前查询租户")
|
||||
public Result<String> switchTenant(
|
||||
@Parameter(description = "目标租户ID", required = true)
|
||||
@RequestParam String tenantId) {
|
||||
try {
|
||||
// 设置当前租户
|
||||
LoginUserContextHolder.setCurrentTenant(tenantId);
|
||||
|
||||
// 持久化选择(避免依赖请求头),后续请求基于Authorization恢复
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
if (userTenantSelectionService != null && user != null) {
|
||||
userTenantSelectionService.setCurrentTenant(user.getId(), tenantId);
|
||||
}
|
||||
|
||||
log.info("用户 {} 切换到租户 {}", user != null ? user.getUsername() : "-", tenantId);
|
||||
return Result.succeed("成功");
|
||||
} catch (SecurityException e) {
|
||||
log.warn("租户切换失败: {}", e.getMessage());
|
||||
return Result.failed(e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("租户切换异常: {}", e.getMessage());
|
||||
return Result.failed("租户切换异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前租户信息
|
||||
*/
|
||||
@GetMapping("/current/info")
|
||||
@Operation(summary = "获取当前租户信息")
|
||||
public Result<TenantInfo> getCurrentTenant() {
|
||||
try {
|
||||
String currentTenantId = LoginUserContextHolder.getCurrentTenantId();
|
||||
if (!StringUtils.hasText(currentTenantId)) {
|
||||
return Result.failed("未获取到当前租户信息");
|
||||
}
|
||||
TenantInfo tenantInfo = tenantHierarchyService.getTenantInfo(currentTenantId);
|
||||
if (tenantInfo == null) {
|
||||
return Result.failed("租户信息不存在");
|
||||
}
|
||||
return Result.succeed(tenantInfo);
|
||||
} catch (Exception e) {
|
||||
log.error("获取当前租户信息失败: {}", e.getMessage());
|
||||
return Result.failed("获取当前租户信息失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前查询范围统计
|
||||
*/
|
||||
@GetMapping("/scope/stats")
|
||||
@Operation(summary = "获取当前查询范围统计")
|
||||
public Result<Map<String, Object>> getCurrentScopeStats() {
|
||||
try {
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
if (user == null) {
|
||||
return Result.failed("用户未登录");
|
||||
}
|
||||
String currentTenantId = LoginUserContextHolder.getCurrentTenantId();
|
||||
List<String> queryTenantIds = LoginUserContextHolder.getCurrentQueryTenantIds();
|
||||
|
||||
Map<String, Object> stats = new HashMap<>();
|
||||
stats.put("currentTenantId", currentTenantId);
|
||||
stats.put("queryTenantCount", queryTenantIds.size());
|
||||
stats.put("queryTenantIds", queryTenantIds);
|
||||
stats.put("canSwitchTenant", LoginUserContextHolder.isManagementUser());
|
||||
stats.put("userType", LoginUserContextHolder.getUserType());
|
||||
stats.put("timestamp", System.currentTimeMillis());
|
||||
return Result.succeed(stats);
|
||||
} catch (Exception e) {
|
||||
log.error("获取查询范围统计失败: {}", e.getMessage());
|
||||
return Result.failed("获取查询范围统计失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置当前租户为用户默认租户
|
||||
*/
|
||||
@PostMapping("/reset")
|
||||
@Operation(summary = "重置为默认租户")
|
||||
public Result<String> resetToDefaultTenant() {
|
||||
try {
|
||||
LoginUserContextHolder.resetToDefaultTenant();
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
if (userTenantSelectionService != null && user != null) {
|
||||
userTenantSelectionService.clearCurrentTenant(user.getId());
|
||||
}
|
||||
log.info("用户 {} 重置为默认租户", user != null ? user.getUsername() : "-");
|
||||
return Result.succeed("成功");
|
||||
} catch (Exception e) {
|
||||
log.error("重置默认租户失败: {}", e.getMessage());
|
||||
return Result.failed("重置默认租户失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 私有方法 =====
|
||||
private boolean isCanSwitchTenant(LoginAppUser user) {
|
||||
return user.isCanSwitchTenant();
|
||||
}
|
||||
|
||||
private List<String> getAccessibleTenantIds(LoginAppUser user) {
|
||||
String userTenantId = getDefaultTenantId(user);
|
||||
if (StringUtils.hasText(userTenantId)) {
|
||||
if (isCanSwitchTenant(user)) {
|
||||
return tenantHierarchyService.getAllSubTenantIds(userTenantId);
|
||||
} else {
|
||||
return List.of(userTenantId);
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private String getDefaultTenantId(LoginAppUser user) {
|
||||
Object company = user.getAttributes().get("company");
|
||||
return company != null ? company.toString() : null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.central.user.feign;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.user.feign.fallback.DeviceCenterServiceFallback;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.central.user.feign;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.user.feign.fallback.OrderCenterServiceFallback;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.central.user.feign;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.user.feign.fallback.TenantServiceFallback;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
package com.central.user.feign;
|
||||
package com.central.user.feign.fallback;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.user.feign.DeviceCenterService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
package com.central.user.feign;
|
||||
package com.central.user.feign.fallback;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.user.feign.OrderCenterService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
package com.central.user.feign;
|
||||
package com.central.user.feign.fallback;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.user.feign.TenantService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package com.central.user.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.central.common.model.Tenant;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户层级管理Mapper
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Mapper
|
||||
public interface TenantHierarchyMapper extends BaseMapper<Tenant> {
|
||||
|
||||
/**
|
||||
* 根据租户ID查询租户信息
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 租户信息
|
||||
*/
|
||||
@Select("SELECT * FROM sys_tenant WHERE tenant_id = #{tenantId} AND status = 1")
|
||||
Tenant selectByTenantId(@Param("tenantId") String tenantId);
|
||||
|
||||
/**
|
||||
* 根据租户ID列表查询租户信息
|
||||
*
|
||||
* @param tenantIds 租户ID列表
|
||||
* @return 租户信息列表
|
||||
*/
|
||||
@Select("<script>" +
|
||||
"SELECT * FROM sys_tenant " +
|
||||
"WHERE tenant_id IN " +
|
||||
"<foreach collection='tenantIds' item='tenantId' open='(' separator=',' close=')'>" +
|
||||
"#{tenantId}" +
|
||||
"</foreach> " +
|
||||
"AND status = 1 " +
|
||||
"ORDER BY tenant_level, tenant_id" +
|
||||
"</script>")
|
||||
List<Tenant> selectByTenantIds(@Param("tenantIds") List<String> tenantIds);
|
||||
|
||||
/**
|
||||
* 查询指定租户的所有子租户ID(递归)
|
||||
*
|
||||
* @param parentTenantId 父租户ID
|
||||
* @return 子租户ID列表
|
||||
*/
|
||||
@Select("SELECT tenant_id FROM sys_tenant " +
|
||||
"WHERE tenant_path LIKE CONCAT(" +
|
||||
" (SELECT tenant_path FROM sys_tenant WHERE tenant_id = #{parentTenantId}), " +
|
||||
" '%'" +
|
||||
") " +
|
||||
"AND status = 1 " +
|
||||
"ORDER BY tenant_level, tenant_id")
|
||||
List<String> selectSubTenantIds(@Param("parentTenantId") String parentTenantId);
|
||||
|
||||
/**
|
||||
* 查询指定租户的直接子租户
|
||||
*
|
||||
* @param parentTenantId 父租户ID
|
||||
* @return 直接子租户列表
|
||||
*/
|
||||
@Select("SELECT * FROM sys_tenant " +
|
||||
"WHERE parent_tenant_id = #{parentTenantId} " +
|
||||
"AND status = 1 " +
|
||||
"ORDER BY tenant_id")
|
||||
List<Tenant> selectDirectChildren(@Param("parentTenantId") String parentTenantId);
|
||||
|
||||
/**
|
||||
* 检查租户ID是否存在
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 存在数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM sys_tenant WHERE tenant_id = #{tenantId}")
|
||||
int existsByTenantId(@Param("tenantId") String tenantId);
|
||||
|
||||
/**
|
||||
* 查询租户路径
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @return 租户路径
|
||||
*/
|
||||
@Select("SELECT tenant_path FROM sys_tenant WHERE tenant_id = #{tenantId} AND status = 1")
|
||||
String selectTenantPath(@Param("tenantId") String tenantId);
|
||||
|
||||
/**
|
||||
* 分页查询租户列表
|
||||
*
|
||||
* @param parentTenantId 父租户ID(可选)
|
||||
* @param tenantName 租户名称(模糊查询,可选)
|
||||
* @param status 状态(可选)
|
||||
* @param offset 偏移量
|
||||
* @param limit 限制数量
|
||||
* @return 租户列表
|
||||
*/
|
||||
@Select("<script>" +
|
||||
"SELECT t.*, " +
|
||||
" (SELECT COUNT(*) FROM sys_tenant c WHERE c.parent_tenant_id = t.tenant_id AND c.status = 1) as children_count, " +
|
||||
" (SELECT tenant_name FROM sys_tenant p WHERE p.tenant_id = t.parent_tenant_id) as parent_tenant_name " +
|
||||
"FROM sys_tenant t " +
|
||||
"WHERE 1=1 " +
|
||||
"<if test='parentTenantId != null and parentTenantId != \"\"'>" +
|
||||
" AND t.parent_tenant_id = #{parentTenantId} " +
|
||||
"</if>" +
|
||||
"<if test='tenantName != null and tenantName != \"\"'>" +
|
||||
" AND t.tenant_name LIKE CONCAT('%', #{tenantName}, '%') " +
|
||||
"</if>" +
|
||||
"<if test='status != null'>" +
|
||||
" AND t.status = #{status} " +
|
||||
"</if>" +
|
||||
"ORDER BY t.tenant_level, t.tenant_id " +
|
||||
"LIMIT #{offset}, #{limit}" +
|
||||
"</script>")
|
||||
List<Tenant> selectTenantList(@Param("parentTenantId") String parentTenantId,
|
||||
@Param("tenantName") String tenantName,
|
||||
@Param("status") Integer status,
|
||||
@Param("offset") Integer offset,
|
||||
@Param("limit") Integer limit);
|
||||
|
||||
/**
|
||||
* 查询租户总数
|
||||
*
|
||||
* @param parentTenantId 父租户ID(可选)
|
||||
* @param tenantName 租户名称(模糊查询,可选)
|
||||
* @param status 状态(可选)
|
||||
* @return 总数
|
||||
*/
|
||||
@Select("<script>" +
|
||||
"SELECT COUNT(*) FROM sys_tenant t " +
|
||||
"WHERE 1=1 " +
|
||||
"<if test='parentTenantId != null and parentTenantId != \"\"'>" +
|
||||
" AND t.parent_tenant_id = #{parentTenantId} " +
|
||||
"</if>" +
|
||||
"<if test='tenantName != null and tenantName != \"\"'>" +
|
||||
" AND t.tenant_name LIKE CONCAT('%', #{tenantName}, '%') " +
|
||||
"</if>" +
|
||||
"<if test='status != null'>" +
|
||||
" AND t.status = #{status} " +
|
||||
"</if>" +
|
||||
"</script>")
|
||||
long countTenantList(@Param("parentTenantId") String parentTenantId,
|
||||
@Param("tenantName") String tenantName,
|
||||
@Param("status") Integer status);
|
||||
}
|
||||
+1
-1
@@ -20,7 +20,7 @@ public interface ISysRoleUserService extends ISuperService<SysRoleUser> {
|
||||
* @param userId
|
||||
* @return
|
||||
*/
|
||||
List<SysRole> findRolesByUserId(Long userId);
|
||||
List<SysRole> findRolesByUserId(Long userId);
|
||||
|
||||
/**
|
||||
* 根据用户ids 获取
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ import java.util.List;
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class SysRoleUserServiceImpl extends SuperServiceImpl<SysUserRoleMapper, SysRoleUser> implements ISysRoleUserService {
|
||||
public class SysRoleUserServiceImpl extends SuperServiceImpl<SysUserRoleMapper, SysRoleUser> implements ISysRoleUserService {
|
||||
@Resource
|
||||
private SysUserRoleMapper sysUserRoleMapper;
|
||||
|
||||
|
||||
+2
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.common.datascope.annotation.IgnoreTenantScope;
|
||||
import com.central.common.lock.DistributedLock;
|
||||
import com.central.common.model.PageResult;
|
||||
import com.central.common.model.Result;
|
||||
@@ -240,6 +241,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
||||
}
|
||||
|
||||
@Override
|
||||
@IgnoreTenantScope
|
||||
public List<SysRole> findRolesByUserId(Long userId) {
|
||||
return roleUserService.findRolesByUserId(userId);
|
||||
}
|
||||
|
||||
+399
@@ -0,0 +1,399 @@
|
||||
package com.central.user.service.impl;
|
||||
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
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 com.central.common.service.ITenantHierarchyService;
|
||||
import com.central.user.mapper.TenantHierarchyMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 租户层级管理服务实现
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
|
||||
@Autowired
|
||||
private TenantHierarchyMapper tenantHierarchyMapper;
|
||||
|
||||
private static final String CACHE_KEY_PREFIX = "tenant:hierarchy:";
|
||||
|
||||
@Override
|
||||
@Cacheable(value = "tenant:hierarchy", key = "#parentTenantId")
|
||||
public List<String> getAllSubTenantIds(String parentTenantId) {
|
||||
if (!StringUtils.hasText(parentTenantId)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
try {
|
||||
List<String> subTenantIds = tenantHierarchyMapper.selectSubTenantIds(parentTenantId);
|
||||
log.debug("查询租户 {} 的所有子租户,数量: {}", parentTenantId, subTenantIds.size());
|
||||
return subTenantIds;
|
||||
} catch (Exception e) {
|
||||
log.error("查询子租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage());
|
||||
return Collections.singletonList(parentTenantId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TenantTreeNode> buildTenantTree(List<String> tenantIds) {
|
||||
if (tenantIds == null || tenantIds.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
try {
|
||||
// 获取租户详细信息
|
||||
List<Tenant> tenants = tenantHierarchyMapper.selectByTenantIds(tenantIds);
|
||||
|
||||
// 转换为树形节点
|
||||
Map<String, TenantTreeNode> nodeMap = new HashMap<>();
|
||||
List<TenantTreeNode> rootNodes = new ArrayList<>();
|
||||
|
||||
// 创建所有节点
|
||||
for (Tenant tenant : tenants) {
|
||||
TenantTreeNode node = TenantTreeNode.builder()
|
||||
.tenantId(tenant.getTenantId())
|
||||
.tenantName(tenant.getTenantName())
|
||||
.parentTenantId(tenant.getParentTenantId())
|
||||
.tenantType(tenant.getTenantType())
|
||||
.tenantLevel(tenant.getTenantLevel())
|
||||
.status(tenant.getStatus())
|
||||
.enabled(tenant.getStatus() == 1)
|
||||
.description(tenant.getDescription())
|
||||
.children(new ArrayList<>())
|
||||
.hasChildren(false)
|
||||
.childrenCount(0)
|
||||
.build();
|
||||
nodeMap.put(tenant.getTenantId(), node);
|
||||
}
|
||||
|
||||
// 构建父子关系
|
||||
for (TenantTreeNode node : nodeMap.values()) {
|
||||
if (!StringUtils.hasText(node.getParentTenantId())) {
|
||||
rootNodes.add(node);
|
||||
} else {
|
||||
TenantTreeNode parent = nodeMap.get(node.getParentTenantId());
|
||||
if (parent != null) {
|
||||
parent.getChildren().add(node);
|
||||
parent.setHasChildren(true);
|
||||
parent.setChildrenCount(parent.getChildren().size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("构建租户树完成,根节点数量: {}", rootNodes.size());
|
||||
return rootNodes;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("构建租户树失败: tenantIds={}, error={}", tenantIds, e.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TenantInfo getTenantInfo(String tenantId) {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Tenant tenant = tenantHierarchyMapper.selectByTenantId(tenantId);
|
||||
if (tenant == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 查询子租户数量
|
||||
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
|
||||
int childrenCount = children != null ? children.size() : 0;
|
||||
|
||||
// 查询父租户名称
|
||||
String parentTenantName = null;
|
||||
if (StringUtils.hasText(tenant.getParentTenantId())) {
|
||||
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
|
||||
if (parentTenant != null) {
|
||||
parentTenantName = parentTenant.getTenantName();
|
||||
}
|
||||
}
|
||||
|
||||
return TenantInfo.builder()
|
||||
.tenantId(tenant.getTenantId())
|
||||
.tenantName(tenant.getTenantName())
|
||||
.parentTenantId(tenant.getParentTenantId())
|
||||
.parentTenantName(parentTenantName)
|
||||
.tenantLevel(tenant.getTenantLevel())
|
||||
.tenantPath(tenant.getTenantPath())
|
||||
.tenantType(tenant.getTenantType())
|
||||
.tenantCode(tenant.getTenantCode())
|
||||
.contactPerson(tenant.getContactPerson())
|
||||
.contactPhone(tenant.getContactPhone())
|
||||
.address(tenant.getAddress())
|
||||
.description(tenant.getDescription())
|
||||
.status(tenant.getStatus())
|
||||
.statusText(tenant.getStatus() == 1 ? "启用" : "停用")
|
||||
.hasChildren(childrenCount > 0)
|
||||
.childrenCount(childrenCount)
|
||||
.createTime(tenant.getCreateTime() != null ?
|
||||
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
|
||||
.updateTime(tenant.getUpdateTime() != null ?
|
||||
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
|
||||
.creatorId(tenant.getCreatorId())
|
||||
.build();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取租户信息失败: tenantId={}, error={}", tenantId, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
||||
public Result<Tenant> createTenant(Tenant tenant) {
|
||||
try {
|
||||
// 验证必填字段
|
||||
if (!StringUtils.hasText(tenant.getTenantId())) {
|
||||
return Result.failed("租户ID不能为空");
|
||||
}
|
||||
if (!StringUtils.hasText(tenant.getTenantName())) {
|
||||
return Result.failed("租户名称不能为空");
|
||||
}
|
||||
|
||||
// 检查租户ID是否已存在
|
||||
if (existsByTenantId(tenant.getTenantId())) {
|
||||
return Result.failed("租户ID已存在");
|
||||
}
|
||||
|
||||
// 验证父租户关系
|
||||
if (StringUtils.hasText(tenant.getParentTenantId())) {
|
||||
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
|
||||
return Result.failed("无效的父子租户关系");
|
||||
}
|
||||
|
||||
// 获取父租户信息,设置层级和路径
|
||||
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
|
||||
if (parentTenant == null) {
|
||||
return Result.failed("父租户不存在");
|
||||
}
|
||||
tenant.setTenantLevel(parentTenant.getTenantLevel() + 1);
|
||||
tenant.setTenantPath(parentTenant.getTenantPath() + tenant.getTenantId() + "/");
|
||||
} else {
|
||||
// 根租户
|
||||
tenant.setTenantLevel(1);
|
||||
tenant.setTenantPath("/" + tenant.getTenantId() + "/");
|
||||
}
|
||||
|
||||
// 设置默认值
|
||||
if (tenant.getStatus() == null) {
|
||||
tenant.setStatus(1);
|
||||
}
|
||||
if (!StringUtils.hasText(tenant.getTenantType())) {
|
||||
tenant.setTenantType("COMPANY");
|
||||
}
|
||||
|
||||
// 设置创建人
|
||||
if (LoginUserContextHolder.getUser() != null) {
|
||||
tenant.setCreatorId(LoginUserContextHolder.getUser().getId());
|
||||
}
|
||||
|
||||
// 保存租户
|
||||
int result = tenantHierarchyMapper.insert(tenant);
|
||||
if (result > 0) {
|
||||
log.info("创建租户成功: tenantId={}, tenantName={}", tenant.getTenantId(), tenant.getTenantName());
|
||||
return Result.succeed(tenant);
|
||||
} else {
|
||||
return Result.failed("创建租户失败");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("创建租户异常: tenant={}, error={}", tenant, e.getMessage());
|
||||
return Result.failed("创建租户异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
||||
public Result<Tenant> updateTenant(Tenant tenant) {
|
||||
try {
|
||||
if (!StringUtils.hasText(tenant.getTenantId())) {
|
||||
return Result.failed("租户ID不能为空");
|
||||
}
|
||||
|
||||
// 检查租户是否存在
|
||||
Tenant existingTenant = tenantHierarchyMapper.selectByTenantId(tenant.getTenantId());
|
||||
if (existingTenant == null) {
|
||||
return Result.failed("租户不存在");
|
||||
}
|
||||
|
||||
// 验证父租户关系变更
|
||||
if (!Objects.equals(existingTenant.getParentTenantId(), tenant.getParentTenantId())) {
|
||||
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
|
||||
return Result.failed("无效的父子租户关系");
|
||||
}
|
||||
}
|
||||
|
||||
// 更新租户
|
||||
int result = tenantHierarchyMapper.updateById(tenant);
|
||||
if (result > 0) {
|
||||
log.info("更新租户成功: tenantId={}", tenant.getTenantId());
|
||||
return Result.succeed(tenant);
|
||||
} else {
|
||||
return Result.failed("更新租户失败");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("更新租户异常: tenant={}, error={}", tenant, e.getMessage());
|
||||
return Result.failed("更新租户异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
||||
public Result<Boolean> deleteTenant(String tenantId) {
|
||||
try {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return Result.failed("租户ID不能为空");
|
||||
}
|
||||
|
||||
// 检查是否有子租户
|
||||
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
|
||||
if (children != null && !children.isEmpty()) {
|
||||
return Result.failed("存在子租户,无法删除");
|
||||
}
|
||||
|
||||
// 软删除(更新状态为0)
|
||||
Tenant tenant = new Tenant();
|
||||
tenant.setTenantId(tenantId);
|
||||
tenant.setStatus(0);
|
||||
|
||||
int result = tenantHierarchyMapper.updateById(tenant);
|
||||
if (result > 0) {
|
||||
log.info("删除租户成功: tenantId={}", tenantId);
|
||||
return Result.succeed(true);
|
||||
} else {
|
||||
return Result.failed("删除租户失败");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("删除租户异常: tenantId={}, error={}", tenantId, e.getMessage());
|
||||
return Result.failed("删除租户异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result<List<TenantInfo>> getTenantList(String parentTenantId, String tenantName, Integer status, Integer page, Integer size) {
|
||||
try {
|
||||
if (page == null || page < 1) page = 1;
|
||||
if (size == null || size < 1) size = 10;
|
||||
|
||||
int offset = (page - 1) * size;
|
||||
|
||||
List<Tenant> tenants = tenantHierarchyMapper.selectTenantList(parentTenantId, tenantName, status, offset, size);
|
||||
long total = tenantHierarchyMapper.countTenantList(parentTenantId, tenantName, status);
|
||||
|
||||
List<TenantInfo> tenantInfos = tenants.stream()
|
||||
.map(this::convertToTenantInfo)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
log.debug("查询租户列表完成,总数: {}, 当前页: {}", total, tenantInfos.size());
|
||||
return Result.succeed(tenantInfos);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("查询租户列表异常: error={}", e.getMessage());
|
||||
return Result.failed("查询租户列表异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByTenantId(String tenantId) {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return false;
|
||||
}
|
||||
return tenantHierarchyMapper.existsByTenantId(tenantId) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateTenantRelation(String tenantId, String parentTenantId) {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 如果没有父租户,则合法
|
||||
if (!StringUtils.hasText(parentTenantId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 不能将自己设置为父租户
|
||||
if (tenantId.equals(parentTenantId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否会形成循环引用
|
||||
String currentTenantId = parentTenantId;
|
||||
Set<String> visited = new HashSet<>();
|
||||
|
||||
while (currentTenantId != null && !visited.contains(currentTenantId)) {
|
||||
visited.add(currentTenantId);
|
||||
|
||||
if (currentTenantId.equals(tenantId)) {
|
||||
// 形成循环引用
|
||||
return false;
|
||||
}
|
||||
|
||||
Tenant currentTenant = tenantHierarchyMapper.selectByTenantId(currentTenantId);
|
||||
currentTenantId = currentTenant != null ? currentTenant.getParentTenantId() : null;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为TenantInfo
|
||||
*/
|
||||
private TenantInfo convertToTenantInfo(Tenant tenant) {
|
||||
if (tenant == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TenantInfo.builder()
|
||||
.tenantId(tenant.getTenantId())
|
||||
.tenantName(tenant.getTenantName())
|
||||
.parentTenantId(tenant.getParentTenantId())
|
||||
.tenantLevel(tenant.getTenantLevel())
|
||||
.tenantPath(tenant.getTenantPath())
|
||||
.tenantType(tenant.getTenantType())
|
||||
.tenantCode(tenant.getTenantCode())
|
||||
.contactPerson(tenant.getContactPerson())
|
||||
.contactPhone(tenant.getContactPhone())
|
||||
.address(tenant.getAddress())
|
||||
.description(tenant.getDescription())
|
||||
.status(tenant.getStatus())
|
||||
.statusText(tenant.getStatus() == 1 ? "启用" : "停用")
|
||||
.hasChildren(tenant.getHasChildren())
|
||||
.childrenCount(tenant.getChildrenCount())
|
||||
.createTime(tenant.getCreateTime() != null ?
|
||||
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
|
||||
.updateTime(tenant.getUpdateTime() != null ?
|
||||
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
|
||||
.creatorId(tenant.getCreatorId())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,75 +1,75 @@
|
||||
spring:
|
||||
datasource:
|
||||
# url: jdbc:mysql://${zlt.datasource.ip}:3306/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
url: jdbc:mysql://${zlt.datasource.ip}/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
username: ${zlt.datasource.username}
|
||||
password: ${zlt.datasource.password}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
#实体扫描,多个package用逗号或者分号分隔
|
||||
typeAliasesPackage: com.central.common.model
|
||||
global-config:
|
||||
db-config:
|
||||
id-type: auto
|
||||
|
||||
springdoc:
|
||||
group-configs:
|
||||
- group: 'default'
|
||||
paths-to-match: '/**'
|
||||
packages-to-scan: com.central.user.controller
|
||||
|
||||
knife4j:
|
||||
enable: true
|
||||
setting:
|
||||
swagger-model-name: 用户中心接口文档
|
||||
|
||||
zlt:
|
||||
cache-manager:
|
||||
configs:
|
||||
- key: menu
|
||||
second: 300
|
||||
- key: user
|
||||
second: 1800
|
||||
#多租户配置
|
||||
tenant:
|
||||
enable: true
|
||||
ignoreTables:
|
||||
- sys_user
|
||||
- sys_role_user
|
||||
- sys_role_menu
|
||||
- wechat_config
|
||||
ignoreSqls:
|
||||
# 用户关联角色时,显示所有角色
|
||||
- com.central.user.mapper.SysRoleMapper.findAll
|
||||
# 用户列表显示用户所关联的所有角色
|
||||
- com.central.user.mapper.SysUserRoleMapper.findRolesByUserIds
|
||||
# 数据权限
|
||||
datascope:
|
||||
enabled: false
|
||||
ignoreTables:
|
||||
- sys_role_user
|
||||
- sys_role_menu
|
||||
includeSqls:
|
||||
# 用户列表
|
||||
- com.central.user.mapper.SysUserMapper.findList
|
||||
# 角色列表
|
||||
- com.central.user.mapper.SysRoleMapper.findList
|
||||
# 菜单列表
|
||||
- com.central.user.mapper.SysMenuMapper.selectList
|
||||
|
||||
tencent:
|
||||
app-id: ${zlt.security.tencent.app-id}
|
||||
app-secret: ${zlt.security.tencent.app-secret}
|
||||
access-token-url: https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=
|
||||
get-phonenumber-url: https://api.weixin.qq.com/cgi-bin/token
|
||||
#审计日志
|
||||
# audit-log:
|
||||
# enabled: true
|
||||
# log-type: db
|
||||
# datasource:
|
||||
# driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# username: ${zlt.datasource.username}
|
||||
# password: ${zlt.datasource.password}
|
||||
#spring:
|
||||
# datasource:
|
||||
## url: jdbc:mysql://${zlt.datasource.ip}:3306/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# url: jdbc:mysql://${zlt.datasource.ip}/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# username: ${zlt.datasource.username}
|
||||
# password: ${zlt.datasource.password}
|
||||
# driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
#
|
||||
#mybatis-plus:
|
||||
# mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
# #实体扫描,多个package用逗号或者分号分隔
|
||||
# typeAliasesPackage: com.central.common.model
|
||||
# global-config:
|
||||
# db-config:
|
||||
# id-type: auto
|
||||
#
|
||||
#springdoc:
|
||||
# group-configs:
|
||||
# - group: 'default'
|
||||
# paths-to-match: '/**'
|
||||
# packages-to-scan: com.central.user.controller
|
||||
#
|
||||
#knife4j:
|
||||
# enable: true
|
||||
# setting:
|
||||
# swagger-model-name: 用户中心接口文档
|
||||
#
|
||||
#zlt:
|
||||
# cache-manager:
|
||||
# configs:
|
||||
# - key: menu
|
||||
# second: 300
|
||||
# - key: user
|
||||
# second: 1800
|
||||
# #多租户配置
|
||||
# tenant:
|
||||
# enable: true
|
||||
# ignoreTables:
|
||||
# - sys_user
|
||||
# - sys_role_user
|
||||
# - sys_role_menu
|
||||
# - wechat_config
|
||||
# ignoreSqls:
|
||||
# # 用户关联角色时,显示所有角色
|
||||
# - com.central.user.mapper.SysRoleMapper.findAll
|
||||
# # 用户列表显示用户所关联的所有角色
|
||||
# - com.central.user.mapper.SysUserRoleMapper.findRolesByUserIds
|
||||
# # 数据权限
|
||||
# datascope:
|
||||
# enabled: false
|
||||
# ignoreTables:
|
||||
# - sys_role_user
|
||||
# - sys_role_menu
|
||||
# includeSqls:
|
||||
# # 用户列表
|
||||
# - com.central.user.mapper.SysUserMapper.findList
|
||||
# # 角色列表
|
||||
# - com.central.user.mapper.SysRoleMapper.findList
|
||||
# # 菜单列表
|
||||
# - com.central.user.mapper.SysMenuMapper.selectList
|
||||
#
|
||||
# tencent:
|
||||
# app-id: ${zlt.security.tencent.app-id}
|
||||
# app-secret: ${zlt.security.tencent.app-secret}
|
||||
# access-token-url: https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=
|
||||
# get-phonenumber-url: https://api.weixin.qq.com/cgi-bin/token
|
||||
##审计日志
|
||||
## audit-log:
|
||||
## enabled: true
|
||||
## log-type: db
|
||||
## datasource:
|
||||
## driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
## jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
## username: ${zlt.datasource.username}
|
||||
## password: ${zlt.datasource.password}
|
||||
|
||||
@@ -4,10 +4,10 @@ server:
|
||||
spring:
|
||||
application:
|
||||
name: user-center
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
ip: 124.222.128.40
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
# ip: 124.222.128.40
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
{
|
||||
"info": {
|
||||
"name": "Tenant Hierarchy APIs",
|
||||
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
|
||||
"description": "多租户层级相关接口集合:租户切换、范围查询、层级管理(/tenant/hierarchy/*)。"
|
||||
},
|
||||
"item": [
|
||||
{
|
||||
"name": "获取可访问租户树",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [
|
||||
{ "key": "Authorization", "value": "Bearer {{token}}" }
|
||||
],
|
||||
"url": { "raw": "{{baseUrl}}/tenant/accessible", "host": ["{{baseUrl}}"], "path": ["tenant", "accessible"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "切换当前查询租户",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
{ "key": "Authorization", "value": "Bearer {{token}}" }
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{baseUrl}}/tenant/switch?tenantId={{tenantId}}",
|
||||
"host": ["{{baseUrl}}"],
|
||||
"path": ["tenant", "switch"],
|
||||
"query": [ { "key": "tenantId", "value": "{{tenantId}}" } ]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "获取当前租户信息",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [ { "key": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"url": { "raw": "{{baseUrl}}/tenant/current", "host": ["{{baseUrl}}"], "path": ["tenant", "current"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "获取当前查询范围统计",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [ { "key": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"url": { "raw": "{{baseUrl}}/tenant/scope/stats", "host": ["{{baseUrl}}"], "path": ["tenant", "scope", "stats"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "重置为默认租户",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [ { "key": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"url": { "raw": "{{baseUrl}}/tenant/reset", "host": ["{{baseUrl}}"], "path": ["tenant", "reset"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "层级-创建租户",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
{ "key": "Authorization", "value": "Bearer {{token}}" },
|
||||
{ "key": "Content-Type", "value": "application/json" }
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"tenantId\": \"t_1001\",\n \"tenantName\": \"演示租户\",\n \"parentTenantId\": \"root\",\n \"tenantType\": \"COMPANY\",\n \"status\": 1\n}"
|
||||
},
|
||||
"url": { "raw": "{{baseUrl}}/tenant/hierarchy/create", "host": ["{{baseUrl}}"], "path": ["tenant", "hierarchy", "create"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "层级-更新租户",
|
||||
"request": {
|
||||
"method": "PUT",
|
||||
"header": [
|
||||
{ "key": "Authorization", "value": "Bearer {{token}}" },
|
||||
{ "key": "Content-Type", "value": "application/json" }
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"tenantId\": \"t_1001\",\n \"tenantName\": \"演示租户-更新\",\n \"status\": 1\n}"
|
||||
},
|
||||
"url": { "raw": "{{baseUrl}}/tenant/hierarchy/update", "host": ["{{baseUrl}}"], "path": ["tenant", "hierarchy", "update"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "层级-删除租户",
|
||||
"request": {
|
||||
"method": "DELETE",
|
||||
"header": [ { "key": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"url": {
|
||||
"raw": "{{baseUrl}}/tenant/hierarchy/delete?tenantId={{tenantId}}",
|
||||
"host": ["{{baseUrl}}"],
|
||||
"path": ["tenant", "hierarchy", "delete"],
|
||||
"query": [ { "key": "tenantId", "value": "{{tenantId}}" } ]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "层级-租户列表(分页)",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [ { "key": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"url": {
|
||||
"raw": "{{baseUrl}}/tenant/hierarchy/list?page={{page}}&size={{size}}&parentTenantId={{parentTenantId}}&tenantName={{tenantName}}&status={{status}}",
|
||||
"host": ["{{baseUrl}}"],
|
||||
"path": ["tenant", "hierarchy", "list"],
|
||||
"query": [
|
||||
{ "key": "page", "value": "{{page}}" },
|
||||
{ "key": "size", "value": "{{size}}" },
|
||||
{ "key": "parentTenantId", "value": "{{parentTenantId}}", "disabled": true },
|
||||
{ "key": "tenantName", "value": "{{tenantName}}", "disabled": true },
|
||||
{ "key": "status", "value": "{{status}}", "disabled": true }
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "层级-租户详情",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [ { "key": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"url": { "raw": "{{baseUrl}}/tenant/hierarchy/detail/{{tenantId}}", "host": ["{{baseUrl}}"], "path": ["tenant", "hierarchy", "detail", "{{tenantId}}"] }
|
||||
}
|
||||
}
|
||||
],
|
||||
"variable": [
|
||||
{ "key": "baseUrl", "value": "http://localhost:8080" },
|
||||
{ "key": "token", "value": "" },
|
||||
{ "key": "tenantId", "value": "t_1001" },
|
||||
{ "key": "page", "value": "1" },
|
||||
{ "key": "size", "value": "10" },
|
||||
{ "key": "parentTenantId", "value": "" },
|
||||
{ "key": "tenantName", "value": "" },
|
||||
{ "key": "status", "value": "" }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
-- ============================================
|
||||
-- 租户层级化重构 - 数据迁移脚本
|
||||
-- 创建时间: 2024-12-19
|
||||
-- 说明: 从现有sys_user表迁移租户数据到租户层级表
|
||||
-- ============================================
|
||||
|
||||
-- 步骤1: 从现有sys_user表提取唯一的租户数据
|
||||
INSERT INTO sys_tenant (tenant_id, tenant_name, tenant_level, tenant_path, tenant_type, description, status)
|
||||
SELECT DISTINCT
|
||||
u.company as tenant_id,
|
||||
CASE
|
||||
WHEN u.company = 'webApp' THEN '平台管理租户'
|
||||
ELSE CONCAT(u.company, '_租户')
|
||||
END as tenant_name,
|
||||
CASE
|
||||
WHEN u.company = 'webApp' THEN 0
|
||||
ELSE 1
|
||||
END as tenant_level,
|
||||
CONCAT('/', u.company, '/') as tenant_path,
|
||||
CASE
|
||||
WHEN u.company = 'webApp' THEN 'PLATFORM'
|
||||
ELSE 'COMPANY'
|
||||
END as tenant_type,
|
||||
CASE
|
||||
WHEN u.company = 'webApp' THEN '系统管理专用租户,具有全平台访问权限'
|
||||
ELSE CONCAT(u.company, '业务租户')
|
||||
END as description,
|
||||
1 as status
|
||||
FROM sys_user u
|
||||
WHERE u.company IS NOT NULL
|
||||
AND u.company != ''
|
||||
AND u.company NOT IN (
|
||||
SELECT tenant_id FROM sys_tenant WHERE tenant_id = u.company
|
||||
);
|
||||
|
||||
-- 步骤2: 为webApp租户设置特殊属性(如果不存在)
|
||||
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, tenant_type, description, status)
|
||||
SELECT 'webApp', '平台管理租户', NULL, 0, '/webApp/', 'PLATFORM', '系统管理专用租户,具有全平台访问权限', 1
|
||||
WHERE NOT EXISTS (SELECT 1 FROM sys_tenant WHERE tenant_id = 'webApp');
|
||||
|
||||
-- 步骤3: 验证迁移结果
|
||||
SELECT
|
||||
COUNT(*) as total_tenants,
|
||||
COUNT(CASE WHEN tenant_type = 'PLATFORM' THEN 1 END) as platform_tenants,
|
||||
COUNT(CASE WHEN tenant_type = 'COMPANY' THEN 1 END) as company_tenants,
|
||||
COUNT(CASE WHEN status = 1 THEN 1 END) as active_tenants
|
||||
FROM sys_tenant;
|
||||
|
||||
-- 步骤4: 显示迁移后的租户列表
|
||||
SELECT
|
||||
tenant_id,
|
||||
tenant_name,
|
||||
parent_tenant_id,
|
||||
tenant_level,
|
||||
tenant_type,
|
||||
status,
|
||||
create_time
|
||||
FROM sys_tenant
|
||||
ORDER BY tenant_level, tenant_id;
|
||||
|
||||
-- 步骤5: 检查是否有用户的company字段在租户表中不存在
|
||||
SELECT DISTINCT
|
||||
u.company as missing_tenant,
|
||||
COUNT(*) as user_count
|
||||
FROM sys_user u
|
||||
LEFT JOIN sys_tenant t ON u.company = t.tenant_id
|
||||
WHERE u.company IS NOT NULL
|
||||
AND u.company != ''
|
||||
AND t.tenant_id IS NULL
|
||||
GROUP BY u.company;
|
||||
|
||||
-- 提示:如果步骤5有结果,说明有用户的租户在迁移中遗漏,需要手动处理
|
||||
@@ -0,0 +1,114 @@
|
||||
-- ======================================================
|
||||
-- 租户层级结构迁移SQL
|
||||
-- 创建时间: 2025年1月
|
||||
-- 描述: 为现有租户系统添加层级结构支持
|
||||
-- ======================================================
|
||||
|
||||
-- 1. 创建租户层级表
|
||||
CREATE TABLE `sys_tenant` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`tenant_id` VARCHAR(32) NOT NULL COMMENT '租户ID',
|
||||
`parent_tenant_id` VARCHAR(32) NULL DEFAULT NULL COMMENT '父租户ID',
|
||||
`tenant_name` VARCHAR(100) NOT NULL COMMENT '租户名称',
|
||||
`tenant_path` VARCHAR(1000) NULL DEFAULT NULL COMMENT '租户路径 格式: /root/parent/current',
|
||||
`level` INT NOT NULL DEFAULT 1 COMMENT '租户层级 1=根租户',
|
||||
`sort_order` INT NOT NULL DEFAULT 0 COMMENT '同级排序',
|
||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用 1=启用 0=禁用',
|
||||
`tenant_type` VARCHAR(20) NOT NULL DEFAULT 'NORMAL' COMMENT '租户类型 ROOT=根租户 NORMAL=普通租户',
|
||||
`description` VARCHAR(500) NULL DEFAULT NULL COMMENT '租户描述',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`creator_id` BIGINT NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
`updater_id` BIGINT NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE KEY `uk_tenant_id` (`tenant_id`) USING BTREE,
|
||||
KEY `idx_parent_tenant_id` (`parent_tenant_id`) USING BTREE,
|
||||
KEY `idx_tenant_path` (`tenant_path`) USING BTREE,
|
||||
KEY `idx_level` (`level`) USING BTREE,
|
||||
KEY `idx_enabled` (`enabled`) USING BTREE
|
||||
) ENGINE = InnoDB
|
||||
AUTO_INCREMENT = 1
|
||||
CHARACTER SET = utf8mb4
|
||||
COLLATE = utf8mb4_general_ci
|
||||
COMMENT = '租户层级结构表'
|
||||
ROW_FORMAT = Dynamic;
|
||||
|
||||
-- 2. 创建租户用户关联表 (如果不存在)
|
||||
CREATE TABLE IF NOT EXISTS `sys_tenant_user` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`tenant_id` VARCHAR(32) NOT NULL COMMENT '租户ID',
|
||||
`user_id` BIGINT NOT NULL COMMENT '用户ID',
|
||||
`role_type` VARCHAR(20) NOT NULL DEFAULT 'MEMBER' COMMENT '角色类型 ADMIN=管理员 MEMBER=成员',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`creator_id` BIGINT NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE KEY `uk_tenant_user` (`tenant_id`, `user_id`) USING BTREE,
|
||||
KEY `idx_user_id` (`user_id`) USING BTREE,
|
||||
KEY `idx_tenant_id` (`tenant_id`) USING BTREE
|
||||
) ENGINE = InnoDB
|
||||
AUTO_INCREMENT = 1
|
||||
CHARACTER SET = utf8mb4
|
||||
COLLATE = utf8mb4_general_ci
|
||||
COMMENT = '租户用户关联表'
|
||||
ROW_FORMAT = Dynamic;
|
||||
|
||||
-- 3. 初始化根租户数据 (根据现有租户ID创建)
|
||||
INSERT INTO `sys_tenant`
|
||||
(`tenant_id`, `parent_tenant_id`, `tenant_name`, `tenant_path`, `level`, `tenant_type`, `description`, `creator_id`)
|
||||
VALUES
|
||||
('webApp', NULL, 'Web应用根租户', '/webApp', 1, 'ROOT', '系统默认根租户,用于超级管理员', 1),
|
||||
('admin', NULL, '系统管理租户', '/admin', 1, 'ROOT', '系统管理租户', 1);
|
||||
|
||||
-- 4. 为现有用户创建租户关联 (示例,需要根据实际业务调整)
|
||||
-- INSERT INTO `sys_tenant_user` (`tenant_id`, `user_id`, `role_type`, `creator_id`)
|
||||
-- SELECT 'webApp', id, 'ADMIN', 1 FROM sys_user WHERE username IN ('admin', 'mgnt');
|
||||
|
||||
-- 5. 创建租户层级查询视图 (可选)
|
||||
CREATE OR REPLACE VIEW `v_tenant_hierarchy_tree` AS
|
||||
SELECT
|
||||
t.tenant_id,
|
||||
t.tenant_name,
|
||||
t.parent_tenant_id,
|
||||
t.tenant_path,
|
||||
t.level,
|
||||
t.enabled,
|
||||
CONCAT(REPEAT(' ', t.level - 1), t.tenant_name) AS display_name,
|
||||
(SELECT COUNT(*) FROM sys_tenant_hierarchy c WHERE c.parent_tenant_id = t.tenant_id) AS children_count
|
||||
FROM sys_tenant_hierarchy t
|
||||
WHERE t.enabled = 1
|
||||
ORDER BY t.tenant_path, t.sort_order;
|
||||
|
||||
-- 6. 创建递归查询函数 (MySQL 8.0+)
|
||||
DELIMITER //
|
||||
CREATE FUNCTION `fn_get_tenant_children`(in_tenant_id VARCHAR(32))
|
||||
RETURNS TEXT
|
||||
READS SQL DATA
|
||||
DETERMINISTIC
|
||||
BEGIN
|
||||
DECLARE result TEXT DEFAULT '';
|
||||
|
||||
WITH RECURSIVE tenant_tree AS (
|
||||
-- 查找指定租户
|
||||
SELECT tenant_id, parent_tenant_id, tenant_name, 1 as depth
|
||||
FROM sys_tenant_hierarchy
|
||||
WHERE tenant_id = in_tenant_id AND enabled = 1
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- 递归查找子租户
|
||||
SELECT h.tenant_id, h.parent_tenant_id, h.tenant_name, t.depth + 1
|
||||
FROM sys_tenant_hierarchy h
|
||||
INNER JOIN tenant_tree t ON h.parent_tenant_id = t.tenant_id
|
||||
WHERE h.enabled = 1
|
||||
)
|
||||
SELECT GROUP_CONCAT(tenant_id SEPARATOR ',') INTO result
|
||||
FROM tenant_tree;
|
||||
|
||||
RETURN IFNULL(result, in_tenant_id);
|
||||
END //
|
||||
DELIMITER ;
|
||||
|
||||
-- 7. 数据迁移后验证查询
|
||||
-- SELECT * FROM sys_tenant_hierarchy ORDER BY tenant_path;
|
||||
-- SELECT * FROM v_tenant_hierarchy_tree;
|
||||
-- SELECT fn_get_tenant_children('webApp') as tenant_children;
|
||||
@@ -0,0 +1,42 @@
|
||||
-- ============================================
|
||||
-- 租户层级化重构 - 数据库表结构
|
||||
-- 创建时间: 2024-12-19
|
||||
-- 说明: 租户层级关系表和相关索引
|
||||
-- ============================================
|
||||
|
||||
-- 创建租户层级关系表
|
||||
CREATE TABLE `sys_tenant` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`tenant_id` VARCHAR(32) NOT NULL COMMENT '租户ID(对应现有company字段)',
|
||||
`tenant_name` VARCHAR(100) NOT NULL COMMENT '租户名称',
|
||||
`parent_tenant_id` VARCHAR(32) DEFAULT NULL COMMENT '父租户ID',
|
||||
`tenant_level` INT DEFAULT 1 COMMENT '租户层级(1=根租户)',
|
||||
`tenant_path` VARCHAR(1000) COMMENT '租户路径(/root/child/)',
|
||||
`tenant_type` VARCHAR(20) DEFAULT 'COMPANY' COMMENT '租户类型(GROUP/COMPANY/DEPARTMENT)',
|
||||
`tenant_code` VARCHAR(32) COMMENT '租户编码',
|
||||
`contact_person` VARCHAR(50) COMMENT '负责人',
|
||||
`contact_phone` VARCHAR(20) COMMENT '联系电话',
|
||||
`address` VARCHAR(255) COMMENT '地址',
|
||||
`description` TEXT COMMENT '租户描述',
|
||||
`status` TINYINT DEFAULT 1 COMMENT '状态(0:停用,1:启用)',
|
||||
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`creator_id` BIGINT COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_id` (`tenant_id`),
|
||||
INDEX `idx_parent_tenant` (`parent_tenant_id`),
|
||||
INDEX `idx_tenant_level` (`tenant_level`),
|
||||
INDEX `idx_tenant_path` (`tenant_path`(255)),
|
||||
INDEX `idx_status` (`status`),
|
||||
INDEX `idx_tenant_type` (`tenant_type`),
|
||||
INDEX `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='租户层级关系表';
|
||||
|
||||
-- 创建租户路径查询优化索引
|
||||
CREATE INDEX `idx_tenant_hierarchy_path_status` ON `sys_tenant`(`tenant_path`(255), `status`);
|
||||
|
||||
-- 创建父子关系查询优化索引
|
||||
CREATE INDEX `idx_tenant_hierarchy_parent_status` ON `sys_tenant`(`parent_tenant_id`, `status`);
|
||||
|
||||
-- 添加表注释
|
||||
ALTER TABLE `sys_tenant` COMMENT = '租户层级关系表 - 支持多级租户管理和权限控制';
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"client": "Thunder Client",
|
||||
"collectionName": "Tenant Hierarchy APIs",
|
||||
"dateExported": "2025-09-18",
|
||||
"version": "1.1",
|
||||
"folders": [],
|
||||
"requests": [
|
||||
{
|
||||
"name": "获取可访问租户树",
|
||||
"url": "{{baseUrl}}/tenant/accessible",
|
||||
"method": "GET",
|
||||
"headers": [ { "name": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"params": []
|
||||
},
|
||||
{
|
||||
"name": "切换当前查询租户",
|
||||
"url": "{{baseUrl}}/tenant/switch",
|
||||
"method": "POST",
|
||||
"headers": [ { "name": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"params": [ { "name": "tenantId", "value": "{{tenantId}}" } ]
|
||||
},
|
||||
{
|
||||
"name": "层级-租户列表(分页)",
|
||||
"url": "{{baseUrl}}/tenant/hierarchy/list",
|
||||
"method": "GET",
|
||||
"headers": [ { "name": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"params": [
|
||||
{ "name": "page", "value": "1" },
|
||||
{ "name": "size", "value": "10" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "层级-租户详情",
|
||||
"url": "{{baseUrl}}/tenant/hierarchy/detail/{{tenantId}}",
|
||||
"method": "GET",
|
||||
"headers": [ { "name": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"params": []
|
||||
},
|
||||
{
|
||||
"name": "层级-创建租户",
|
||||
"url": "{{baseUrl}}/tenant/hierarchy/create",
|
||||
"method": "POST",
|
||||
"headers": [
|
||||
{ "name": "Authorization", "value": "Bearer {{token}}" },
|
||||
{ "name": "Content-Type", "value": "application/json" }
|
||||
],
|
||||
"body": "{\n \"tenantId\": \"t_1001\",\n \"tenantName\": \"演示租户\",\n \"parentTenantId\": \"root\",\n \"tenantType\": \"COMPANY\",\n \"status\": 1\n}"
|
||||
},
|
||||
{
|
||||
"name": "层级-更新租户",
|
||||
"url": "{{baseUrl}}/tenant/hierarchy/update",
|
||||
"method": "PUT",
|
||||
"headers": [
|
||||
{ "name": "Authorization", "value": "Bearer {{token}}" },
|
||||
{ "name": "Content-Type", "value": "application/json" }
|
||||
],
|
||||
"body": "{\n \"tenantId\": \"t_1001\",\n \"tenantName\": \"演示租户-更新\",\n \"status\": 1\n}"
|
||||
},
|
||||
{
|
||||
"name": "层级-删除租户",
|
||||
"url": "{{baseUrl}}/tenant/hierarchy/delete",
|
||||
"method": "DELETE",
|
||||
"headers": [ { "name": "Authorization", "value": "Bearer {{token}}" } ],
|
||||
"params": [ { "name": "tenantId", "value": "{{tenantId}}" } ]
|
||||
}
|
||||
],
|
||||
"settings": {
|
||||
"envId": "default",
|
||||
"variables": [
|
||||
{ "name": "baseUrl", "value": "http://localhost:8080" },
|
||||
{ "name": "token", "value": "" },
|
||||
{ "name": "tenantId", "value": "t_1001" }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# 前端迁移记录(react-web-next)
|
||||
|
||||
本文记录将 `zlt-web/react-web` 管理后台迁移至新工程 `zlt-web/react-web-next` 的过程与阶段成果,便于后续持续迁移与审计。
|
||||
|
||||
## 目标
|
||||
- 不改动旧工程代码与行为,逐步等价迁移到新工程。
|
||||
- 统一为各页面提供“租户 + 包含子租户”查询能力。
|
||||
- 优化结构(组件化/服务分层/请求封装)与视觉风格(现代化、统一)。
|
||||
|
||||
## 已完成(阶段一)
|
||||
- 新工程脚手架与基础结构:
|
||||
- 目录:`zlt-web/react-web-next/*`
|
||||
- 路由:`config/routes.ts`
|
||||
- 布局:`src/layouts/BasicLayout.tsx`
|
||||
- 全局样式:`src/global.less`
|
||||
- 统一租户过滤器组件:
|
||||
- `src/components/TenantScopeFilter/index.tsx`
|
||||
- 接入 Welcome 页面、租户管理页面工具栏
|
||||
- 请求封装:
|
||||
- `src/app.tsx` 中配置 request 拦截,自动注入 Authorization;
|
||||
- 兼容后端 `Result` 结构,前端拿到 `{ success, msg, data }` 风格
|
||||
- 页面迁移:
|
||||
1. 登录页(/user/login)
|
||||
- 源对标:`react-web/src/pages/user/Login`
|
||||
- 新路径:`react-web-next/src/pages/user/Login`
|
||||
- 对接接口:`/api-uaa/oauth/token`(与旧版一致)
|
||||
- 行为:缓存租户标识、会话存 access_token、验证码刷新、成功后跳转
|
||||
2. 欢迎页(/welcome)
|
||||
- 示例接入统一租户过滤器
|
||||
3. 租户管理页(/system/tenant.html)
|
||||
- 源对标:旧租户管理(此次为重构实现)
|
||||
- 功能:机构树筛选 + 表格列表 + 树型上级选择 + 新建/编辑/删除
|
||||
- 服务:沿用 `/tenant/hierarchy/*` 接口
|
||||
4. 角色管理页(/system/role.html)
|
||||
- 源对标:`react-web/src/pages/system/Role`
|
||||
- 新路径:`react-web-next/src/pages/system/Role`
|
||||
- 组件化拆分:`components/RoleForm`、`components/AssignAuth`,页面容器通过 QueryFilter 选择“所属应用(tenantId)”
|
||||
- 统一接入:页面工具栏挂载 `TenantScopeFilter`,全局租户切换不改变接口形态;列表查询保留后端要求的 `tenantId` 参数
|
||||
5. 菜单管理页(/system/menus.html)
|
||||
- 源对标:`react-web/src/pages/system/Menu`
|
||||
- 新路径:`react-web-next/src/pages/system/Menu`
|
||||
- 组件化拆分:`components/MenuTree`(树形表格)、`components/MenuForm`(新增/编辑复用)
|
||||
- 查询条件:QueryFilter 选择“所属应用(tenantId)”与关键字;顶部接入 `TenantScopeFilter`
|
||||
- 服务复用:`/api-user/menus/findAlls`、`/api-user/menus/findOnes`、`/api-user/menus/saveOrUpdate`、`/api-user/menus/{id}`
|
||||
6. Token 管理页(/system/tokens.html)
|
||||
- 源对标:`react-web/src/pages/system/Token`
|
||||
- 新路径:`react-web-next/src/pages/system/Token`
|
||||
- 组件化:页面容器内使用 ProTable;顶部接入 `TenantScopeFilter`
|
||||
- 查询条件:QueryFilter 选择“所属应用(tenantId)”与用户名
|
||||
- 服务复用:`/api-uaa/tokens`(分页)、`/api-uaa/oauth/remove/token`(删除)
|
||||
7. 应用管理页(/attestation/app.html)
|
||||
- 源对标:`react-web/src/pages/system/App`
|
||||
- 新路径:`react-web-next/src/pages/system/App`
|
||||
- 组件化拆分:`components/AppForm`(新增/编辑复用)
|
||||
- 查询条件:QueryFilter `searchKey`
|
||||
- 服务复用:`/api-uaa/clients/list`、`/api-uaa/clients/saveOrUpdate`、`/api-uaa/clients/{id}`
|
||||
8. 微信配置(MiniApp)页(/system/miniApp.html)
|
||||
- 源对标:`react-web/src/pages/system/MiniApp`
|
||||
- 新路径:`react-web-next/src/pages/system/MiniApp`
|
||||
- 组件化拆分:`components/MiniAppForm`(新增/编辑复用)
|
||||
- 查询条件:QueryFilter `searchKey` + `searchValue`;顶部接入 `TenantScopeFilter`
|
||||
- 服务复用:`/api-user/wechat/config/list`、`/api-user/wechat/config`(POST/PUT/DELETE)
|
||||
9. 代码生成器页(/generator/list.html)
|
||||
- 源对标:`react-web/src/pages/system/Generator`
|
||||
- 新路径:`react-web-next/src/pages/system/Generator`
|
||||
- 组件化:页面容器 + ProTable;支持表名搜索与下载 zip
|
||||
- 服务复用:`/api-generator/generator/list`、`/api-generator/generator/code`
|
||||
10. 我的信息页(/system/myInfo.html)
|
||||
- 源对标:`react-web/src/pages/system/UserInfo`
|
||||
- 新路径:`react-web-next/src/pages/system/UserInfo`
|
||||
- 组件化:页面容器 + ProForm;右侧头像上传(`/api-file/files-anon`)
|
||||
- 服务复用:`/api-user/users/current`、`/api-user/users/saveOrUpdate`
|
||||
11. 订单管理页(/orders/order.html)
|
||||
- 源对标:`react-web/src/pages/orders/Order`
|
||||
- 新路径:`react-web-next/src/pages/orders/Order`
|
||||
- 组件化:页面容器 + ProTable;QueryFilter(订单编号/状态/支付类型);顶部接入 `TenantScopeFilter`
|
||||
- 服务复用:`/api-order/list`、`/api-order/update/order`
|
||||
12. 二维码管理页(/orders/qrcode.html)
|
||||
- 源对标:`react-web/src/pages/orders/Qrcode`
|
||||
- 新路径:`react-web-next/src/pages/orders/Qrcode`
|
||||
- 组件化拆分:`components/QrcodeForm`(新增/编辑复用)
|
||||
- 服务复用:`/api-order/qrcode`(分页/新增/修改)、`/api-order/qrcode/{id}`(删除)
|
||||
13. 景区管理页(/orders/tourism.html)
|
||||
- 源对标:`react-web/src/pages/orders/Tourism`
|
||||
- 新路径:`react-web-next/src/pages/orders/Tourism`
|
||||
- 组件化拆分:`components/TourismForm`(新增/编辑复用)
|
||||
- 服务复用:`/api-order/tourism`(分页/新增/修改/删除)
|
||||
14. 首页轮播页(/orders/homeCarousel.html)
|
||||
- 源对标:`react-web/src/pages/orders/HomeCarousel`
|
||||
- 新路径:`react-web-next/src/pages/orders/HomeCarousel`
|
||||
- 组件化拆分:`components/HomeCarouselForm`(新增/编辑复用)
|
||||
- 服务复用:`/api-order/home/carousel`(分页/新增/修改/删除)
|
||||
|
||||
## 待办(阶段二)
|
||||
- 系统模块迁移(如有新增);
|
||||
- 订单模块迁移(退款/统计/分账/视频模板/编辑任务/微信消息等);
|
||||
- 设备模块迁移(设备/分组/监控/运维等);
|
||||
- 日志/搜索等其它模块;
|
||||
- 页面权限点与菜单项细化;
|
||||
- 主题与暗黑模式可选支持;
|
||||
- 构建与部署脚本对齐。
|
||||
|
||||
> 每完成一页,请在此文档追加:来源页、目标页、接口、已知差异、回归结论。
|
||||
@@ -0,0 +1,28 @@
|
||||
# 前端迁移记录(增量)- 订单批次
|
||||
|
||||
本次在新工程 `zlt-web/react-web-next` 继续迁移并组件化以下页面:
|
||||
|
||||
1. 订单管理(/orders/order.html)
|
||||
- 页面:src/pages/orders/Order
|
||||
- 服务:src/services/orders.ts(order 列表)
|
||||
- 查询:订单编号、订单状态、支付类型
|
||||
- 统一接入:TenantScopeFilter
|
||||
|
||||
2. 二维码管理(/orders/qrcode.html)
|
||||
- 页面:src/pages/orders/Qrcode
|
||||
- 组件:src/pages/orders/Qrcode/components/QrcodeForm
|
||||
- 服务:src/services/orders.ts(qrcode 分页/新增/修改/删除)
|
||||
|
||||
3. 景区管理(/orders/tourism.html)
|
||||
- 页面:src/pages/orders/Tourism
|
||||
- 组件:src/pages/orders/Tourism/components/TourismForm
|
||||
- 服务:src/services/orders.ts(tourism 分页/新增/修改/删除)
|
||||
|
||||
4. 首页轮播(/orders/homeCarousel.html)
|
||||
- 页面:src/pages/orders/HomeCarousel
|
||||
- 组件:src/pages/orders/HomeCarousel/components/HomeCarouselForm
|
||||
- 服务:src/services/orders.ts(homeCarousel 分页/新增/修改/删除)
|
||||
|
||||
路由增量:config/routes.ts 已新增 orders 组下的上述路径。
|
||||
|
||||
说明:以上页面均采用“页面容器 + 组件(表单/列表) + 统一租户筛选”的结构编写,保持与旧项目接口兼容,界面风格与交互统一。
|
||||
@@ -0,0 +1,250 @@
|
||||
# 多租户层级使用指南(Tenant Hierarchy User Guide)
|
||||
|
||||
> 适用范围:本仓库已启用“基于租户层级”的数据隔离与权限控制方案。本文面向后端/前端开发者与运维人员,说明如何理解、使用与排查多租户层级能力。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标与整体方案
|
||||
|
||||
- 以“租户层级(父子关系)”为核心维度,实现查询范围自动下钻:
|
||||
- 管理端用户(BACKEND)可在选中锚点租户后,查询该租户及其所有子租户数据。
|
||||
- C 端用户(APP)只允许查询自身所属租户的数据,不跨租户。
|
||||
- 运行期自动解析“当前查询租户锚点”,统一在 MyBatis Plus 层通过拦截器改写 SQL,免去业务侧手动拼接 `tenant_id` 条件。
|
||||
- 支持“本次请求临时覆盖租户”“忽略层级过滤”等特殊场景。
|
||||
|
||||
---
|
||||
|
||||
## 2. 核心概念与模型
|
||||
|
||||
### 2.1 登录用户模型扩展
|
||||
|
||||
类 `com.central.common.model.LoginAppUser` 新增字段(已在登录时注入):
|
||||
- `company`:用户所属默认租户ID(等同历史的公司ID)。
|
||||
- `currentTenantId`:当前查询租户ID(可切换)。
|
||||
- `accessibleTenantIds`:可访问的租户ID列表(含子租户)。
|
||||
- `canSwitchTenant`:是否允许切换租户(管理员权限标识)。
|
||||
|
||||
用户类型(`APP`/`BACKEND`)存放在 `user.getAttributes().get("type")`,并在登录转换时注入:
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java:152`
|
||||
|
||||
### 2.2 租户锚点 Tenant Anchor
|
||||
|
||||
- “当前查询租户锚点”是生成 SQL 过滤的依据。
|
||||
- 解析优先级:`TenantQueryOverrideContext` 覆盖 > 持久化选择 > `currentTenantId` > `company`。
|
||||
|
||||
### 2.3 用户类型与权限
|
||||
|
||||
- 管理端用户(BACKEND):默认可切换租户(`canSwitchTenant=true`),范围为“当前锚点租户 + 所有子租户”。
|
||||
- C 端用户(APP):范围仅限“自身所属租户”,不可跨租户。
|
||||
- 超级管理员:用户名 `admin` 或 `mgnt`,不受任何租户限制。
|
||||
|
||||
---
|
||||
|
||||
## 3. 运行时解析流程
|
||||
|
||||
1) 解析登录用户(SecurityContext → LoginAppUser)
|
||||
- `LoginUserUtils.getUser(authentication)` 支持 `LoginAppUser` 与 `Jwt`(从 `details_user` claim 还原)。
|
||||
- 登录后由 `UserTenantInitializer` 初始化 `company/currentTenantId/accessibleTenantIds/canSwitchTenant`。
|
||||
- 代码:
|
||||
- 初始化入口:`zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java:187`
|
||||
- 初始化器:`zlt-commons/zlt-common-core/src/main/java/com/central/common/service/UserTenantInitializer.java`
|
||||
|
||||
2) 当前查询租户ID解析
|
||||
- 工具方法(推荐):`SecurityTenantUtils.getCurrentTenantId()`。
|
||||
- 优先读取 `UserTenantSelectionService` 的持久化选择(如 Redis/DB 自行实现)。
|
||||
- 回落到 `LoginAppUser.currentTenantId` 或 `company`。
|
||||
- 代码:`zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/SecurityTenantUtils.java:33`
|
||||
|
||||
3) 查询范围(含子租户)
|
||||
- `SecurityTenantUtils.getCurrentQueryTenantIds()`:
|
||||
- APP 用户 → 仅锚点租户。
|
||||
- 管理端用户 → 通过 `ITenantHierarchyService#getAllSubTenantIds` 递归获得所有子租户。
|
||||
|
||||
4) 租户上下文(兼容 ThreadLocal)
|
||||
- `LoginUserContextHolder.setCurrentTenant(tenantId)` 会同时设置 `TenantContextHolder`,兼容旧逻辑。
|
||||
|
||||
5) 本次请求强制覆盖
|
||||
- `TenantQueryOverrideContext.setTenantId(tenantId)` 仅对当前请求生效,优先于默认锚点。
|
||||
|
||||
---
|
||||
|
||||
## 4. SQL 改写与数据范围控制
|
||||
|
||||
MyBatis Plus 插件装配:`zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java`
|
||||
|
||||
- 当 `zlt.datascope.enabled=true`(默认开启)时:
|
||||
- 启用 `DataScopeInnerInterceptor`,由 `CombinedSqlHandler` 组合以下处理器生成 WHERE 条件:
|
||||
- `CreatorDataScopeSqlHandler`:按“创建人”维度控制(角色未授予 ALL 时追加 `creator_id = ?`)。
|
||||
- `TenantDataScopeSqlHandler`:按“租户层级”控制。
|
||||
- 默认拼接结果为:`(creator 条件) AND (tenant 条件)`。
|
||||
|
||||
- 当启用层级数据范围时,为避免冲突,不再叠加 MyBatis-Plus 的等值租户插件(`CustomTenantInterceptor`)。
|
||||
|
||||
- 租户列名:`TenantDataScopeSqlHandler` 默认使用 `tenant_id`。如果你的表列名不同,可自定义 `SqlHandler` Bean 替换,或统一使用 MyBatis-Plus 驼峰映射将实体 `tenantId` 映射到列 `tenant_id`。
|
||||
|
||||
- APP 用户与管理端的 SQL 形态:
|
||||
- APP 用户:`tenant_id = 'anchorTenant'`
|
||||
- 管理端用户:`tenant_id IN ('anchorTenant','child1','child2',...)`
|
||||
|
||||
- 超级管理员绕过:`SecurityTenantUtils.isSuperAdmin() == true` 时不追加租户条件。
|
||||
|
||||
- 调试 SQL:`zlt.datascope.enabled-sql-debug=true` 可打印改写后的 SQL(慎用于生产)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 后端使用姿势(代码片段)
|
||||
|
||||
- 获取当前租户ID:
|
||||
```java
|
||||
String tenantId = SecurityTenantUtils.getCurrentTenantId();
|
||||
```
|
||||
|
||||
- 获取当前查询范围(含子租户):
|
||||
```java
|
||||
List<String> tenantIds = SecurityTenantUtils.getCurrentQueryTenantIds();
|
||||
```
|
||||
|
||||
- 获取当前登录用户(推荐):
|
||||
```java
|
||||
LoginAppUser user = SecurityTenantUtils.getCurrentUser();
|
||||
```
|
||||
|
||||
- 切换当前租户(需具备切换权限):
|
||||
```java
|
||||
LoginUserContextHolder.setCurrentTenant("t-1001");
|
||||
```
|
||||
|
||||
- 重置为默认租户:
|
||||
```java
|
||||
LoginUserContextHolder.resetToDefaultTenant();
|
||||
```
|
||||
|
||||
- 本次请求临时覆盖查询租户(仅当前请求有效):
|
||||
```java
|
||||
TenantQueryOverrideContext.setTenantId("t-override");
|
||||
try {
|
||||
// 执行业务逻辑...
|
||||
} finally {
|
||||
TenantQueryOverrideContext.clear();
|
||||
}
|
||||
```
|
||||
|
||||
- 忽略层级过滤(方法/类上标注):
|
||||
```java
|
||||
@IgnoreTenantScope
|
||||
public List<?> crossTenantReport(...) { ... }
|
||||
```
|
||||
|
||||
- 判断身份:
|
||||
```java
|
||||
boolean isAdmin = SecurityTenantUtils.isSuperAdmin();
|
||||
boolean canSwitch = LoginUserContextHolder.isManagementUser();
|
||||
String userType = LoginUserContextHolder.getUserType(); // APP / BACKEND
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 前端与接口使用
|
||||
|
||||
用户侧租户切换与视图范围接口(`zlt-business/user-center` 提供):
|
||||
- 获取可访问租户树:`GET /tenant/accessible`
|
||||
- 切换当前查询租户:`POST /tenant/switch?tenantId=xxx`
|
||||
- 获取当前租户信息:`GET /tenant/current`
|
||||
- 获取当前查询范围统计:`GET /tenant/scope/stats`
|
||||
- 重置为默认租户:`POST /tenant/reset`
|
||||
|
||||
系统级租户管理接口(`TenantController`,用于平台管理):
|
||||
- 设置/获取/清除当前租户:`POST /tenant/set`、`GET /tenant/current`、`POST /tenant/clear`
|
||||
- 验证租户权限:`POST /tenant/validate`
|
||||
- 获取租户状态/统计:`GET /tenant/status`、`GET /tenant/statistics`
|
||||
- 创建/删除/更新租户:`POST /tenant/create`、`DELETE /tenant/{tenantId}`、`PUT /tenant/{tenantId}`
|
||||
|
||||
前端示例可参考:`zlt-web/react-web/src/main/frontend/src/services/tenant.ts`
|
||||
|
||||
> 说明:部分“/tenant/hierarchy/*”管理接口在前端中已预留,服务端实现位于 `ITenantHierarchyService`(业务侧可按需暴露对应 Controller)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 配置项说明(application.yml)
|
||||
|
||||
```yaml
|
||||
zlt:
|
||||
tenant:
|
||||
enable: false # 传统等值租户插件(与层级方案二选一,层级启用时建议保持 false)
|
||||
ignore-tables: # 不加租户条件的表
|
||||
- sys_user
|
||||
- sys_role_user
|
||||
- sys_role_menu
|
||||
ignore-sqls: # 不加租户条件的 SQL ID
|
||||
- com.central.user.mapper.SysRoleMapper.findAll
|
||||
datascope:
|
||||
enabled: true # 开启层级数据范围拦截
|
||||
enabled-sql-debug: false # 打印改写 SQL(开发调试用)
|
||||
include-tables: # 需要加权限控制的表,支持通配,"*" 表示全部
|
||||
- "*"
|
||||
ignore-tables: [] # 明确排除的表
|
||||
include-sqls: [] # 为空=所有SQL;非空=仅这些SQL加控制
|
||||
ignore-sqls: [] # 这些SQL不加控制(内置已忽略若干)
|
||||
creator-id-column-name: creator_id
|
||||
```
|
||||
|
||||
> 注意:业务表需要包含 `tenant_id` 字段(或通过映射确保能生成正确的列名)。
|
||||
|
||||
---
|
||||
|
||||
## 8. 常见问题与排查
|
||||
|
||||
- 查询不到数据?
|
||||
- 检查当前用户是否为 APP 用户(仅等值查询)。
|
||||
- 检查 `tenant_id` 是否正确写入数据。
|
||||
- 检查是否设置了不正确的 `TenantQueryOverrideContext`。
|
||||
- 开启 `zlt.datascope.enabled-sql-debug=true` 查看最终 SQL。
|
||||
|
||||
- 切换租户无效?
|
||||
- 管理端用户需具备切换权限(`canSwitchTenant=true`)。
|
||||
- 确认 `UserTenantSelectionService` 持久化是否实现并生效(否则只在本进程内生效)。
|
||||
|
||||
- 与“webApp”租户的关系?
|
||||
- 当 `TenantContextHolder = webApp` 时,传统等值租户插件会跳过租户过滤(平台级查询),但在层级模式下默认不启用该插件。
|
||||
|
||||
---
|
||||
|
||||
## 9. 相关类与路径索引
|
||||
|
||||
- 解析与上下文
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/SecurityTenantUtils.java`
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/context/LoginUserContextHolder.java`
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/context/TenantContextHolder.java`
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/context/TenantQueryOverrideContext.java`
|
||||
|
||||
- 登录与初始化
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java`
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/service/UserTenantInitializer.java`
|
||||
- `zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java`
|
||||
|
||||
- 租户层级服务
|
||||
- 接口:`zlt-commons/zlt-common-core/src/main/java/com/central/common/service/ITenantHierarchyService.java`
|
||||
- 实现:`zlt-business/user-center/src/main/java/com/central/user/service/impl/TenantHierarchyServiceImpl.java`
|
||||
- VO/实体:`Tenant`、`TenantInfo`、`TenantTreeNode`
|
||||
|
||||
- MyBatis Plus 拦截器
|
||||
- 装配:`zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java`
|
||||
- 处理器:`TenantDataScopeSqlHandler`、`CreatorDataScopeSqlHandler`、`CombinedSqlHandler`
|
||||
- 注解与 AOP:`@IgnoreTenantScope`、`TenantScopeAspect`
|
||||
|
||||
- 控制器(用户侧)
|
||||
- `zlt-business/user-center/src/main/java/com/central/user/controller/TenantSwitchController.java`
|
||||
- `zlt-business/user-center/src/main/java/com/central/user/controller/TenantController.java`
|
||||
|
||||
---
|
||||
|
||||
## 10. 快速验证
|
||||
|
||||
1) 启动网关与认证服务(或直接运行 user-center 模块)。
|
||||
2) 使用后台管理员账号登录(BACKEND),调用:
|
||||
- `GET /tenant/accessible` 获取可访问租户树。
|
||||
- `POST /tenant/switch?tenantId=<目标ID>` 切换租户。
|
||||
- 任意业务查询接口应自动携带 `tenant_id IN (...)` 条件(可开启 SQL Debug 验证)。
|
||||
3) 使用 APP 账号登录,重复上述步骤,观察查询仅限等值 `tenant_id = ...`。
|
||||
|
||||
如需进一步协助实现 `/tenant/hierarchy/*` 管理接口或自定义 SQL 处理器,请在 Issue 中说明具体诉求与表结构,我们可继续完善。
|
||||
@@ -0,0 +1,67 @@
|
||||
# 开发记录 - 多租户层级与后台租户管理
|
||||
|
||||
本文档用于记录已完成的工作事项与关键改动,便于后续按计划推进与审计。
|
||||
|
||||
## 一、改动概览
|
||||
|
||||
- 修复:`TenantSwitchController` 中误用 `LoginAppUser#getType()`。
|
||||
- 改为使用 `user.isCanSwitchTenant()` 判定是否可切换租户。
|
||||
- 同时修正一处日志格式问题。
|
||||
- 文件:
|
||||
- zlt-business/user-center/src/main/java/com/central/user/controller/TenantSwitchController.java:163
|
||||
- 新增:多租户层级使用说明文档。
|
||||
- 文件:
|
||||
- zlt-doc/多租户层级使用指南.md
|
||||
- 新增:后端“租户层级管理”控制器,供前端管理后台使用。
|
||||
- 路径前缀:`/tenant/hierarchy`
|
||||
- 接口:创建、更新、删除(软删)、列表、详情
|
||||
- 文件:
|
||||
- zlt-business/user-center/src/main/java/com/central/user/controller/TenantHierarchyController.java
|
||||
- 新增:接口调用集合以便联调与测试。
|
||||
- Postman:zlt-doc/postman/tenant-hierarchy.postman_collection.json
|
||||
- Thunder Client:zlt-doc/thunder/tenant-hierarchy-collection.json
|
||||
- 新增:前端管理后台“租户管理”页面(支持以机构树型添加租户)。
|
||||
- 页面:zlt-web/react-web/src/main/frontend/src/pages/system/TenantManage/index.tsx
|
||||
- 路由:在 `config/routes.ts` 新增 `/system/tenant.html` 指向上述页面
|
||||
|
||||
## 二、功能要点
|
||||
|
||||
1. 多租户层级运行规则
|
||||
- 管理端(BACKEND):基于当前锚点租户,范围为锚点 + 全部子租户。
|
||||
- C 端(APP):仅限自身租户。
|
||||
- 超管:admin/mgnt,绕过限制。
|
||||
- 详见:zlt-doc/多租户层级使用指南.md。
|
||||
|
||||
2. 后端层级管理接口(/tenant/hierarchy/*)
|
||||
- `POST /create`:创建租户,校验父子关系合法性。
|
||||
- `PUT /update`:更新租户,校验父子关系合法性。
|
||||
- `DELETE /delete?tenantId=`:软删除,禁止删除有子租户的节点。
|
||||
- `GET /list`:分页查询(当前服务返回 data 列表,total 先占位为当前页条数)。
|
||||
- `GET /detail/{tenantId}`:详情。
|
||||
|
||||
3. 前端管理后台 - 租户管理
|
||||
- 左侧“机构树”用于筛选父节点;右侧表格展示节点下租户列表。
|
||||
- “新建/编辑”表单提供 TreeSelect 选择上级机构(机构树型添加)。
|
||||
- 支持编辑、删除、刷新机构树,分页查询与状态筛选。
|
||||
- 依赖服务:`@/services/tenant`(已包含 create/update/delete/list/detail)。
|
||||
|
||||
## 三、影响范围与兼容性
|
||||
|
||||
- 现有登录态、上下文解析兼容:`LoginUserContextHolder` 与 `TenantContextHolder` 同步维护。
|
||||
- MyBatis-Plus 拦截器:层级数据范围启用时,不叠加等值租户插件,避免条件冲突。
|
||||
- 前端路由新增 `/system/tenant.html`,不影响既有菜单与页面;如需在菜单中展示名称,可在 i18n 或菜单配置中补充文案。
|
||||
|
||||
## 四、后续建议与待办
|
||||
|
||||
- 服务层 `getTenantList` 返回结构补充 total/分页元数据,前端可直接渲染精准分页。
|
||||
- 如需“全租户树”管理(跨根节点),可增加“全量树”接口或在后端放宽可访问范围。
|
||||
- 完善 `UserTenantSelectionService` 的持久化实现,优化锚点租户恢复体验。
|
||||
- 为租户管理页面补充权限点(如 `tenant:create/update/delete`)并在菜单/按钮上进行控制。
|
||||
|
||||
## 五、验收建议
|
||||
|
||||
- 使用 Postman/Thunder 集合验证 `/tenant/hierarchy/*` 接口可用性。
|
||||
- 管理端账号登录,在“租户管理”页面完成新增/编辑/删除/筛选等动作;新增时通过树选择上级机构。
|
||||
- 结合 `zlt.datascope.enabled-sql-debug=true` 验证实际查询 SQL 是否注入了正确的租户层级条件。
|
||||
|
||||
> 注:如需我继续完善分页 total、权限控制或菜单文案,请在 Issue 中告知具体需求。
|
||||
@@ -0,0 +1,875 @@
|
||||
# Go-Fly平台租户层级化重构实施指南
|
||||
|
||||
## 📋 项目概述
|
||||
|
||||
**项目名称**: 基于LoginUserContextHolder的租户层级化架构重构
|
||||
**技术栈**: Spring Boot 3.1.6 + MyBatis Plus + Java 17 + MySQL 8.0
|
||||
**重构目标**: 为现有租户体系增加父子层级关系,统一用户和租户上下文管理
|
||||
**预估工期**: 4周
|
||||
|
||||
## 🎯 重构目标
|
||||
|
||||
### 核心目标
|
||||
1. **租户层级化**: 支持集团→分公司→部门的多级层级结构
|
||||
2. **统一上下文管理**: LoginUserContextHolder统一管理用户和租户信息
|
||||
3. **权限精细化**: 管理员可查看子租户数据,普通用户仅查看自己租户
|
||||
4. **界面友好**: 提供租户选择器,用户明确当前数据查询范围
|
||||
5. **向下兼容**: 保持现有C端用户和业务逻辑完全不变
|
||||
|
||||
### 架构优化
|
||||
- **简化架构**: 逐步淘汰TenantContextHolder,统一使用LoginUserContextHolder
|
||||
- **功能增强**: 支持租户切换、多租户查询、权限控制
|
||||
- **微服务一致性**: JWT和Feign自动传递租户上下文
|
||||
|
||||
## 🏗️ 现状分析
|
||||
|
||||
### 当前架构
|
||||
```
|
||||
用户登录 → LoginUserContextHolder (用户信息)
|
||||
↓
|
||||
TenantContextHolder (租户信息) → CustomTenantInterceptor → SQL过滤
|
||||
```
|
||||
|
||||
### 目标架构
|
||||
```
|
||||
用户登录 → LoginUserContextHolder (用户+租户统一管理)
|
||||
↓
|
||||
租户权限计算 → 拦截器自动处理 → SQL过滤
|
||||
↓
|
||||
前端租户选择器 ↔ 租户切换API
|
||||
```
|
||||
|
||||
## 📊 数据库设计
|
||||
|
||||
### 租户层级关系表
|
||||
```sql
|
||||
CREATE TABLE `sys_tenant_hierarchy` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`tenant_id` VARCHAR(32) NOT NULL COMMENT '租户ID(对应现有company字段)',
|
||||
`tenant_name` VARCHAR(100) NOT NULL COMMENT '租户名称',
|
||||
`parent_tenant_id` VARCHAR(32) DEFAULT NULL COMMENT '父租户ID',
|
||||
`tenant_level` INT DEFAULT 1 COMMENT '租户层级(1=根租户)',
|
||||
`tenant_path` VARCHAR(1000) COMMENT '租户路径(/root/child/)',
|
||||
`tenant_type` VARCHAR(20) DEFAULT 'COMPANY' COMMENT '租户类型(GROUP/COMPANY/DEPARTMENT)',
|
||||
`tenant_code` VARCHAR(32) COMMENT '租户编码',
|
||||
`contact_person` VARCHAR(50) COMMENT '负责人',
|
||||
`contact_phone` VARCHAR(20) COMMENT '联系电话',
|
||||
`address` VARCHAR(255) COMMENT '地址',
|
||||
`description` TEXT COMMENT '租户描述',
|
||||
`status` TINYINT DEFAULT 1 COMMENT '状态(0:停用,1:启用)',
|
||||
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`creator_id` BIGINT COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_id` (`tenant_id`),
|
||||
INDEX `idx_parent_tenant` (`parent_tenant_id`),
|
||||
INDEX `idx_tenant_path` (`tenant_path`(255)),
|
||||
INDEX `idx_status` (`status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='租户层级关系表';
|
||||
```
|
||||
|
||||
### 数据迁移脚本
|
||||
```sql
|
||||
-- 步骤1: 从现有用户表提取租户数据
|
||||
INSERT INTO sys_tenant_hierarchy (tenant_id, tenant_name, tenant_level, tenant_path, tenant_type)
|
||||
SELECT DISTINCT
|
||||
u.company as tenant_id,
|
||||
CONCAT(u.company, '_租户') as tenant_name,
|
||||
1 as tenant_level,
|
||||
CONCAT('/', u.company, '/') as tenant_path,
|
||||
'COMPANY' as tenant_type
|
||||
FROM sys_user u
|
||||
WHERE u.company IS NOT NULL AND u.company != '' AND u.company != 'webApp';
|
||||
|
||||
-- 步骤2: 创建webApp超级租户
|
||||
INSERT INTO sys_tenant_hierarchy (tenant_id, tenant_name, tenant_level, tenant_path, tenant_type, description)
|
||||
VALUES ('webApp', '平台管理租户', 0, '/webApp/', 'PLATFORM', '系统管理专用租户');
|
||||
```
|
||||
|
||||
## 💻 核心代码实现
|
||||
|
||||
### 1. 扩展LoginAppUser模型
|
||||
```java
|
||||
/**
|
||||
* 扩展现有LoginAppUser,添加租户管理字段
|
||||
*/
|
||||
public class LoginAppUser extends User implements OAuth2AuthenticatedPrincipal {
|
||||
// ... 现有字段保持不变
|
||||
|
||||
/**
|
||||
* 用户所属租户ID(对应SysUser.company)
|
||||
*/
|
||||
private String company;
|
||||
|
||||
/**
|
||||
* 当前查询的租户ID(用户可切换)
|
||||
*/
|
||||
private String currentTenantId;
|
||||
|
||||
/**
|
||||
* 用户可访问的所有租户ID列表(包含子租户)
|
||||
*/
|
||||
private List<String> accessibleTenantIds;
|
||||
|
||||
/**
|
||||
* 是否允许切换租户(管理员权限)
|
||||
*/
|
||||
private boolean canSwitchTenant;
|
||||
|
||||
// getter/setter...
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 扩展LoginUserContextHolder
|
||||
```java
|
||||
/**
|
||||
* 扩展现有的LoginUserContextHolder,统一管理用户和租户信息
|
||||
*/
|
||||
public class LoginUserContextHolder {
|
||||
private static final ThreadLocal<LoginAppUser> CONTEXT = new TransmittableThreadLocal<>();
|
||||
|
||||
// === 现有方法保持完全不变 ===
|
||||
public static void setUser(LoginAppUser user) { CONTEXT.set(user); }
|
||||
public static LoginAppUser getUser() { return CONTEXT.get(); }
|
||||
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("用户无租户切换权限");
|
||||
}
|
||||
|
||||
if (!user.getAccessibleTenantIds().contains(tenantId)) {
|
||||
throw new SecurityException("无权限访问租户: " + tenantId);
|
||||
}
|
||||
|
||||
user.setCurrentTenantId(tenantId);
|
||||
log.debug("用户 {} 切换到租户 {}", user.getUsername(), tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前查询租户ID
|
||||
*/
|
||||
public static String getCurrentTenantId() {
|
||||
LoginAppUser user = getUser();
|
||||
if (user != null) {
|
||||
// 如果没有设置当前租户,返回用户默认租户
|
||||
return StringUtils.isNotEmpty(user.getCurrentTenantId())
|
||||
? user.getCurrentTenantId()
|
||||
: user.getCompany();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前查询范围的所有租户ID(当前租户+所有子租户)
|
||||
*/
|
||||
public static List<String> getCurrentQueryTenantIds() {
|
||||
String currentTenantId = getCurrentTenantId();
|
||||
if (StringUtils.isEmpty(currentTenantId)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
LoginAppUser user = getUser();
|
||||
|
||||
// C端用户只能查询自己的租户
|
||||
if (user != null && "APP".equals(user.getType())) {
|
||||
return Arrays.asList(currentTenantId);
|
||||
}
|
||||
|
||||
// 管理员用户可以查询当前租户及其所有子租户
|
||||
TenantHierarchyService tenantService = SpringContextHolder.getBean(TenantHierarchyService.class);
|
||||
return tenantService.getAllSubTenantIds(currentTenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否有访问指定租户的权限
|
||||
*/
|
||||
public static boolean hasTenantAccess(String tenantId) {
|
||||
LoginAppUser user = getUser();
|
||||
return user != null && user.getAccessibleTenantIds() != null
|
||||
&& user.getAccessibleTenantIds().contains(tenantId);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. TenantContextHolder兼容性处理
|
||||
```java
|
||||
/**
|
||||
* 保持兼容性的TenantContextHolder,委托给LoginUserContextHolder
|
||||
*/
|
||||
public class TenantContextHolder {
|
||||
private static final ThreadLocal<String> CONTEXT = new TransmittableThreadLocal<>();
|
||||
|
||||
@Deprecated
|
||||
public static void setTenant(String tenant) {
|
||||
CONTEXT.set(tenant);
|
||||
// 同时更新LoginUserContextHolder中的租户信息
|
||||
try {
|
||||
LoginUserContextHolder.setCurrentTenant(tenant);
|
||||
} catch (Exception e) {
|
||||
// 兼容性处理:如果设置失败,仍然保持原有逻辑
|
||||
log.debug("无法通过LoginUserContextHolder设置租户,使用原有逻辑: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static String getTenant() {
|
||||
// 优先从LoginUserContextHolder获取
|
||||
String tenantFromUser = LoginUserContextHolder.getCurrentTenantId();
|
||||
if (StringUtils.isNotEmpty(tenantFromUser)) {
|
||||
return tenantFromUser;
|
||||
}
|
||||
// 降级到原有逻辑
|
||||
return CONTEXT.get();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static void clear() {
|
||||
CONTEXT.remove();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 租户层级管理服务
|
||||
```java
|
||||
/**
|
||||
* 租户层级管理服务
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class TenantHierarchyServiceImpl implements TenantHierarchyService {
|
||||
|
||||
@Autowired
|
||||
private TenantHierarchyMapper tenantHierarchyMapper;
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
private static final String CACHE_KEY_PREFIX = "tenant:sub:";
|
||||
|
||||
/**
|
||||
* 获取租户的所有子租户ID(包含自身,带缓存)
|
||||
*/
|
||||
@Override
|
||||
@Cacheable(value = "tenant:hierarchy", key = "#parentTenantId")
|
||||
public List<String> getAllSubTenantIds(String parentTenantId) {
|
||||
if (StringUtils.isEmpty(parentTenantId)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
// 数据库查询子租户
|
||||
List<String> subTenantIds = tenantHierarchyMapper.selectSubTenantIds(parentTenantId);
|
||||
subTenantIds.add(0, parentTenantId); // 添加自身到首位
|
||||
|
||||
log.debug("查询子租户列表: parent={}, count={}", parentTenantId, subTenantIds.size());
|
||||
return subTenantIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建租户树结构
|
||||
*/
|
||||
@Override
|
||||
public List<TenantTreeNode> buildTenantTree(List<String> tenantIds) {
|
||||
if (tenantIds == null || tenantIds.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
// 获取租户详细信息
|
||||
List<TenantHierarchy> tenants = tenantHierarchyMapper.selectByTenantIds(tenantIds);
|
||||
|
||||
// 构建树形结构
|
||||
Map<String, TenantTreeNode> nodeMap = new HashMap<>();
|
||||
List<TenantTreeNode> rootNodes = new ArrayList<>();
|
||||
|
||||
// 创建所有节点
|
||||
for (TenantHierarchy tenant : tenants) {
|
||||
TenantTreeNode node = TenantTreeNode.builder()
|
||||
.tenantId(tenant.getTenantId())
|
||||
.tenantName(tenant.getTenantName())
|
||||
.tenantType(tenant.getTenantType())
|
||||
.parentTenantId(tenant.getParentTenantId())
|
||||
.children(new ArrayList<>())
|
||||
.build();
|
||||
nodeMap.put(tenant.getTenantId(), node);
|
||||
}
|
||||
|
||||
// 构建父子关系
|
||||
for (TenantTreeNode node : nodeMap.values()) {
|
||||
if (StringUtils.isEmpty(node.getParentTenantId())) {
|
||||
rootNodes.add(node);
|
||||
} else {
|
||||
TenantTreeNode parent = nodeMap.get(node.getParentTenantId());
|
||||
if (parent != null) {
|
||||
parent.getChildren().add(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rootNodes;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 改造CustomTenantInterceptor
|
||||
```java
|
||||
/**
|
||||
* 基于LoginUserContextHolder的租户拦截器
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class UserContextTenantInterceptor extends TenantLineInnerInterceptor {
|
||||
|
||||
public UserContextTenantInterceptor(TenantLineHandler tenantLineHandler,
|
||||
List<String> ignoreSqls, List<String> noIgnoreSqls) {
|
||||
super(tenantLineHandler);
|
||||
this.ignoreSqls = ignoreSqls;
|
||||
this.noIgnoreSqls = noIgnoreSqls;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter,
|
||||
RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
|
||||
throws SQLException {
|
||||
|
||||
String msId = ms.getId();
|
||||
log.debug("租户拦截器处理SQL: {}", msId);
|
||||
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
if (user == null) {
|
||||
log.debug("用户未登录,跳过租户过滤: {}", msId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 系统管理员跳过
|
||||
if (isSuperAdmin(user)) {
|
||||
log.debug("系统管理员权限,跳过租户过滤: {}", msId);
|
||||
return;
|
||||
}
|
||||
|
||||
// webApp租户特殊处理
|
||||
String currentTenant = LoginUserContextHolder.getCurrentTenantId();
|
||||
if ("webApp".equals(currentTenant)) {
|
||||
log.debug("webApp租户,跳过租户过滤: {}", msId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 忽略的SQL跳过
|
||||
if (isIgnoreMappedStatement(msId)) {
|
||||
log.debug("SQL {} 在忽略列表中,跳过租户过滤", msId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 租户为空时的处理
|
||||
if (StringUtils.isEmpty(currentTenant)) {
|
||||
log.warn("用户租户信息为空,拒绝数据访问: user={}, sql={}", user.getUsername(), msId);
|
||||
throw new SecurityException("缺少租户权限信息");
|
||||
}
|
||||
|
||||
// 执行租户过滤
|
||||
log.debug("SQL {} 执行租户过滤,当前租户: {}", msId, currentTenant);
|
||||
super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Expression getTenantId() {
|
||||
// 直接从LoginUserContextHolder获取当前租户
|
||||
String currentTenantId = LoginUserContextHolder.getCurrentTenantId();
|
||||
|
||||
if (StringUtils.isEmpty(currentTenantId)) {
|
||||
throw new SecurityException("无法获取当前租户信息");
|
||||
}
|
||||
|
||||
return new StringValue(currentTenantId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTenantIdColumn() {
|
||||
return "tenant_id"; // 保持使用原有字段名
|
||||
}
|
||||
|
||||
private boolean isSuperAdmin(LoginAppUser user) {
|
||||
return "admin".equals(user.getUsername()) || "mgnt".equals(user.getUsername());
|
||||
}
|
||||
|
||||
private boolean isIgnoreMappedStatement(String msId) {
|
||||
return ignoreSqls.stream().anyMatch(sql -> sql.equalsIgnoreCase(msId));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 6. 租户切换API
|
||||
```java
|
||||
/**
|
||||
* 租户切换管理接口
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/tenant")
|
||||
@Tag(name = "租户管理")
|
||||
@Slf4j
|
||||
public class TenantSwitchController {
|
||||
|
||||
@Autowired
|
||||
private TenantHierarchyService tenantHierarchyService;
|
||||
|
||||
/**
|
||||
* 获取用户可访问的租户树
|
||||
*/
|
||||
@GetMapping("/accessible")
|
||||
@Operation(summary = "获取可访问租户列表")
|
||||
public Result<List<TenantTreeNode>> getAccessibleTenants() {
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
|
||||
if (!user.isCanSwitchTenant()) {
|
||||
return Result.failed("用户无租户切换权限");
|
||||
}
|
||||
|
||||
List<String> accessibleTenantIds = user.getAccessibleTenantIds();
|
||||
List<TenantTreeNode> tenantTree = tenantHierarchyService.buildTenantTree(accessibleTenantIds);
|
||||
|
||||
return Result.succeed(tenantTree);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换当前查询租户
|
||||
*/
|
||||
@PostMapping("/switch")
|
||||
@Operation(summary = "切换当前查询租户")
|
||||
public Result<Void> switchTenant(@RequestParam String tenantId) {
|
||||
try {
|
||||
// 直接使用LoginUserContextHolder的方法
|
||||
LoginUserContextHolder.setCurrentTenant(tenantId);
|
||||
|
||||
log.info("用户 {} 切换到租户 {}",
|
||||
LoginUserContextHolder.getUser().getUsername(), tenantId);
|
||||
|
||||
return Result.succeed();
|
||||
} catch (SecurityException e) {
|
||||
log.warn("租户切换失败: {}", e.getMessage());
|
||||
return Result.failed(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前租户信息
|
||||
*/
|
||||
@GetMapping("/current")
|
||||
@Operation(summary = "获取当前租户信息")
|
||||
public Result<TenantInfo> getCurrentTenant() {
|
||||
String currentTenantId = LoginUserContextHolder.getCurrentTenantId();
|
||||
|
||||
if (StringUtils.isEmpty(currentTenantId)) {
|
||||
return Result.failed("未获取到当前租户信息");
|
||||
}
|
||||
|
||||
TenantInfo tenantInfo = tenantHierarchyService.getTenantInfo(currentTenantId);
|
||||
return Result.succeed(tenantInfo);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 7. 用户登录时租户信息初始化
|
||||
```java
|
||||
/**
|
||||
* 用户登录时初始化租户信息
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class UserTenantInitializer {
|
||||
|
||||
@Autowired
|
||||
private TenantHierarchyService tenantHierarchyService;
|
||||
|
||||
/**
|
||||
* 在用户登录成功后初始化租户信息
|
||||
*/
|
||||
public void initializeUserTenantInfo(LoginAppUser user) {
|
||||
String userTenantId = user.getCompany();
|
||||
|
||||
if (StringUtils.isEmpty(userTenantId)) {
|
||||
log.warn("用户 {} 未分配租户", user.getUsername());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 判断用户类型和权限
|
||||
boolean canSwitchTenant = isManagementUser(user);
|
||||
user.setCanSwitchTenant(canSwitchTenant);
|
||||
|
||||
if (canSwitchTenant) {
|
||||
// 管理员用户:获取可访问的所有租户(当前租户+子租户)
|
||||
List<String> accessibleTenants = tenantHierarchyService.getAllSubTenantIds(userTenantId);
|
||||
user.setAccessibleTenantIds(accessibleTenants);
|
||||
|
||||
log.info("管理员用户 {} 可访问 {} 个租户", user.getUsername(), accessibleTenants.size());
|
||||
} else {
|
||||
// C端用户:只能访问自己的租户
|
||||
user.setAccessibleTenantIds(Arrays.asList(userTenantId));
|
||||
}
|
||||
|
||||
// 设置默认当前租户
|
||||
user.setCurrentTenantId(userTenantId);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("初始化用户租户信息失败: userId={}, error={}", user.getId(), e.getMessage());
|
||||
// 降级处理:设置基本信息
|
||||
user.setAccessibleTenantIds(Arrays.asList(userTenantId));
|
||||
user.setCurrentTenantId(userTenantId);
|
||||
user.setCanSwitchTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为管理用户
|
||||
*/
|
||||
private boolean isManagementUser(LoginAppUser user) {
|
||||
// 根据用户类型判断:BACKEND用户为管理员,APP用户为C端用户
|
||||
return "BACKEND".equals(user.getType());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🎨 前端实现
|
||||
|
||||
### 租户选择器组件
|
||||
```jsx
|
||||
/**
|
||||
* 租户选择器组件
|
||||
*/
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { TreeSelect, Space, Typography, Tag } from 'antd';
|
||||
import { BuildOutlined, SwapOutlined } from '@ant-design/icons';
|
||||
import { tenantApi } from '@/services/tenant';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const TenantSelector = ({
|
||||
onChange,
|
||||
placeholder = "选择查询租户范围",
|
||||
showCurrentInfo = true,
|
||||
style = { width: 300 }
|
||||
}) => {
|
||||
const [tenantTree, setTenantTree] = useState([]);
|
||||
const [currentTenant, setCurrentTenant] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [canSwitch, setCanSwitch] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadTenantData();
|
||||
}, []);
|
||||
|
||||
const loadTenantData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// 并行加载可访问租户和当前租户信息
|
||||
const [accessibleResult, currentResult] = await Promise.all([
|
||||
tenantApi.getAccessibleTenants(),
|
||||
tenantApi.getCurrentTenant()
|
||||
]);
|
||||
|
||||
if (accessibleResult.success) {
|
||||
const treeData = buildTreeData(accessibleResult.data);
|
||||
setTenantTree(treeData);
|
||||
setCanSwitch(accessibleResult.data.length > 1);
|
||||
}
|
||||
|
||||
if (currentResult.success) {
|
||||
setCurrentTenant(currentResult.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载租户数据失败:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const buildTreeData = (tenants) => {
|
||||
return tenants.map(tenant => ({
|
||||
title: (
|
||||
<Space>
|
||||
<BuildOutlined />
|
||||
<span>{tenant.tenantName}</span>
|
||||
<Tag size="small" color={getTenantTypeColor(tenant.tenantType)}>
|
||||
{tenant.tenantType}
|
||||
</Tag>
|
||||
</Space>
|
||||
),
|
||||
value: tenant.tenantId,
|
||||
key: tenant.tenantId,
|
||||
children: tenant.children ? buildTreeData(tenant.children) : undefined
|
||||
}));
|
||||
};
|
||||
|
||||
const getTenantTypeColor = (type) => {
|
||||
const colorMap = {
|
||||
'GROUP': 'purple',
|
||||
'COMPANY': 'blue',
|
||||
'DEPARTMENT': 'green'
|
||||
};
|
||||
return colorMap[type] || 'default';
|
||||
};
|
||||
|
||||
const handleTenantChange = async (tenantId) => {
|
||||
if (!tenantId) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await tenantApi.switchTenant(tenantId);
|
||||
if (result.success) {
|
||||
// 更新当前租户信息
|
||||
const currentResult = await tenantApi.getCurrentTenant();
|
||||
if (currentResult.success) {
|
||||
setCurrentTenant(currentResult.data);
|
||||
}
|
||||
|
||||
// 通知父组件
|
||||
onChange?.(tenantId);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('切换租户失败:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!canSwitch) {
|
||||
// 不能切换租户时显示当前租户信息
|
||||
return showCurrentInfo && currentTenant ? (
|
||||
<Space>
|
||||
<Text type="secondary">当前租户:</Text>
|
||||
<Tag icon={<BuildOutlined />} color="blue">
|
||||
{currentTenant.tenantName}
|
||||
</Tag>
|
||||
</Space>
|
||||
) : null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Space direction="vertical" size="small">
|
||||
{showCurrentInfo && currentTenant && (
|
||||
<Space>
|
||||
<Text type="secondary">数据范围:</Text>
|
||||
<Tag icon={<BuildOutlined />} color="blue">
|
||||
{currentTenant.tenantName}
|
||||
</Tag>
|
||||
</Space>
|
||||
)}
|
||||
|
||||
<TreeSelect
|
||||
style={style}
|
||||
value={currentTenant?.tenantId}
|
||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||
treeData={tenantTree}
|
||||
placeholder={placeholder}
|
||||
treeDefaultExpandAll
|
||||
onChange={handleTenantChange}
|
||||
allowClear={false}
|
||||
loading={loading}
|
||||
suffixIcon={<SwapOutlined />}
|
||||
showSearch
|
||||
treeNodeFilterProp="title"
|
||||
/>
|
||||
</Space>
|
||||
);
|
||||
};
|
||||
|
||||
export default TenantSelector;
|
||||
```
|
||||
|
||||
## 🚀 分步实施计划
|
||||
|
||||
### 步骤1:数据库和实体层(2天)✅ 已完成
|
||||
**任务**:
|
||||
- [x] 创建sys_tenant_hierarchy表
|
||||
- [x] 执行数据迁移脚本
|
||||
- [x] 创建实体类:Tenant、TenantTreeNode、TenantInfo
|
||||
|
||||
**验收标准**:
|
||||
- 表创建成功,索引生效
|
||||
- 现有租户数据完整迁移
|
||||
- 实体类映射正确
|
||||
|
||||
**完成情况**:
|
||||
- ✅ 已创建tenant-hierarchy-tables.sql表结构脚本
|
||||
- ✅ 已创建tenant-hierarchy-data-migration.sql数据迁移脚本
|
||||
- ✅ 已创建Tenant.java实体类
|
||||
- ✅ 已创建TenantTreeNode.java树形节点VO
|
||||
- ✅ 已创建TenantInfo.java租户信息VO
|
||||
|
||||
### 步骤2:服务层和API(3天)✅ 已完成
|
||||
**任务**:
|
||||
- [x] 实现TenantHierarchyService服务
|
||||
- [x] 创建TenantHierarchyMapper
|
||||
- [x] 实现TenantSwitchController API
|
||||
- [ ] 创建租户管理页面
|
||||
|
||||
**验收标准**:
|
||||
- 租户增删改查功能正常
|
||||
- 树形查询性能满足要求
|
||||
- API接口文档完整
|
||||
|
||||
**完成情况**:
|
||||
- ✅ 已创建ITenantHierarchyService接口
|
||||
- ✅ 已实现TenantHierarchyServiceImpl服务类,包含缓存、事务管理
|
||||
- ✅ 已创建TenantHierarchyMapper,支持复杂查询和分页
|
||||
- ✅ 已实现TenantSwitchController API,提供租户切换功能
|
||||
- 🔄 租户管理页面待后续实现
|
||||
|
||||
### 步骤3:用户租户关联(2天)✅ 已完成
|
||||
**任务**:
|
||||
- [x] 扩展LoginAppUser模型
|
||||
- [x] 实现UserTenantInitializer
|
||||
- [x] 用户登录时租户信息初始化
|
||||
|
||||
**验收标准**:
|
||||
- 用户登录后正确获得租户权限
|
||||
- 管理员和普通用户权限区分正确
|
||||
|
||||
**完成情况**:
|
||||
- ✅ 已扩展LoginAppUser模型,添加company、currentTenantId、accessibleTenantIds、canSwitchTenant字段
|
||||
- ✅ 已实现UserTenantInitializer组件,支持根据用户类型自动计算租户权限
|
||||
- ✅ 已修改LoginUserUtils.getLoginAppUser方法,集成租户初始化逻辑
|
||||
- ✅ 支持降级处理,租户功能异常时不影响用户登录
|
||||
|
||||
### 步骤4:前端组件(2.5天)✅ 已完成
|
||||
**任务**:
|
||||
- [x] 开发TenantSelector组件
|
||||
- [x] 实现租户切换功能
|
||||
- [x] 在主要管理页面集成组件
|
||||
|
||||
**验收标准**:
|
||||
- 租户选择器功能完整
|
||||
- 切换租户后数据正确刷新
|
||||
- 界面友好,用户体验良好
|
||||
|
||||
**完成情况**:
|
||||
- ✅ 已创建TenantSelector React组件,支持树形结构展示
|
||||
- ✅ 已实现租户切换功能,包含权限验证和状态管理
|
||||
- ✅ 已创建TenantExample示例页面,演示组件集成方式
|
||||
- ✅ 支持管理员和普通用户的不同展示模式
|
||||
|
||||
### 步骤5:上下文统一和拦截器(3天)✅ 已完成
|
||||
**任务**:
|
||||
- [x] 扩展LoginUserContextHolder
|
||||
- [x] 改造CustomTenantInterceptor
|
||||
- [x] TenantContextHolder兼容性处理
|
||||
- [x] 微服务上下文传递
|
||||
|
||||
**验收标准**:
|
||||
- 所有功能通过LoginUserContextHolder管理
|
||||
- 拦截器正确处理租户过滤
|
||||
- 现有功能完全兼容
|
||||
|
||||
**完成情况**:
|
||||
- ✅ 已扩展LoginUserContextHolder,添加租户管理功能
|
||||
- ✅ 已创建SpringContextHolder工具类,解决循环依赖问题
|
||||
- ✅ 已改造CustomTenantInterceptor,使用新的LoginUserContextHolder
|
||||
- ✅ 保持TenantContextHolder兼容性,避免影响现有代码
|
||||
|
||||
### 步骤6:测试和部署(2.5天)
|
||||
**任务**:
|
||||
- [ ] 单元测试和集成测试
|
||||
- [ ] 性能测试和优化
|
||||
- [ ] 生产环境部署
|
||||
|
||||
**验收标准**:
|
||||
- 所有测试用例通过
|
||||
- 性能指标满足要求
|
||||
- 生产环境稳定运行
|
||||
|
||||
## 🔧 配置说明
|
||||
|
||||
### 应用配置
|
||||
```yaml
|
||||
# application.yml
|
||||
tenant:
|
||||
cache:
|
||||
ttl: 3600 # 租户缓存过期时间(秒)
|
||||
prefix: "tenant:" # 缓存key前缀
|
||||
|
||||
security:
|
||||
super-admin-users: # 系统管理员用户列表
|
||||
- admin
|
||||
- mgnt
|
||||
|
||||
query:
|
||||
default-include-sub: true # 默认是否包含子租户查询
|
||||
max-depth: 10 # 最大层级深度限制
|
||||
|
||||
spring:
|
||||
cache:
|
||||
redis:
|
||||
time-to-live: 3600s
|
||||
```
|
||||
|
||||
### 拦截器配置
|
||||
```java
|
||||
@Configuration
|
||||
@EnableConfigurationProperties({TenantProperties.class})
|
||||
public class TenantInterceptorConfig {
|
||||
|
||||
@Bean
|
||||
public TenantLineInnerInterceptor tenantInterceptor(TenantProperties properties) {
|
||||
return new UserContextTenantInterceptor(
|
||||
new DefaultTenantLineHandler(),
|
||||
properties.getIgnoreSqls(),
|
||||
properties.getNoIgnoreSqls()
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 📈 性能优化
|
||||
|
||||
### 缓存策略
|
||||
```java
|
||||
@Cacheable(value = "tenant:hierarchy", key = "#parentTenantId")
|
||||
public List<String> getAllSubTenantIds(String parentTenantId) {
|
||||
// 实现缓存的子租户查询
|
||||
}
|
||||
```
|
||||
|
||||
### 索引优化
|
||||
```sql
|
||||
-- 优化租户路径查询
|
||||
CREATE INDEX idx_tenant_hierarchy_path_status ON sys_tenant_hierarchy(tenant_path(255), status);
|
||||
|
||||
-- 优化父子关系查询
|
||||
CREATE INDEX idx_tenant_hierarchy_parent_status ON sys_tenant_hierarchy(parent_tenant_id, status);
|
||||
```
|
||||
|
||||
## 🔒 安全考虑
|
||||
|
||||
1. **权限边界**:严格校验用户访问租户的权限
|
||||
2. **数据隔离**:确保用户只能访问授权的租户数据
|
||||
3. **日志审计**:记录所有租户切换操作
|
||||
4. **异常处理**:租户权限异常时安全降级
|
||||
|
||||
## 📝 注意事项
|
||||
|
||||
1. **兼容性**:保持现有C端用户逻辑完全不变
|
||||
2. **渐进式迁移**:可以分步骤实施,每步独立验证
|
||||
3. **数据备份**:重要操作前做好数据备份
|
||||
4. **测试充分**:特别关注权限边界和数据隔离测试
|
||||
|
||||
## 🎯 预期收益
|
||||
|
||||
✅ **管理效率提升**:支持集团化管理,层级权限清晰
|
||||
✅ **用户体验优化**:界面友好,操作直观
|
||||
✅ **架构简化**:统一用户和租户上下文管理
|
||||
✅ **扩展性增强**:支持未来复杂的权限模型扩展
|
||||
✅ **完全兼容**:现有功能和用户不受影响
|
||||
|
||||
---
|
||||
|
||||
**总结**:本重构方案通过扩展LoginUserContextHolder统一管理用户和租户信息,实现了租户层级化管理,同时保持了100%的向下兼容性。整个方案设计简洁、实施风险低、扩展性强,是一个可靠的企业级解决方案。
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -44,7 +44,7 @@ public class Oauth2ServerAuthSuccessHandler implements ServerAuthenticationSucce
|
||||
}
|
||||
|
||||
headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
|
||||
headerValues.add(SecurityConstants.TENANT_HEADER, (String)claims.get(SecurityConstants.CLIENT_ID));
|
||||
// 不再注入 x-tenant-header,租户从 Authorization 解析
|
||||
headerValues.add(SecurityConstants.ACCOUNT_TYPE_HEADER, (String)claims.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,202 +1,202 @@
|
||||
spring:
|
||||
cloud:
|
||||
gateway:
|
||||
discovery:
|
||||
locator:
|
||||
lowerCaseServiceId: true
|
||||
enabled: true
|
||||
routes:
|
||||
- id: auth
|
||||
uri: lb://uaa-server
|
||||
predicates:
|
||||
- Path=/api-uaa/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- PreserveHostHeader
|
||||
- id: auth-login-page
|
||||
uri: lb://uaa-server
|
||||
predicates:
|
||||
- Path=/login.html
|
||||
filters:
|
||||
- PreserveHostHeader
|
||||
- id: auth-login-process
|
||||
uri: lb://uaa-server
|
||||
predicates:
|
||||
- Path=/user/login
|
||||
filters:
|
||||
- PreserveHostHeader
|
||||
- id: auth-login-token
|
||||
uri: lb://uaa-server
|
||||
predicates:
|
||||
- Path=/oauth/token
|
||||
filters:
|
||||
- PreserveHostHeader
|
||||
- id: auth-login-authorize
|
||||
uri: lb://uaa-server
|
||||
predicates:
|
||||
- Path=/oauth/authorize
|
||||
filters:
|
||||
- PreserveHostHeader
|
||||
- id: auth-check-process
|
||||
uri: lb://uaa-server
|
||||
predicates:
|
||||
- Path=/oauth/check_token
|
||||
filters:
|
||||
- PreserveHostHeader
|
||||
- id: user
|
||||
uri: lb://user-center
|
||||
predicates:
|
||||
- Path=/api-user/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: file
|
||||
uri: lb://file-center
|
||||
predicates:
|
||||
- Path=/api-file/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: log
|
||||
uri: lb://log-center
|
||||
predicates:
|
||||
- Path=/api-log/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: generator
|
||||
uri: lb://code-generator
|
||||
predicates:
|
||||
- Path=/api-generator/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: search
|
||||
uri: lb://search-center
|
||||
predicates:
|
||||
- Path=/api-search/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: device
|
||||
uri: lb://device-center
|
||||
predicates:
|
||||
- Path=/api-device/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: order
|
||||
uri: lb://order-center
|
||||
predicates:
|
||||
- Path=/api-order/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: coupon
|
||||
uri: lb://coupon-center
|
||||
predicates:
|
||||
- Path=/api-coupon/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
# sentinel:
|
||||
# datasource.ds1.nacos:
|
||||
# server-addr: ${spring.cloud.nacos.server-addr}
|
||||
# data-id: ${spring.application.name}-sentinel-gw-flow
|
||||
# group-id: DEFAULT_GROUP
|
||||
# ruleType: gw-flow
|
||||
# filter:
|
||||
# enabled: true
|
||||
|
||||
knife4j:
|
||||
gateway:
|
||||
enabled: true
|
||||
strategy: manual
|
||||
routes:
|
||||
- name: 用户服务
|
||||
service-name: user-center
|
||||
url: /api-user/v3/api-docs/default
|
||||
context-path: /api-user
|
||||
- name: 授权服务
|
||||
service-name: uaa-server
|
||||
url: /api-uaa/v3/api-docs/default
|
||||
context-path: /api-uaa
|
||||
- name: 搜索服务
|
||||
service-name: search-center
|
||||
url: /api-search/v3/api-docs/default
|
||||
context-path: /api-search
|
||||
- name: 文件服务
|
||||
service-name: file-center
|
||||
url: /api-file/v3/api-docs/default
|
||||
context-path: /api-file
|
||||
- name: 设备服务
|
||||
service-name: device-center
|
||||
url: /api-device/v3/api-docs/default
|
||||
context-path: /api-device
|
||||
- name: 订单服务
|
||||
service-name: order-center
|
||||
url: /api-order/v3/api-docs/default
|
||||
context-path: /api-order
|
||||
- name: 设备运维服务
|
||||
service-name: device-ops-center
|
||||
url: /api-device-ops/v3/api-docs/default
|
||||
context-path: /api-device-ops
|
||||
- name: 优惠券服务
|
||||
service-name: coupon-center
|
||||
url: /api-coupon/v3/api-docs/default
|
||||
context-path: /api-coupon
|
||||
|
||||
zlt:
|
||||
security:
|
||||
ignore:
|
||||
# 忽略认证的地址
|
||||
httpUrls: >
|
||||
/api-uaa/oauth/**,
|
||||
/api-uaa/validata/**,
|
||||
/api-uaa/css/**,
|
||||
/api-uaa/images/**,
|
||||
/api-uaa/js/**,
|
||||
/login.html,
|
||||
/user/login, /oauth/authorize,
|
||||
/api-uaa/tokens/key,
|
||||
/*/v3/api-docs/**,
|
||||
/api-order/files/path,
|
||||
/api-order/update,
|
||||
/api-order/queue/first,
|
||||
/api-order/wechat/**,
|
||||
/api-order/home/carousel/app,
|
||||
/api-order/device/status,
|
||||
/api-order/token/callback,
|
||||
/api-device/stream-urls,
|
||||
/api-device/token/query,
|
||||
/api-order/user/temp,
|
||||
/api-file/file/expires,
|
||||
/api-order/refund/auto,
|
||||
/api-order/files/exists/**,
|
||||
/api-coupon/coupon/ctrip/create,
|
||||
/api-order/tourism/nearby,
|
||||
/api-coupon/ctrip/query/**,
|
||||
/api-coupon/ctrip/refund/**,
|
||||
/api-coupon/ctrip/pay/**
|
||||
auth:
|
||||
urlPermission:
|
||||
#是否开启url级别权限
|
||||
enable: false
|
||||
#配置只进行登录认证,不进行url权限认证的api
|
||||
ignoreUrls: >
|
||||
/api-user/menus/current,
|
||||
/api-user/users/current,
|
||||
/api-log/requestStat
|
||||
#白名单
|
||||
includeClientIds:
|
||||
- webApp
|
||||
renew:
|
||||
#是否开启token自动续签(目前只有redis实现)
|
||||
enable: true
|
||||
#白名单
|
||||
includeClientIds:
|
||||
- webApp
|
||||
gateway:
|
||||
#网关动态路由
|
||||
dynamicRoute:
|
||||
enabled: true
|
||||
|
||||
hystrix:
|
||||
command:
|
||||
default:
|
||||
execution:
|
||||
isolation:
|
||||
thread:
|
||||
timeoutInMilliseconds: 1000
|
||||
#spring:
|
||||
# cloud:
|
||||
# gateway:
|
||||
# discovery:
|
||||
# locator:
|
||||
# lowerCaseServiceId: true
|
||||
# enabled: true
|
||||
# routes:
|
||||
# - id: auth
|
||||
# uri: lb://uaa-server
|
||||
# predicates:
|
||||
# - Path=/api-uaa/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - PreserveHostHeader
|
||||
# - id: auth-login-page
|
||||
# uri: lb://uaa-server
|
||||
# predicates:
|
||||
# - Path=/login.html
|
||||
# filters:
|
||||
# - PreserveHostHeader
|
||||
# - id: auth-login-process
|
||||
# uri: lb://uaa-server
|
||||
# predicates:
|
||||
# - Path=/user/login
|
||||
# filters:
|
||||
# - PreserveHostHeader
|
||||
# - id: auth-login-token
|
||||
# uri: lb://uaa-server
|
||||
# predicates:
|
||||
# - Path=/oauth/token
|
||||
# filters:
|
||||
# - PreserveHostHeader
|
||||
# - id: auth-login-authorize
|
||||
# uri: lb://uaa-server
|
||||
# predicates:
|
||||
# - Path=/oauth/authorize
|
||||
# filters:
|
||||
# - PreserveHostHeader
|
||||
# - id: auth-check-process
|
||||
# uri: lb://uaa-server
|
||||
# predicates:
|
||||
# - Path=/oauth/check_token
|
||||
# filters:
|
||||
# - PreserveHostHeader
|
||||
# - id: user
|
||||
# uri: lb://user-center
|
||||
# predicates:
|
||||
# - Path=/api-user/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - id: file
|
||||
# uri: lb://file-center
|
||||
# predicates:
|
||||
# - Path=/api-file/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - id: log
|
||||
# uri: lb://log-center
|
||||
# predicates:
|
||||
# - Path=/api-log/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - id: generator
|
||||
# uri: lb://code-generator
|
||||
# predicates:
|
||||
# - Path=/api-generator/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - id: search
|
||||
# uri: lb://search-center
|
||||
# predicates:
|
||||
# - Path=/api-search/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - id: device
|
||||
# uri: lb://device-center
|
||||
# predicates:
|
||||
# - Path=/api-device/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - id: order
|
||||
# uri: lb://order-center
|
||||
# predicates:
|
||||
# - Path=/api-order/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
# - id: coupon
|
||||
# uri: lb://coupon-center
|
||||
# predicates:
|
||||
# - Path=/api-coupon/**
|
||||
# filters:
|
||||
# - StripPrefix=1
|
||||
## sentinel:
|
||||
## datasource.ds1.nacos:
|
||||
## server-addr: ${spring.cloud.nacos.server-addr}
|
||||
## data-id: ${spring.application.name}-sentinel-gw-flow
|
||||
## group-id: DEFAULT_GROUP
|
||||
## ruleType: gw-flow
|
||||
## filter:
|
||||
## enabled: true
|
||||
#
|
||||
#knife4j:
|
||||
# gateway:
|
||||
# enabled: true
|
||||
# strategy: manual
|
||||
# routes:
|
||||
# - name: 用户服务
|
||||
# service-name: user-center
|
||||
# url: /api-user/v3/api-docs/default
|
||||
# context-path: /api-user
|
||||
# - name: 授权服务
|
||||
# service-name: uaa-server
|
||||
# url: /api-uaa/v3/api-docs/default
|
||||
# context-path: /api-uaa
|
||||
# - name: 搜索服务
|
||||
# service-name: search-center
|
||||
# url: /api-search/v3/api-docs/default
|
||||
# context-path: /api-search
|
||||
# - name: 文件服务
|
||||
# service-name: file-center
|
||||
# url: /api-file/v3/api-docs/default
|
||||
# context-path: /api-file
|
||||
# - name: 设备服务
|
||||
# service-name: device-center
|
||||
# url: /api-device/v3/api-docs/default
|
||||
# context-path: /api-device
|
||||
# - name: 订单服务
|
||||
# service-name: order-center
|
||||
# url: /api-order/v3/api-docs/default
|
||||
# context-path: /api-order
|
||||
# - name: 设备运维服务
|
||||
# service-name: device-ops-center
|
||||
# url: /api-device-ops/v3/api-docs/default
|
||||
# context-path: /api-device-ops
|
||||
# - name: 优惠券服务
|
||||
# service-name: coupon-center
|
||||
# url: /api-coupon/v3/api-docs/default
|
||||
# context-path: /api-coupon
|
||||
#
|
||||
#zlt:
|
||||
# security:
|
||||
# ignore:
|
||||
# # 忽略认证的地址
|
||||
# httpUrls: >
|
||||
# /api-uaa/oauth/**,
|
||||
# /api-uaa/validata/**,
|
||||
# /api-uaa/css/**,
|
||||
# /api-uaa/images/**,
|
||||
# /api-uaa/js/**,
|
||||
# /login.html,
|
||||
# /user/login, /oauth/authorize,
|
||||
# /api-uaa/tokens/key,
|
||||
# /*/v3/api-docs/**,
|
||||
# /api-order/files/path,
|
||||
# /api-order/update,
|
||||
# /api-order/queue/first,
|
||||
# /api-order/wechat/**,
|
||||
# /api-order/home/carousel/app,
|
||||
# /api-order/device/status,
|
||||
# /api-order/token/callback,
|
||||
# /api-device/stream-urls,
|
||||
# /api-device/token/query,
|
||||
# /api-order/user/temp,
|
||||
# /api-file/file/expires,
|
||||
# /api-order/refund/auto,
|
||||
# /api-order/files/exists/**,
|
||||
# /api-coupon/coupon/ctrip/create,
|
||||
# /api-order/tourism/nearby,
|
||||
# /api-coupon/ctrip/query/**,
|
||||
# /api-coupon/ctrip/refund/**,
|
||||
# /api-coupon/ctrip/pay/**
|
||||
# auth:
|
||||
# urlPermission:
|
||||
# #是否开启url级别权限
|
||||
# enable: false
|
||||
# #配置只进行登录认证,不进行url权限认证的api
|
||||
# ignoreUrls: >
|
||||
# /api-user/menus/current,
|
||||
# /api-user/users/current,
|
||||
# /api-log/requestStat
|
||||
# #白名单
|
||||
# includeClientIds:
|
||||
# - webApp
|
||||
# renew:
|
||||
# #是否开启token自动续签(目前只有redis实现)
|
||||
# enable: true
|
||||
# #白名单
|
||||
# includeClientIds:
|
||||
# - webApp
|
||||
# gateway:
|
||||
# #网关动态路由
|
||||
# dynamicRoute:
|
||||
# enabled: true
|
||||
#
|
||||
#hystrix:
|
||||
# command:
|
||||
# default:
|
||||
# execution:
|
||||
# isolation:
|
||||
# thread:
|
||||
# timeoutInMilliseconds: 1000
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.central.oauth.controller;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.oauth.model.*;
|
||||
import com.central.oauth.service.ICryptoService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
/**
|
||||
* RSA加解密接口控制器
|
||||
*/
|
||||
@Tag(name = "RSA加解密接口")
|
||||
@RestController
|
||||
@RequestMapping("/crypto")
|
||||
@Slf4j
|
||||
public class CryptoController {
|
||||
|
||||
@Autowired
|
||||
private ICryptoService cryptoService;
|
||||
|
||||
/**
|
||||
* 获取RSA公钥
|
||||
* 前端可以调用此接口获取公钥,用于数据加密
|
||||
*/
|
||||
@Operation(summary = "获取RSA公钥", description = "获取用于加密的RSA公钥,前端使用此公钥加密敏感数据")
|
||||
@GetMapping("/public-key")
|
||||
public Result<PublicKeyResponse> getPublicKey() {
|
||||
try {
|
||||
PublicKeyResponse response = cryptoService.getPublicKey();
|
||||
log.info("公钥获取成功");
|
||||
return Result.succeed(response, "公钥获取成功");
|
||||
} catch (Exception e) {
|
||||
log.error("获取公钥失败", e);
|
||||
return Result.failed("获取公钥失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA加密接口
|
||||
* 使用RSA公钥加密数据
|
||||
*/
|
||||
@Operation(summary = "RSA加密", description = "使用RSA公钥加密数据,返回Base64编码的密文")
|
||||
@PostMapping("/encrypt")
|
||||
public Result<CryptoResponse> encrypt(@Valid @RequestBody CryptoRequest request,
|
||||
HttpServletRequest httpRequest) {
|
||||
try {
|
||||
// 获取客户端IP
|
||||
String clientIp = getClientIp(httpRequest);
|
||||
|
||||
// 检查请求频率限制
|
||||
if (!cryptoService.checkRateLimit(clientIp)) {
|
||||
log.warn("客户端 {} 请求频率过高", clientIp);
|
||||
return Result.failed("请求过于频繁,请稍后重试");
|
||||
}
|
||||
|
||||
CryptoResponse response = cryptoService.encrypt(request);
|
||||
log.info("数据加密成功,客户端IP: {}", clientIp);
|
||||
return Result.succeed(response, "加密成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("加密失败: {}", e.getMessage(), e);
|
||||
return Result.failed("加密失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA解密接口
|
||||
* 使用RSA私钥解密数据(管理员功能,需要权限控制)
|
||||
*/
|
||||
@Operation(summary = "RSA解密", description = "使用RSA私钥解密数据,返回明文(需要管理员权限)")
|
||||
@PostMapping("/decrypt")
|
||||
public Result<DecryptResponse> decrypt(@Valid @RequestBody DecryptRequest request,
|
||||
HttpServletRequest httpRequest) {
|
||||
try {
|
||||
// 获取客户端IP
|
||||
String clientIp = getClientIp(httpRequest);
|
||||
|
||||
// 检查请求频率限制(解密接口限制更严格)
|
||||
if (!cryptoService.checkRateLimit(clientIp)) {
|
||||
log.warn("客户端 {} 解密请求频率过高", clientIp);
|
||||
return Result.failed("请求过于频繁,请稍后重试");
|
||||
}
|
||||
|
||||
// 记录解密操作日志(安全审计)
|
||||
log.info("解密请求,客户端IP: {}, 时间戳: {}", clientIp, request.getTimestamp());
|
||||
|
||||
DecryptResponse response = cryptoService.decrypt(request);
|
||||
log.info("数据解密成功,客户端IP: {}", clientIp);
|
||||
return Result.succeed(response, "解密成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("解密失败: {}", e.getMessage(), e);
|
||||
return Result.failed("解密失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试加解密流程
|
||||
* 用于验证RSA加解密功能是否正常
|
||||
*/
|
||||
@Operation(summary = "测试加解密", description = "测试RSA加解密流程是否正常工作")
|
||||
@PostMapping("/test")
|
||||
public Result<String> testCrypto(@RequestParam(defaultValue = "hello123") String testData,
|
||||
HttpServletRequest httpRequest) {
|
||||
try {
|
||||
String clientIp = getClientIp(httpRequest);
|
||||
|
||||
// 检查请求频率
|
||||
if (!cryptoService.checkRateLimit(clientIp)) {
|
||||
return Result.failed("请求过于频繁,请稍后重试");
|
||||
}
|
||||
|
||||
String timestamp = String.valueOf(System.currentTimeMillis());
|
||||
|
||||
// 1. 加密测试
|
||||
CryptoRequest encryptReq = new CryptoRequest();
|
||||
encryptReq.setData(testData);
|
||||
encryptReq.setTimestamp(timestamp);
|
||||
|
||||
CryptoResponse encryptResp = cryptoService.encrypt(encryptReq);
|
||||
|
||||
// 2. 解密测试
|
||||
DecryptRequest decryptReq = new DecryptRequest();
|
||||
decryptReq.setEncryptedData(encryptResp.getEncryptedData());
|
||||
decryptReq.setTimestamp(String.valueOf(System.currentTimeMillis()));
|
||||
|
||||
DecryptResponse decryptResp = cryptoService.decrypt(decryptReq);
|
||||
|
||||
// 3. 验证结果
|
||||
boolean success = testData.equals(decryptResp.getData());
|
||||
String result = String.format("测试%s - 原文: %s, 密文: %s, 解密: %s",
|
||||
success ? "成功" : "失败",
|
||||
testData,
|
||||
encryptResp.getEncryptedData().substring(0, Math.min(20, encryptResp.getEncryptedData().length())) + "...",
|
||||
decryptResp.getData());
|
||||
|
||||
log.info("加解密测试完成,结果: {}, 客户端IP: {}", success, clientIp);
|
||||
return Result.succeed(result, success ? "测试成功" : "测试失败");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("测试加解密失败", e);
|
||||
return Result.failed("测试失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端真实IP地址
|
||||
*/
|
||||
private String getClientIp(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
|
||||
// 处理多级代理的情况
|
||||
if (ip != null && ip.contains(",")) {
|
||||
ip = ip.substring(0, ip.indexOf(",")).trim();
|
||||
}
|
||||
|
||||
return ip != null ? ip : "unknown";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.central.oauth.controller;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.model.CodeEnum;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.utils.RSAUtil;
|
||||
import com.central.common.utils.StringUtils;
|
||||
import com.central.oauth.model.Client;
|
||||
import com.central.oauth.model.LoginReq;
|
||||
import com.central.oauth.service.IClientService;
|
||||
import com.central.oauth.service.IValidateCodeService;
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import com.central.oauth.service.impl.UnifiedLogoutService;
|
||||
import com.central.oauth.service.impl.UserDetailServiceFactory;
|
||||
import com.central.oauth.support.mobile.MobileAuthenticationProvider;
|
||||
import com.central.oauth.support.openid.OpenIdAuthenticationProvider;
|
||||
import com.central.oauth.support.password.PasswordAuthenticationProvider;
|
||||
import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationProvider;
|
||||
import com.central.oauth.support.tencent.TencentAuthenticationProvider;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.token.OpenIdAuthenticationToken;
|
||||
import com.central.oauth2.common.token.TencentAuthenticationToken;
|
||||
import com.central.oauth2.common.util.AuthUtils;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequestWrapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Tag(name = "登录接口")
|
||||
@RestController
|
||||
@RequestMapping("/oauth")
|
||||
@Slf4j
|
||||
public class LoginController {
|
||||
|
||||
@Resource
|
||||
private IClientService clientService;
|
||||
|
||||
@Resource
|
||||
@Lazy
|
||||
private RegisteredClientRepository registeredClientRepository;
|
||||
|
||||
@Resource
|
||||
private ZltUserDetailsService zltUserDetailsService;
|
||||
|
||||
@Resource
|
||||
@Lazy
|
||||
private OAuth2AuthorizationService authorizationService;
|
||||
|
||||
@Resource
|
||||
private OAuth2TokenGenerator tokenGenerator;
|
||||
|
||||
@Resource
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Resource
|
||||
private UserDetailServiceFactory userDetailServiceFactory;
|
||||
|
||||
@Resource
|
||||
private IValidateCodeService validateCodeService;
|
||||
|
||||
@Resource
|
||||
private SecurityProperties securityProperties;
|
||||
@Resource
|
||||
private UnifiedLogoutService unifiedLogoutService;
|
||||
|
||||
@PostMapping(value = "/login")
|
||||
public Result<Map<String, Object>> login(@RequestBody LoginReq req) {
|
||||
try {
|
||||
// 1) 参数与用户基础校验
|
||||
Result<?> userCheck = zltUserDetailsService.checkUser(req);
|
||||
// 日志(避免敏感信息)
|
||||
log.info("用户登录请求:用户名={}, 客户端ID={}, 授权类型={}", req.getUserName(), req.getClientId(), req.getGrantType());
|
||||
if (Objects.equals(userCheck.getResp_code(), CodeEnum.ERROR.getCode())) {
|
||||
return Result.failed(userCheck.getResp_msg());
|
||||
}
|
||||
|
||||
// 2) 客户端与授权类型校验
|
||||
Client client = clientService.loadClientByClientId(req.getClientId());
|
||||
if (client == null) {
|
||||
return Result.failed("所属客户端不存在");
|
||||
}
|
||||
RegisteredClient registeredClient = registeredClientRepository.findByClientId(client.getClientId());
|
||||
if (registeredClient == null) {
|
||||
return Result.failed("未注册的客户端");
|
||||
}
|
||||
AuthorizationGrantType grantTypeToUse = new AuthorizationGrantType(req.getGrantType());
|
||||
if (!registeredClient.getAuthorizationGrantTypes().contains(grantTypeToUse)) {
|
||||
return Result.failed("客户端未开通该授权类型: " + req.getGrantType());
|
||||
}
|
||||
|
||||
// 3) 解密密码(需要密码的授权类型)
|
||||
String rawPassword = null;
|
||||
if ("password".equals(req.getGrantType()) || "password_code".equals(req.getGrantType()) || "mobile_password".equals(req.getGrantType())) {
|
||||
try {
|
||||
rawPassword = RSAUtil.decryptOne(req.getPassword());
|
||||
if (StringUtils.isBlank(rawPassword)) {
|
||||
return Result.failed("登录密码不能为空");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("密码解密失败", e);
|
||||
return Result.failed("登录密码解密失败,请确保使用正确的加密方式");
|
||||
}
|
||||
}
|
||||
|
||||
// 4) 本地颁发令牌(不走标准端点)
|
||||
return issueTokenInternally(req, registeredClient, rawPassword);
|
||||
} catch (Exception e) {
|
||||
log.error("登录过程发生异常", e);
|
||||
return Result.failed("登录失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping(value = "/logout")
|
||||
public Result<String> logOut(HttpServletRequest request) {
|
||||
String token = AuthUtils.extractHeaderToken(request);
|
||||
if (StringUtils.isBlank(token)) {
|
||||
return Result.failed("未提供Authorization Bearer token");
|
||||
}
|
||||
try {
|
||||
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
|
||||
if (authorization == null) {
|
||||
return Result.failed("无效的token或token已过期");
|
||||
}
|
||||
if (Boolean.TRUE.equals(securityProperties.getAuth().getUnifiedLogout())) {
|
||||
com.central.oauth.utils.UsernameHolder.setContext(authorization.getPrincipalName());
|
||||
unifiedLogoutService.allLogout();
|
||||
} else {
|
||||
authorizationService.remove(authorization);
|
||||
}
|
||||
return Result.succeed("退出成功");
|
||||
} catch (Exception e) {
|
||||
log.error("登出过程发生异常", e);
|
||||
return Result.failed("登出失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 屏蔽参数中的 token/access_token,只允许从 Authorization 头取 token
|
||||
*/
|
||||
private static class HeaderOnlyTokenRequestWrapper extends HttpServletRequestWrapper {
|
||||
public HeaderOnlyTokenRequestWrapper(HttpServletRequest request) { super(request); }
|
||||
@Override public String getParameter(String name) {
|
||||
if ("token".equals(name) || "access_token".equals(name)) { return null; }
|
||||
return super.getParameter(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用本地 Provider 颁发令牌,支持多种授权类型
|
||||
*/
|
||||
private Result<Map<String, Object>> issueTokenInternally(LoginReq req, RegisteredClient registeredClient, String rawPassword) {
|
||||
try {
|
||||
OAuth2ClientAuthenticationToken clientPrincipal =
|
||||
new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null);
|
||||
|
||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication;
|
||||
switch (req.getGrantType()) {
|
||||
case "password": {
|
||||
PasswordAuthenticationProvider provider = new PasswordAuthenticationProvider(
|
||||
authorizationService, tokenGenerator, userDetailServiceFactory, passwordEncoder);
|
||||
com.central.oauth2.common.token.PasswordAuthenticationToken authToken =
|
||||
new com.central.oauth2.common.token.PasswordAuthenticationToken(req.getUserName(), rawPassword);
|
||||
authToken.setScopes(registeredClient.getScopes());
|
||||
authToken.setClientPrincipal(clientPrincipal);
|
||||
java.util.HashMap<String, Object> ap = new java.util.HashMap<>();
|
||||
ap.put(com.central.common.constant.SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, com.central.common.constant.SecurityConstants.DEF_ACCOUNT_TYPE);
|
||||
authToken.setAdditionalParameters(ap);
|
||||
accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) provider.authenticate(authToken);
|
||||
break;
|
||||
}
|
||||
case "password_code": {
|
||||
PasswordCodeAuthenticationProvider provider = new PasswordCodeAuthenticationProvider(
|
||||
authorizationService, tokenGenerator, userDetailServiceFactory, passwordEncoder, validateCodeService);
|
||||
com.central.oauth2.common.token.PasswordCodeAuthenticationToken authToken =
|
||||
new com.central.oauth2.common.token.PasswordCodeAuthenticationToken(
|
||||
req.getUserName(), rawPassword, req.getDeviceId(), req.getValidCode());
|
||||
authToken.setScopes(registeredClient.getScopes());
|
||||
authToken.setClientPrincipal(clientPrincipal);
|
||||
java.util.HashMap<String, Object> ap = new java.util.HashMap<>();
|
||||
ap.put(com.central.common.constant.SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, com.central.common.constant.SecurityConstants.DEF_ACCOUNT_TYPE);
|
||||
authToken.setAdditionalParameters(ap);
|
||||
accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) provider.authenticate(authToken);
|
||||
break;
|
||||
}
|
||||
case "mobile_password": {
|
||||
MobileAuthenticationProvider provider = new MobileAuthenticationProvider(
|
||||
authorizationService, tokenGenerator, userDetailServiceFactory, passwordEncoder);
|
||||
com.central.oauth2.common.token.MobileAuthenticationToken authToken =
|
||||
new com.central.oauth2.common.token.MobileAuthenticationToken(req.getMobile(), rawPassword);
|
||||
authToken.setScopes(registeredClient.getScopes());
|
||||
authToken.setClientPrincipal(clientPrincipal);
|
||||
java.util.HashMap<String, Object> ap = new java.util.HashMap<>();
|
||||
ap.put(com.central.common.constant.SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, com.central.common.constant.SecurityConstants.DEF_ACCOUNT_TYPE);
|
||||
authToken.setAdditionalParameters(ap);
|
||||
accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) provider.authenticate(authToken);
|
||||
break;
|
||||
}
|
||||
case "openId": {
|
||||
OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider(
|
||||
authorizationService, tokenGenerator, userDetailServiceFactory);
|
||||
OpenIdAuthenticationToken authToken = new OpenIdAuthenticationToken(req.getOpenId());
|
||||
authToken.setScopes(registeredClient.getScopes());
|
||||
authToken.setClientPrincipal(clientPrincipal);
|
||||
java.util.HashMap<String, Object> ap = new java.util.HashMap<>();
|
||||
ap.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, SecurityConstants.DEF_ACCOUNT_TYPE);
|
||||
authToken.setAdditionalParameters(ap);
|
||||
accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) provider.authenticate(authToken);
|
||||
break;
|
||||
}
|
||||
case "tencent": {
|
||||
TencentAuthenticationProvider provider = new TencentAuthenticationProvider(
|
||||
authorizationService, tokenGenerator, userDetailServiceFactory, securityProperties);
|
||||
TencentAuthenticationToken authToken =
|
||||
new com.central.oauth2.common.token.TencentAuthenticationToken(
|
||||
req.getCode(), req.getEncryptedData(), req.getIv(),
|
||||
StringUtils.isBlank(req.getAppCode()) ? "" : req.getAppCode());
|
||||
authToken.setScopes(registeredClient.getScopes());
|
||||
authToken.setClientPrincipal(clientPrincipal);
|
||||
java.util.HashMap<String, Object> ap = new java.util.HashMap<>();
|
||||
ap.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, SecurityConstants.DEF_ACCOUNT_TYPE);
|
||||
authToken.setAdditionalParameters(ap);
|
||||
accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) provider.authenticate(authToken);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return Result.failed("不支持的授权类型: " + req.getGrantType());
|
||||
}
|
||||
|
||||
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
|
||||
OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
|
||||
Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
|
||||
|
||||
OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse
|
||||
.withToken(accessToken.getTokenValue())
|
||||
.tokenType(accessToken.getTokenType())
|
||||
.scopes(accessToken.getScopes());
|
||||
if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
|
||||
builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
|
||||
}
|
||||
if (refreshToken != null) {
|
||||
builder.refreshToken(refreshToken.getTokenValue());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(additionalParameters)) {
|
||||
builder.additionalParameters(additionalParameters);
|
||||
}
|
||||
OAuth2AccessTokenResponse tokenResponse = builder.build();
|
||||
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("access_token", tokenResponse.getAccessToken().getTokenValue());
|
||||
body.put("token_type", tokenResponse.getAccessToken().getTokenType().getValue());
|
||||
body.put("expires_in", tokenResponse.getAccessToken().getExpiresAt() != null && tokenResponse.getAccessToken().getIssuedAt() != null
|
||||
? ChronoUnit.SECONDS.between(tokenResponse.getAccessToken().getIssuedAt(), tokenResponse.getAccessToken().getExpiresAt())
|
||||
: 0);
|
||||
body.put("scope", String.join(" ", tokenResponse.getAccessToken().getScopes()));
|
||||
if (tokenResponse.getRefreshToken() != null) {
|
||||
body.put("refresh_token", tokenResponse.getRefreshToken().getTokenValue());
|
||||
}
|
||||
if (!tokenResponse.getAdditionalParameters().isEmpty()) {
|
||||
body.putAll(tokenResponse.getAdditionalParameters());
|
||||
}
|
||||
return Result.succeed(body, "登录成功");
|
||||
} catch (Exception ex) {
|
||||
log.error("本地颁发令牌失败", ex);
|
||||
String msg = ex.getMessage();
|
||||
return Result.failed(StringUtils.isBlank(msg) ? "登录失败" : ("登录失败:" + msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.central.oauth.model;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 加密请求模型
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "加密请求")
|
||||
public class CryptoRequest {
|
||||
|
||||
@Schema(description = "要加密的明文数据", required = true, example = "hello123")
|
||||
@NotBlank(message = "数据不能为空")
|
||||
private String data;
|
||||
|
||||
@Schema(description = "请求时间戳(防重放攻击)", required = true)
|
||||
@NotBlank(message = "时间戳不能为空")
|
||||
private String timestamp;
|
||||
|
||||
@Schema(description = "随机数(增强安全性)", required = false)
|
||||
private String nonce;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.central.oauth.model;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 加密响应模型
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "加密响应")
|
||||
public class CryptoResponse {
|
||||
|
||||
@Schema(description = "加密后的数据", example = "LBS9qzlDcBQeb+WLhGRKm5+zoQk...")
|
||||
private String encryptedData;
|
||||
|
||||
@Schema(description = "响应时间戳")
|
||||
private Long timestamp;
|
||||
|
||||
@Schema(description = "加密算法信息")
|
||||
private String algorithm;
|
||||
|
||||
@Schema(description = "密钥长度")
|
||||
private Integer keyLength;
|
||||
|
||||
public CryptoResponse() {
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
this.algorithm = "RSA/ECB/PKCS1Padding";
|
||||
this.keyLength = 1024;
|
||||
}
|
||||
|
||||
public CryptoResponse(String encryptedData) {
|
||||
this();
|
||||
this.encryptedData = encryptedData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.central.oauth.model;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
/**
|
||||
* 解密请求模型
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "解密请求")
|
||||
public class DecryptRequest {
|
||||
|
||||
@Schema(description = "要解密的密文数据", required = true, example = "LBS9qzlDcBQeb+WLhGRKm5+zoQk...")
|
||||
@NotBlank(message = "加密数据不能为空")
|
||||
private String encryptedData;
|
||||
|
||||
@Schema(description = "请求时间戳(防重放攻击)", required = true)
|
||||
@NotBlank(message = "时间戳不能为空")
|
||||
private String timestamp;
|
||||
|
||||
@Schema(description = "随机数(增强安全性)", required = false)
|
||||
private String nonce;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.central.oauth.model;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 解密响应模型
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "解密响应")
|
||||
public class DecryptResponse {
|
||||
|
||||
@Schema(description = "解密后的明文数据")
|
||||
private String data;
|
||||
|
||||
@Schema(description = "响应时间戳")
|
||||
private Long timestamp;
|
||||
|
||||
@Schema(description = "解密算法信息")
|
||||
private String algorithm;
|
||||
|
||||
public DecryptResponse() {
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
this.algorithm = "RSA/ECB/PKCS1Padding";
|
||||
}
|
||||
|
||||
public DecryptResponse(String data) {
|
||||
this();
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.central.oauth.model;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 登录请求
|
||||
*/
|
||||
@Data
|
||||
public class LoginReq {
|
||||
|
||||
@Schema(description = "用户名(grantType 为 password/password_code 时必填)")
|
||||
private String userName;
|
||||
|
||||
@Schema(description = "密码(RSA 加密)。grantType 为 password/password_code/mobile_password 必填")
|
||||
private String password;
|
||||
|
||||
@Schema(description = "认证类型:1)用户名+密码=password;2)用户名+密码+验证码=password_code;3)手机号+密码=mobile_password;4)OpenId=openId;5)微信小程序=tencent。必填")
|
||||
private String grantType;
|
||||
|
||||
@Schema(description = "手机号(grantType 为 mobile_password 必填)")
|
||||
private String mobile;
|
||||
|
||||
@Schema(description = "客户端ID,必填")
|
||||
private String clientId;
|
||||
|
||||
@Schema(description = "验证码(grantType 为 password_code 必填)")
|
||||
private String validCode;
|
||||
|
||||
@Schema(description = "前端唯一标识,需与获取验证码一致(grantType 为 password_code 必填)")
|
||||
private String deviceId;
|
||||
|
||||
@Schema(description = "OpenId(grantType 为 openId 必填)")
|
||||
private String openId;
|
||||
|
||||
@Schema(description = "微信小程序登录 code(grantType 为 tencent 必填)")
|
||||
private String code;
|
||||
|
||||
@Schema(description = "微信小程序加密数据 encryptedData(tencent 模式建议必填)")
|
||||
private String encryptedData;
|
||||
|
||||
@Schema(description = "微信小程序 iv(tencent 模式建议必填)")
|
||||
private String iv;
|
||||
|
||||
@Schema(description = "应用标识 appCode(tencent 模式可选,缺省使用默认配置)")
|
||||
private String appCode;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.central.oauth.model;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 公钥响应模型
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "公钥响应")
|
||||
public class PublicKeyResponse {
|
||||
|
||||
@Schema(description = "RSA公钥(Base64编码)")
|
||||
private String publicKey;
|
||||
|
||||
@Schema(description = "密钥长度")
|
||||
private Integer keyLength;
|
||||
|
||||
@Schema(description = "加密算法")
|
||||
private String algorithm;
|
||||
|
||||
@Schema(description = "响应时间戳")
|
||||
private Long timestamp;
|
||||
|
||||
@Schema(description = "密钥版本(用于密钥轮换)")
|
||||
private String version;
|
||||
|
||||
public PublicKeyResponse() {
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
this.algorithm = "RSA/ECB/PKCS1Padding";
|
||||
this.keyLength = 1024;
|
||||
this.version = "v1.0";
|
||||
}
|
||||
|
||||
public PublicKeyResponse(String publicKey) {
|
||||
this();
|
||||
this.publicKey = publicKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.central.oauth.service;
|
||||
|
||||
import com.central.oauth.model.*;
|
||||
|
||||
/**
|
||||
* 加密服务接口
|
||||
*/
|
||||
public interface ICryptoService {
|
||||
|
||||
/**
|
||||
* 获取RSA公钥
|
||||
* @return 公钥响应
|
||||
*/
|
||||
PublicKeyResponse getPublicKey();
|
||||
|
||||
/**
|
||||
* RSA公钥加密
|
||||
* @param request 加密请求
|
||||
* @return 加密响应
|
||||
*/
|
||||
CryptoResponse encrypt(CryptoRequest request);
|
||||
|
||||
/**
|
||||
* RSA私钥解密
|
||||
* @param request 解密请求
|
||||
* @return 解密响应
|
||||
*/
|
||||
DecryptResponse decrypt(DecryptRequest request);
|
||||
|
||||
/**
|
||||
* 验证时间戳(防重放攻击)
|
||||
* @param timestamp 时间戳字符串
|
||||
* @return 是否有效
|
||||
*/
|
||||
boolean validateTimestamp(String timestamp);
|
||||
|
||||
/**
|
||||
* 检查请求频率限制
|
||||
* @param clientIp 客户端IP
|
||||
* @return 是否允许请求
|
||||
*/
|
||||
boolean checkRateLimit(String clientIp);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.central.oauth.service;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.oauth.model.LoginReq;
|
||||
import com.central.wechat.entity.WechatConfig;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
@@ -45,4 +47,10 @@ public interface ZltUserDetailsService extends UserDetailsService {
|
||||
* @return
|
||||
*/
|
||||
WechatConfig loadMiniAppConfig(String appId, String type);
|
||||
|
||||
/**
|
||||
* 检查登录用户
|
||||
* @return
|
||||
*/
|
||||
Result checkUser(LoginReq req) ;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import com.central.common.utils.RSAUtil;
|
||||
import com.central.oauth.model.*;
|
||||
import com.central.oauth.service.ICryptoService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 加密服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CryptoServiceImpl implements ICryptoService {
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
// 时间戳有效期(5分钟)
|
||||
private static final long TIMESTAMP_VALID_PERIOD = 50 * 60 * 1000 ;
|
||||
|
||||
// 请求频率限制(每IP每分钟最多10次)
|
||||
private static final int RATE_LIMIT_COUNT = 30;
|
||||
private static final int RATE_LIMIT_PERIOD = 60;
|
||||
|
||||
@Override
|
||||
public PublicKeyResponse getPublicKey() {
|
||||
try {
|
||||
// 获取RSA公钥(Base64编码)
|
||||
String publicKeyStr = Base64.getEncoder().encodeToString(RSAUtil.publicKey.getEncoded());
|
||||
return new PublicKeyResponse(publicKeyStr);
|
||||
} catch (Exception e) {
|
||||
log.error("获取公钥失败", e);
|
||||
throw new RuntimeException("获取公钥失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CryptoResponse encrypt(CryptoRequest request) {
|
||||
try {
|
||||
// 1. 验证时间戳
|
||||
if (!validateTimestamp(request.getTimestamp())) {
|
||||
throw new RuntimeException("请求时间戳无效或已过期");
|
||||
}
|
||||
|
||||
// 2. 验证数据
|
||||
if (!StringUtils.hasText(request.getData())) {
|
||||
throw new RuntimeException("要加密的数据不能为空");
|
||||
}
|
||||
|
||||
// 3. 数据长度限制(RSA加密有长度限制)
|
||||
if (request.getData().getBytes().length > 100) {
|
||||
throw new RuntimeException("数据长度不能超过100字节");
|
||||
}
|
||||
|
||||
// 4. RSA公钥加密
|
||||
String encryptedData = RSAUtil.encryptOne(request.getData());
|
||||
if (encryptedData == null) {
|
||||
throw new RuntimeException("数据加密失败");
|
||||
}
|
||||
|
||||
log.info("数据加密成功,原始长度: {}, 加密后长度: {}",
|
||||
request.getData().length(), encryptedData.length());
|
||||
|
||||
return new CryptoResponse(encryptedData);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("加密处理失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("加密失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DecryptResponse decrypt(DecryptRequest request) {
|
||||
try {
|
||||
// 1. 验证时间戳
|
||||
if (!validateTimestamp(request.getTimestamp())) {
|
||||
throw new RuntimeException("请求时间戳无效或已过期");
|
||||
}
|
||||
|
||||
// 2. 验证加密数据
|
||||
if (!StringUtils.hasText(request.getEncryptedData())) {
|
||||
throw new RuntimeException("要解密的数据不能为空");
|
||||
}
|
||||
|
||||
// 3. RSA私钥解密
|
||||
String decryptedData = RSAUtil.decryptOne(request.getEncryptedData());
|
||||
if (decryptedData == null) {
|
||||
throw new RuntimeException("数据解密失败,请检查密文格式");
|
||||
}
|
||||
|
||||
log.info("数据解密成功,解密后长度: {}", decryptedData.length());
|
||||
|
||||
return new DecryptResponse(decryptedData);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("解密处理失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("解密失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateTimestamp(String timestamp) {
|
||||
try {
|
||||
if (!StringUtils.hasText(timestamp)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
long requestTime = Long.parseLong(timestamp);
|
||||
long currentTime = System.currentTimeMillis();
|
||||
|
||||
// 检查时间戳是否在有效期内(防重放攻击)
|
||||
long timeDiff = Math.abs(currentTime - requestTime);
|
||||
|
||||
if (timeDiff > TIMESTAMP_VALID_PERIOD) {
|
||||
log.warn("请求时间戳超出有效期: {} ms", timeDiff);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否为重放请求(同一时间戳只能使用一次)
|
||||
String key = "crypto:timestamp:" + timestamp;
|
||||
String exists = redisTemplate.opsForValue().get(key);
|
||||
if (exists != null) {
|
||||
log.warn("检测到重放请求,时间戳: {}", timestamp);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 记录已使用的时间戳
|
||||
redisTemplate.opsForValue().set(key, "used", TIMESTAMP_VALID_PERIOD, TimeUnit.MILLISECONDS);
|
||||
|
||||
return true;
|
||||
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("时间戳格式错误: {}", timestamp);
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.error("验证时间戳失败", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkRateLimit(String clientIp) {
|
||||
try {
|
||||
String key = "crypto:rate_limit:" + clientIp;
|
||||
String countStr = redisTemplate.opsForValue().get(key);
|
||||
|
||||
if (countStr == null) {
|
||||
// 首次请求
|
||||
redisTemplate.opsForValue().set(key, "1", RATE_LIMIT_PERIOD, TimeUnit.SECONDS);
|
||||
return true;
|
||||
}
|
||||
|
||||
int count = Integer.parseInt(countStr);
|
||||
if (count >= RATE_LIMIT_COUNT) {
|
||||
log.warn("客户端 {} 请求频率过高,当前计数: {}", clientIp, count);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 增加计数
|
||||
redisTemplate.opsForValue().increment(key);
|
||||
return true;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("检查请求频率失败", e);
|
||||
// 出错时允许请求,避免影响正常业务
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,11 @@ package com.central.oauth.service.impl;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.common.utils.LoginUserUtils;
|
||||
import com.central.common.utils.StringUtils;
|
||||
import com.central.oauth.model.LoginReq;
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import com.central.wechat.entity.WechatConfig;
|
||||
import com.central.wechat.feign.WechatConfigService;
|
||||
@@ -16,12 +19,6 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class UserDetailServiceImpl implements ZltUserDetailsService {
|
||||
@@ -56,8 +53,8 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByWxOpenId(String wxOpenId,String mobile,String unionId) throws UsernameNotFoundException {
|
||||
SysUser sysUser = userService.findByWxOpenId(wxOpenId,mobile,unionId);
|
||||
public UserDetails loadUserByWxOpenId(String wxOpenId, String mobile, String unionId) throws UsernameNotFoundException {
|
||||
SysUser sysUser = userService.findByWxOpenId(wxOpenId, mobile, unionId);
|
||||
checkUser(sysUser);
|
||||
return LoginUserUtils.getLoginAppUser(sysUser);
|
||||
}
|
||||
@@ -67,6 +64,66 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
|
||||
return wechatConfigService.getConfigByAppId(appId, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result checkUser(LoginReq req) {
|
||||
if (req == null) {
|
||||
return Result.failed("请求参数不能为空");
|
||||
}
|
||||
if (StringUtils.isBlank(req.getClientId())) {
|
||||
return Result.failed("客户端ID不能为空");
|
||||
}
|
||||
|
||||
String grantType = req.getGrantType();
|
||||
if ("mobile_password".equals(grantType)) {
|
||||
if (StringUtils.isBlank(req.getMobile())) {
|
||||
return Result.failed("手机号不能为空");
|
||||
}
|
||||
} else if ("openId".equals(grantType)) {
|
||||
if (StringUtils.isBlank(req.getOpenId())) {
|
||||
return Result.failed("openId不能为空");
|
||||
}
|
||||
return Result.succeed("校验通过");
|
||||
} else if ("tencent".equals(grantType)) {
|
||||
if (StringUtils.isBlank(req.getCode())) {
|
||||
return Result.failed("code不能为空");
|
||||
}
|
||||
if (StringUtils.isBlank(req.getEncryptedData())) {
|
||||
return Result.failed("encryptedData不能为空");
|
||||
}
|
||||
if (StringUtils.isBlank(req.getIv())) {
|
||||
return Result.failed("iv不能为空");
|
||||
}
|
||||
return Result.succeed("校验通过");
|
||||
} else {
|
||||
if (StringUtils.isBlank(req.getUserName())) {
|
||||
return Result.failed("用户名不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
if ("password_code".equals(grantType)) {
|
||||
if (StringUtils.isBlank(req.getDeviceId())) {
|
||||
return Result.failed("deviceId不能为空");
|
||||
}
|
||||
if (StringUtils.isBlank(req.getValidCode())) {
|
||||
return Result.failed("验证码不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
SysUser sysUser;
|
||||
if ("mobile_password".equals(grantType)) {
|
||||
sysUser = userService.findByMobile(req.getMobile());
|
||||
} else {
|
||||
sysUser = userService.findByUsername(req.getUserName());
|
||||
}
|
||||
if (sysUser == null) {
|
||||
return Result.failed("用户不存在或密码错误");
|
||||
}
|
||||
if (!sysUser.getEnabled()) {
|
||||
return Result.failed("用户已冻结");
|
||||
}
|
||||
return Result.succeed("校验通过");
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByMobile(String mobile) {
|
||||
SysUser sysUser = userService.findByMobile(mobile);
|
||||
@@ -80,3 +137,4 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,52 +1,65 @@
|
||||
spring:
|
||||
datasource:
|
||||
# url: jdbc:mysql://${zlt.datasource.ip}:3306/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
url: jdbc:mysql://${zlt.datasource.ip}/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
username: ${zlt.datasource.username}
|
||||
password: ${zlt.datasource.password}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
#实体扫描,多个package用逗号或者分号分隔
|
||||
typeAliasesPackage: com.central.oauth.model
|
||||
global-config:
|
||||
db-config:
|
||||
id-type: auto
|
||||
|
||||
springdoc:
|
||||
group-configs:
|
||||
- group: 'default'
|
||||
paths-to-match: '/**'
|
||||
packages-to-scan: com.central.oauth.controller
|
||||
|
||||
knife4j:
|
||||
enable: true
|
||||
setting:
|
||||
swagger-model-name: 认证中心接口文档
|
||||
#spring:
|
||||
# datasource:
|
||||
## url: jdbc:mysql://${zlt.datasource.ip}:3306/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# url: jdbc:mysql://${zlt.datasource.ip}/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
# username: ${zlt.datasource.username}
|
||||
# password: ${zlt.datasource.password}
|
||||
# driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
#
|
||||
#mybatis-plus:
|
||||
# mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
# #瀹炰綋鎵弿锛屽涓猵ackage鐢ㄩ€楀彿鎴栬€呭垎鍙峰垎闅?
|
||||
# typeAliasesPackage: com.central.oauth.model
|
||||
# global-config:
|
||||
# db-config:
|
||||
# id-type: auto
|
||||
#
|
||||
#springdoc:
|
||||
# group-configs:
|
||||
# - group: 'default'
|
||||
# paths-to-match: '/**'
|
||||
# packages-to-scan: com.central.oauth.controller
|
||||
#
|
||||
#knife4j:
|
||||
# enable: true
|
||||
# setting:
|
||||
# swagger-model-name: 璁よ瘉涓績鎺ュ彛鏂囨。
|
||||
#
|
||||
#zlt:
|
||||
# security:
|
||||
# code:
|
||||
# # 蹇界暐楠岃瘉鐮佺殑搴旂敤缂栧彿
|
||||
# ignoreClientCode: app
|
||||
# auth:
|
||||
# # 寮€鍚粺涓€鐧诲嚭
|
||||
# unifiedLogout: true
|
||||
# # 鍚岃处鍙风櫥褰曚簰韪?
|
||||
# isSingleLogin: true
|
||||
# #澶氱鎴烽厤缃?
|
||||
# tenant:
|
||||
# enable: true
|
||||
# ignoreTables:
|
||||
# - oauth_client_details
|
||||
# # 鏁版嵁鏉冮檺
|
||||
# datascope:
|
||||
# enabled: false
|
||||
# includeSqls:
|
||||
# # 搴旂敤鍒楄〃
|
||||
# - com.central.oauth.mapper.ClientMapper.findList
|
||||
#uaa:
|
||||
# wx:
|
||||
# # 骞冲彴榛樿鐨凙PPID
|
||||
# appId: wx0c3cc6f1d297644d
|
||||
|
||||
zlt:
|
||||
security:
|
||||
code:
|
||||
# 忽略验证码的应用编号
|
||||
ignoreClientCode: app
|
||||
auth:
|
||||
# 开启统一登出
|
||||
unifiedLogout: true
|
||||
# 同账号登录互踢
|
||||
isSingleLogin: true
|
||||
#多租户配置
|
||||
tenant:
|
||||
enable: true
|
||||
ignoreTables:
|
||||
- oauth_client_details
|
||||
# 数据权限
|
||||
datascope:
|
||||
enabled: false
|
||||
includeSqls:
|
||||
# 应用列表
|
||||
- com.central.oauth.mapper.ClientMapper.findList
|
||||
uaa:
|
||||
wx:
|
||||
# 平台默认的APPID
|
||||
appId: wx0c3cc6f1d297644d
|
||||
# 涓鸿嚜瀹氫箟鐧诲綍/鐧诲嚭鎺ュ彛鏀捐
|
||||
ignore:
|
||||
httpUrls:
|
||||
- /oauth/login
|
||||
- /oauth/logout
|
||||
- /oauth/logout/giveToken
|
||||
- /oauth/token
|
||||
# 鍏煎榛樿琛ㄥ崟鐧诲綍涓庡唴缃櫥鍑?
|
||||
- /user/login
|
||||
- /oauth/remove/token
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
server:
|
||||
port: 8000
|
||||
servlet:
|
||||
session:
|
||||
cookie:
|
||||
name: OAUTH2SESSION
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: uaa-server
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
# ip: 124.222.128.40
|
||||
|
||||
encrypt:
|
||||
key-store:
|
||||
location: classpath:zlt.jks
|
||||
secret: zlt!@#$
|
||||
alias: zlt
|
||||
server:
|
||||
port: 8011
|
||||
servlet:
|
||||
session:
|
||||
cookie:
|
||||
name: OAUTH2SESSION
|
||||
encoding:
|
||||
enabled: true
|
||||
force: true
|
||||
charset: UTF-8
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: uaa-server
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
# ip: 124.222.128.40
|
||||
|
||||
encrypt:
|
||||
key-store:
|
||||
location: classpath:zlt.jks
|
||||
secret: zlt!@#$
|
||||
alias: zlt
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
# react-web-next(重构版)
|
||||
本项目是在不改动现有 `zlt-web/react-web` 的前提下,基于其功能与接口重新组织的“重构版”管理后台前端代码。目标:
|
||||
- 保持所有管理页面功能等价(逐步迁移),显著提升结构与可读性;
|
||||
- 为“每个页面”统一增加“租户 + 包含子租户”查询控制;
|
||||
- 优化主题与布局,使界面更现代、更一致;
|
||||
- 通过组件化与约定,降低后续页面维护成本。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
react-web-next/
|
||||
├─ config/
|
||||
│ ├─ config.ts # Umi 配置(启用 routes、hash history、proxy)
|
||||
│ └─ routes.ts # 路由定义(按域分组)
|
||||
├─ src/
|
||||
│ ├─ layouts/
|
||||
│ │ └─ BasicLayout.tsx # 基础布局(含统一头部操作区)
|
||||
│ ├─ components/
|
||||
│ │ └─ TenantScopeFilter/ # 统一的租户/子租户过滤器
|
||||
│ ├─ pages/
|
||||
│ │ ├─ Welcome.tsx # 示例页(接入租户过滤器)
|
||||
│ │ └─ system/
|
||||
│ │ └─ TenantManage/ # 重构后的租户管理页(树型新增等)
|
||||
│ ├─ services/
|
||||
│ │ └─ tenant.ts # 租户相关 API(复用后端接口)
|
||||
│ ├─ utils/
|
||||
│ │ ├─ request.ts # 请求封装与拦截
|
||||
│ │ ├─ download.ts # 通用下载(支持 Content-Disposition)
|
||||
│ │ └─ export.ts # 前端导出 Excel
|
||||
│ ├─ app.tsx
|
||||
│ └─ global.less
|
||||
├─ package.json
|
||||
└─ tsconfig.json
|
||||
```
|
||||
|
||||
## 运行
|
||||
|
||||
1) 进入目录安装依赖:`npm install`(或 `pnpm i`/`yarn`)
|
||||
2) 开发:
|
||||
- dev(本地网关):`npm run start` 或 `npm run start:dev`
|
||||
- test(测试网关):`npm run start:test`
|
||||
- pre(预发网关):`npm run start:pre`
|
||||
- 临时覆盖网关地址:
|
||||
- PowerShell:`$env:GATEWAY_ORIGIN="http://10.x.x.x:9900"; npm run start:test`
|
||||
- CMD:`set GATEWAY_ORIGIN=http://10.x.x.x:9900 && npm run start:test`
|
||||
3) 构建:`npm run build`
|
||||
|
||||
> 说明:仅开发环境启用代理;生产由统一网关/容器转发。
|
||||
|
||||
## 迁移策略
|
||||
|
||||
- 按模块逐页迁移:
|
||||
1. 将旧页逻辑拆分为“表格 + 表单 + 服务”三个层次;
|
||||
2. 在表格 `toolBarRender` 中默认挂载 `TenantScopeFilter`;
|
||||
3. 保留原有接口地址/参数命名,避免改动后端;
|
||||
4. 体验层(样式/布局/反馈)用 Ant Design Pro 的推荐实践统一收敛。
|
||||
- 公共模式:
|
||||
- 统一请求封装(`src/utils/request.ts`)处理返回结构;
|
||||
- 统一主题变量与间距;
|
||||
- 统一“租户过滤”的行为:
|
||||
- 选择租户 → 调用 `/tenant/switch?tenantId=X` 设置锚点;
|
||||
- 勾选“包含子租户”→ 拦截器自动展开,无需改动每个接口;
|
||||
- 支持“一键重置”回默认租户。
|
||||
|
||||
## 环境与代理
|
||||
|
||||
- 统一代理:`config/proxy.ts` 仅配置一条规则,将所有 `/api-*` 转发到统一网关 `GATEWAY_ORIGIN`。
|
||||
- 环境选择:`REACT_APP_ENV=dev|test|pre` 选择 `proxy` 分支;默认 `dev`。
|
||||
- 启动脚本:见 package.json 的 `start:*`(已内置常用网关地址)。
|
||||
- 生产环境:不启用该代理,由 API 网关/容器转发到后端微服务。
|
||||
|
||||
## 下载与导出
|
||||
|
||||
- 下载(后端生成文件):
|
||||
- 使用 `src/utils/download.ts` 的 `download(res, defaultName)`
|
||||
- 示例:
|
||||
```ts
|
||||
const res = await request('/api-user/users/export', {
|
||||
method: 'POST', responseType: 'blob', getResponse: true,
|
||||
});
|
||||
download(res, 'user.xls'); // 将从 Content-Disposition 解析文件名
|
||||
```
|
||||
- 直接 URL 下载(无 CORS 或简单文件):
|
||||
- `downloadByUrl(url, filename?)`
|
||||
- 前端导出 Excel(内存数据 → xlsx):
|
||||
- 使用 `src/utils/export.ts` 的 `exportExcel({ data, header, fileName })`
|
||||
- header 示例:`[{ title: '用户名', dataIndex: 'username' }]`
|
||||
|
||||
## 已完成
|
||||
|
||||
- 基础框架/布局、主题与请求封装;
|
||||
- `TenantScopeFilter` 组件;
|
||||
- 租户管理页(树型添加/编辑/删除)重构版;
|
||||
- Welcome 示例接入过滤器;
|
||||
- 路由与文档;
|
||||
- 下载/导出工具与用户导出统一改造。
|
||||
|
||||
## 待办(按需推进)
|
||||
|
||||
- 逐步迁移原项目下系统、设备、订单等页面;
|
||||
- 页面级权限点与菜单项的细化;
|
||||
- 更精确的分页 total 透传(后端补齐后更新前端);
|
||||
- 单元测试、E2E 用例补充。
|
||||
|
||||
如需我继续迁移具体页面,请告知优先级(如 系统/订单/设备 等模块)。
|
||||
@@ -0,0 +1,45 @@
|
||||
// Umi 3 基础配置(中文注释)
|
||||
// 目标:
|
||||
// - 显式启用 routes.ts(保持与原项目路径兼容,支持 *.html 路径)
|
||||
// - 使用 browser history,开发调试直达路径不 404;产物 publicPath 保持相对路径便于静态托管
|
||||
// - 开发环境走 proxy 转发后端,避免跨域
|
||||
import routes from './routes';
|
||||
import proxy from './proxy';
|
||||
|
||||
const { REACT_APP_ENV } = process.env as any;
|
||||
const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
export default {
|
||||
hash: true,
|
||||
// 资源路径:开发用根路径,生产为相对路径
|
||||
publicPath: isDev ? '/' : './',
|
||||
antd: {},
|
||||
// 页面 meta 标签
|
||||
metas: [
|
||||
{ charset: 'utf-8' },
|
||||
{ name: 'viewport', content: 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' },
|
||||
],
|
||||
// 主题(现代风格 + 红绿配主色)
|
||||
theme: {
|
||||
'primary-color': '#ff4d4f',
|
||||
'border-radius-base': '8px',
|
||||
'box-shadow-base': '0 8px 32px rgba(0, 0, 0, 0.1)',
|
||||
'animation-duration-slow': '0.4s',
|
||||
'animation-duration-base': '0.3s',
|
||||
'animation-duration-fast': '0.2s',
|
||||
},
|
||||
// 关闭 i18n,多语言后续按需启用
|
||||
locale: { antd: false, default: 'zh-CN', baseNavigator: true },
|
||||
// 使用按需编译的动态导入,提升首屏
|
||||
dynamicImport: { loading: '@/components/PageLoading' },
|
||||
// 路由采用显式配置
|
||||
routes,
|
||||
// 历史模式
|
||||
history: { type: 'browser' },
|
||||
// Dev 代理
|
||||
proxy: (proxy as any)[REACT_APP_ENV || 'dev'],
|
||||
// 构建优化
|
||||
nodeModulesTransform: { type: 'none' },
|
||||
mfsu: false,
|
||||
fastRefresh: {},
|
||||
} as any;
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* 开发代理配置(仅 dev 生效)
|
||||
* - 统一网关转发:仅代理 /api- 前缀到网关(/api-user、/api-uaa 等)
|
||||
* - 生产环境由网关/容器转发,此文件不生效
|
||||
*/
|
||||
const GATEWAY = process.env.GATEWAY_ORIGIN || 'http://127.0.0.1:9900';
|
||||
|
||||
export default {
|
||||
dev: {
|
||||
// 单一规则覆盖所有微服务前缀:/api-*
|
||||
'/api-': { target: GATEWAY, changeOrigin: true },
|
||||
},
|
||||
test: {
|
||||
'/api-': { target: GATEWAY, changeOrigin: true },
|
||||
},
|
||||
pre: {
|
||||
'/api-': { target: GATEWAY, changeOrigin: true },
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
export default [
|
||||
{ path: '/user/login', component: '@/pages/user/Login' },
|
||||
{
|
||||
path: '/',
|
||||
component: '@/layouts/BasicLayout',
|
||||
routes: [
|
||||
{ path: '/', redirect: '/welcome' },
|
||||
{ path: '/welcome', component: '@/pages/Welcome' },
|
||||
{
|
||||
path: '/system',
|
||||
routes: [
|
||||
{ path: '/system/tokens.html', component: '@/pages/system/Token' },
|
||||
{ path: '/system/menus.html', component: '@/pages/system/Menu' },
|
||||
{ path: '/system/role.html', component: '@/pages/system/Role' },
|
||||
{ path: '/system/user.html', component: '@/pages/system/User' },
|
||||
{ path: '/system/tenant.html', component: '@/pages/system/TenantManage' },
|
||||
{ path: '/system/miniApp.html', component: '@/pages/system/MiniApp' },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/orders',
|
||||
routes: [
|
||||
{ path: '/orders/order.html', component: '@/pages/orders/Order' },
|
||||
{ path: '/orders/orderFiles.html', component: '@/pages/orders/OrderFile' },
|
||||
{ path: '/orders/qrcode.html', component: '@/pages/orders/Qrcode' },
|
||||
{ path: '/orders/tourism.html', component: '@/pages/orders/Tourism' },
|
||||
{ path: '/orders/tourismFile.html', component: '@/pages/orders/TourismFile' },
|
||||
{ path: '/orders/homeCarousel.html', component: '@/pages/orders/HomeCarousel' },
|
||||
{ path: '/orders/refund.html', component: '@/pages/orders/Refund' },
|
||||
{ path: '/orders/statistics.html', component: '@/pages/orders/Statistics' },
|
||||
{ path: '/orders/profitSharing.html', component: '@/pages/orders/ProfitSharing' },
|
||||
{ path: '/orders/profit-sharing/statistics.html', component: '@/pages/orders/ProfitSharing/Statistics' },
|
||||
{ path: '/orders/videoTemplate.html', component: '@/pages/orders/VideoTemplate' },
|
||||
{ path: '/orders/editTask.html', component: '@/pages/orders/EditTask' },
|
||||
{ path: '/orders/wxMessage.html', component: '@/pages/orders/WxMessage' },
|
||||
{ path: '/orders/coupon.html', component: '@/pages/orders/Coupon' },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/device',
|
||||
routes: [
|
||||
{ path: '/device/wayline.html', component: '@/pages/device/Wayline' },
|
||||
{ path: '/device/device.html', component: '@/pages/device/Device' },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/log',
|
||||
routes: [
|
||||
{ path: '/log/sysLog.html', component: '@/pages/log/SysLog' },
|
||||
{ path: '/log/auditLog.html', component: '@/pages/log/AuditLog' },
|
||||
{ path: '/log/slowQueryLog.html', component: '@/pages/log/SlowSqlLog' },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/search',
|
||||
routes: [
|
||||
{ path: '/search/index_manager.html', component: '@/pages/search/Index' },
|
||||
{ path: '/search/user_search.html', component: '@/pages/search/User' },
|
||||
],
|
||||
},
|
||||
{ path: '/message/message.html', component: '@/pages/message' },
|
||||
{
|
||||
path: '/files',
|
||||
routes: [
|
||||
{ path: '/files/files.html', component: '@/pages/files/File' },
|
||||
],
|
||||
},
|
||||
{ path: '/generator/list.html', component: '@/pages/system/Generator' },
|
||||
{ path: '/attestation/app.html', component: '@/pages/system/App' },
|
||||
{ path: '/system/myInfo.html', component: '@/pages/system/UserInfo' },
|
||||
{ component: '@/pages/404' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "react-web-next",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://127.0.0.1:9900 umi dev",
|
||||
"start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://127.0.0.1:9900 umi dev",
|
||||
"start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev",
|
||||
"start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev",
|
||||
"build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build",
|
||||
"lint": "eslint --ext .ts,.tsx src",
|
||||
"tsc": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/pro-components": "1.1.1",
|
||||
"@ant-design/pro-layout": "^7.22.7",
|
||||
"antd": "^4.20.0",
|
||||
"file-saver": "^2.0.5",
|
||||
"jsencrypt": "^3.5.4",
|
||||
"lodash": "^4.17.21",
|
||||
"moment": "^2.29.0",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"umi": "^3.5.0",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/react": "^17.0.0",
|
||||
"@types/react-dom": "^17.0.0",
|
||||
"@umijs/preset-react": "^2.1.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"typescript": "^4.5.0"
|
||||
},
|
||||
"overrides": {
|
||||
"path-to-regexp": "^3.3.0",
|
||||
"postcss": "^7.0.39",
|
||||
"@babel/runtime": "^7.26.10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
(占位文件)此目录用于存放静态资源(如 favicon、静态图标)。
|
||||
本项目主要通过 src/assets 引入资源;若无静态文件需求,此目录可保持为空。
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.6 KiB |
@@ -0,0 +1,61 @@
|
||||
// 避免类型耦合,使用 any 降级
|
||||
import './global.less';
|
||||
import React from 'react';
|
||||
import { ThemeProvider } from './theme';
|
||||
import { history } from 'umi';
|
||||
|
||||
export function rootContainer(container: React.ReactNode, _args?: any) {
|
||||
return React.createElement(ThemeProvider, null, container);
|
||||
}
|
||||
|
||||
// 使用简化的 request 配置,避免与类型强绑定(兼容 umi 3)
|
||||
export const request: any = {
|
||||
errorConfig: {
|
||||
errorHandler(error: any) {
|
||||
// 可在此处统一处理错误,如通知等
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
requestInterceptors: [
|
||||
(url: string, options: any) => {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
const headers: Record<string, string> = { ...(options?.headers as any) };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
return { url, options: { ...options, headers } };
|
||||
},
|
||||
],
|
||||
responseInterceptors: [
|
||||
async (response: Response) => {
|
||||
// 兼容后端 Result 结构
|
||||
try {
|
||||
const cloned = response.clone();
|
||||
const data = await cloned.json();
|
||||
if (data && typeof (data as any).resp_code !== 'undefined') {
|
||||
const mapped = {
|
||||
success: (data as any).resp_code === 0,
|
||||
code: (data as any).resp_code,
|
||||
msg: (data as any).resp_msg,
|
||||
data: (data as any).data,
|
||||
} as any;
|
||||
(response as any).data = mapped;
|
||||
}
|
||||
} catch (e) {
|
||||
// 静默处理解析错误
|
||||
}
|
||||
return response;
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// 简单路由守卫:未登录访问受保护路由时跳回登录;已登录访问登录页时跳到欢迎页
|
||||
export function onRouteChange({ location }: any) {
|
||||
try {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
const isLoginPath = String(location?.pathname || '').startsWith('/user/login');
|
||||
if (!token && !isLoginPath) {
|
||||
history.push('/user/login');
|
||||
} else if (token && isLoginPath) {
|
||||
history.push('/welcome');
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.9 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.6 KiB |
@@ -0,0 +1,36 @@
|
||||
import React from 'react';
|
||||
import { Spin } from 'antd';
|
||||
import { LoadingOutlined } from '@ant-design/icons';
|
||||
|
||||
const PageLoading: React.FC = () => {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
height: '100vh',
|
||||
background: 'var(--bg-primary, #0f1419)',
|
||||
color: 'var(--text-primary, #ffffff)'
|
||||
}}
|
||||
>
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<Spin
|
||||
indicator={<LoadingOutlined style={{ fontSize: 32, color: '#667eea' }} spin />}
|
||||
size="large"
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
fontSize: 16,
|
||||
color: 'var(--text-secondary, #a0a6b8)'
|
||||
}}
|
||||
>
|
||||
正在加载...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageLoading;
|
||||
@@ -0,0 +1,51 @@
|
||||
.secure-login-form {
|
||||
max-width: 400px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
|
||||
.password-strength {
|
||||
margin-bottom: 16px;
|
||||
|
||||
.strength-label {
|
||||
font-size: 12px;
|
||||
margin-bottom: 4px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.strength-suggestions {
|
||||
font-size: 11px;
|
||||
color: #999;
|
||||
margin-top: 4px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-form-item {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.ant-input-affix-wrapper-lg,
|
||||
.ant-input-password-large {
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.ant-btn-lg {
|
||||
height: 48px;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
// 深色主题适配
|
||||
.dark-theme {
|
||||
.secure-login-form {
|
||||
.password-strength {
|
||||
.strength-label {
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
.strength-suggestions {
|
||||
color: #aaa;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Form, Input, Button, message, Progress } from 'antd';
|
||||
import { UserOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
|
||||
import { useSecurity } from '../../hooks/useSecurity';
|
||||
import './index.less';
|
||||
|
||||
interface LoginFormData {
|
||||
username: string;
|
||||
password: string;
|
||||
rememberMe?: boolean;
|
||||
}
|
||||
|
||||
interface SecureLoginFormProps {
|
||||
onLogin: (loginData: LoginFormData) => Promise<void>;
|
||||
loading?: boolean;
|
||||
showPasswordStrength?: boolean;
|
||||
}
|
||||
|
||||
const SecureLoginForm: React.FC<SecureLoginFormProps> = ({
|
||||
onLogin,
|
||||
loading = false,
|
||||
showPasswordStrength = true
|
||||
}) => {
|
||||
const [form] = Form.useForm();
|
||||
const { secureLogin, validatePassword, isEncrypting } = useSecurity();
|
||||
const [passwordStrength, setPasswordStrength] = useState<{
|
||||
level: 'weak' | 'medium' | 'strong';
|
||||
score: number;
|
||||
suggestions: string[];
|
||||
} | null>(null);
|
||||
|
||||
/**
|
||||
* 密码输入变化处理
|
||||
*/
|
||||
const handlePasswordChange = (value: string) => {
|
||||
if (showPasswordStrength && value) {
|
||||
const strength = validatePassword(value);
|
||||
setPasswordStrength(strength);
|
||||
} else {
|
||||
setPasswordStrength(null);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 表单提交处理
|
||||
*/
|
||||
const handleSubmit = async (values: LoginFormData) => {
|
||||
try {
|
||||
// 使用安全登录处理
|
||||
const secureData = await secureLogin(values);
|
||||
if (!secureData) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 调用父组件的登录方法
|
||||
await onLogin(secureData);
|
||||
} catch (error) {
|
||||
console.error('登录失败:', error);
|
||||
message.error('登录失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取密码强度颜色
|
||||
*/
|
||||
const getPasswordStrengthColor = (level: string) => {
|
||||
switch (level) {
|
||||
case 'weak':
|
||||
return '#ff4d4f';
|
||||
case 'medium':
|
||||
return '#faad14';
|
||||
case 'strong':
|
||||
return '#52c41a';
|
||||
default:
|
||||
return '#d9d9d9';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="secure-login-form">
|
||||
<Form
|
||||
form={form}
|
||||
onFinish={handleSubmit}
|
||||
autoComplete="off"
|
||||
layout="vertical"
|
||||
>
|
||||
<Form.Item
|
||||
name="username"
|
||||
rules={[
|
||||
{ required: true, message: '请输入用户名' },
|
||||
{ min: 2, message: '用户名至少2个字符' }
|
||||
]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined />}
|
||||
placeholder="用户名"
|
||||
size="large"
|
||||
autoComplete="username"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="password"
|
||||
rules={[
|
||||
{ required: true, message: '请输入密码' },
|
||||
{ min: 6, message: '密码至少6个字符' }
|
||||
]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined />}
|
||||
placeholder="密码"
|
||||
size="large"
|
||||
iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
|
||||
autoComplete="current-password"
|
||||
onChange={(e) => handlePasswordChange(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{/* 密码强度指示器 */}
|
||||
{showPasswordStrength && passwordStrength && (
|
||||
<div className="password-strength">
|
||||
<div className="strength-label">
|
||||
密码强度: <span style={{ color: getPasswordStrengthColor(passwordStrength.level) }}>
|
||||
{passwordStrength.level === 'weak' ? '弱' :
|
||||
passwordStrength.level === 'medium' ? '中等' : '强'}
|
||||
</span>
|
||||
</div>
|
||||
<Progress
|
||||
percent={passwordStrength.score}
|
||||
strokeColor={getPasswordStrengthColor(passwordStrength.level)}
|
||||
showInfo={false}
|
||||
size="small"
|
||||
/>
|
||||
{passwordStrength.suggestions.length > 0 && (
|
||||
<div className="strength-suggestions">
|
||||
建议: {passwordStrength.suggestions.join('、')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Form.Item>
|
||||
<Button
|
||||
type="primary"
|
||||
htmlType="submit"
|
||||
size="large"
|
||||
loading={loading || isEncrypting}
|
||||
block
|
||||
>
|
||||
{isEncrypting ? '加密中...' : '登录'}
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SecureLoginForm;
|
||||
@@ -0,0 +1,77 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Space, Button, TreeSelect, Checkbox, message } from 'antd';
|
||||
import { tenantApi, TenantTreeNode } from '@/services/tenant';
|
||||
|
||||
interface Props {
|
||||
// 当租户或“包含子租户”变更后回调
|
||||
onChanged?: (tenantId: string, includeChildren: boolean) => void;
|
||||
}
|
||||
|
||||
const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
|
||||
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
||||
const [tenantId, setTenantId] = useState<string | undefined>();
|
||||
const [includeChildren, setIncludeChildren] = useState(true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [treeRes, currentRes] = await Promise.all([
|
||||
tenantApi.getAccessibleTenants(),
|
||||
tenantApi.getCurrentTenant(),
|
||||
]);
|
||||
if (treeRes.success) setTree(treeRes.data || []);
|
||||
if (currentRes.success) setTenantId(currentRes.data?.tenantId);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const toTreeData = (nodes: TenantTreeNode[]): any[] =>
|
||||
nodes?.map((n) => ({
|
||||
title: n.tenantName,
|
||||
value: n.tenantId,
|
||||
key: n.tenantId,
|
||||
children: n.children ? toTreeData(n.children) : undefined,
|
||||
})) || [];
|
||||
|
||||
const handleApply = async () => {
|
||||
if (!tenantId) return;
|
||||
try {
|
||||
const res = await tenantApi.switchTenant(tenantId);
|
||||
if (res.success) {
|
||||
message.success('租户范围已更新');
|
||||
onChanged?.(tenantId, includeChildren);
|
||||
} else {
|
||||
message.error(res.msg || '切换失败');
|
||||
}
|
||||
} catch (e) {
|
||||
message.error('切换失败');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Space>
|
||||
<TreeSelect
|
||||
style={{ minWidth: 260 }}
|
||||
treeDefaultExpandAll
|
||||
loading={loading}
|
||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||
placeholder="选择租户(含子租户)"
|
||||
value={tenantId}
|
||||
onChange={(val) => setTenantId(val)}
|
||||
treeData={toTreeData(tree)}
|
||||
/>
|
||||
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>
|
||||
包含子租户
|
||||
</Checkbox>
|
||||
<Button type="primary" onClick={handleApply}>
|
||||
应用
|
||||
</Button>
|
||||
</Space>
|
||||
);
|
||||
};
|
||||
|
||||
export default TenantScopeFilter;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user