mengstack-website/guide/multi-tenancy.md
2026-10-02 23:55:36 +08:00

59 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 多租户系统
MengStack 内置多租户支持,通过 `X-Tenant-ID` 请求头实现租户隔离。
## 工作原理
```
┌─────────┐ ┌─────────┐
│ Tenant A │──X-Tenant-ID: A──→│ │──WHERE tenant_id='A'──→ DB
├─────────┤ │ MengStack │
│ Tenant B │──X-Tenant-ID: B──→│ Server │──WHERE tenant_id='B'──→ DB
├─────────┤ │ │
│ Tenant C │──X-Tenant-ID: C──→│ │──WHERE tenant_id='C'──→ DB
└─────────┘ └─────────┘
```
每个请求必须携带 `X-Tenant-ID` 头,中间件自动提取并注入到上下文中。
## 使用方式
### 请求示例
```bash
curl http://localhost:2222/api/v1/profile \
-H "Authorization: Bearer <token>" \
-H "X-Tenant-ID: tenant-001"
```
### 中间件处理
认证中间件自动验证:
1. 解析 JWT Token 获取用户信息
2. 验证 `X-Tenant-ID` 头是否存在
3. 将 `user_id` 和 `tenant_id` 注入到 Gin Context
4. 下游 Handler 可直接使用 `c.GetUint("user_id")` 和 `c.GetString("tenant_id")`
### 数据层隔离
Repository 层自动添加租户过滤:
```go
func (r *GormUserRepository) FindByTenant(ctx context.Context, tenantID string) ([]*domain.User, error) {
var users []*domain.User
err := r.db.Where("tenant_id = ?", tenantID).Find(&users).Error
return users, err
}
```
## 租户注册
租户管理是独立模块(M4 里程碑),当前版本通过手动在数据库创建租户记录。
## 安全考虑
- 中间件强制校验 `X-Tenant-ID`,缺失则返回 401
- 数据查询自动过滤,防止跨租户数据泄露
- JWT Token 中包含租户信息,服务端二次验证