b98cf3c718
用户可切活跃租户,消耗按"计费租户"扣(数据仍落活跃租户/工作区): - User.active_tenant_id(切换持久化)+ Tenant.shared_billing(每租户开关,默认关)。 - 中间件 ActiveTenantForUser:active_tenant_id 若有效(仍是成员)则用之,否则默认租户。 - 计费目标解析 ResolveBillingTenantID:本人是活跃租户 owner 或该租户 shared_billing 开 → 记活跃租户;否则记本人个人租户(各付各的)。SubmitTask 的硬拦截 + 用量都按它走。 - 接口:GET /me/tenants、POST /me/tenant(切换)、PUT /admin/tenants/:id/shared-billing; /tenants/current 改显"可花余额"(计费租户) + billing_shared 标记。 live 验证(demoB 是公司A 成员、个人租户=公司B):切到公司A 后—— shared OFF:任务落公司A 工作区、用量扣公司B(个人),公司A 不变; shared ON:用量扣公司A(共享),公司B 不变;/tenants/current 余额随之在 6.48↔15.92 切换。全过。 前端切换器 + admin 开关见后续。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
32 lines
1.3 KiB
Go
32 lines
1.3 KiB
Go
package middleware
|
||
|
||
import (
|
||
"github.com/gin-gonic/gin"
|
||
|
||
"github.com/sundynix/sundynix-gateway/internal/store"
|
||
)
|
||
|
||
// CtxTenantID 是鉴权后写入 gin.Context 的当前租户 ID 键。
|
||
const CtxTenantID = "tenant_id"
|
||
|
||
// TenantContext 解析当前用户的默认租户并注入 tenant_id(多租户作用域的事实源)。
|
||
// 须挂在 Auth 之后(依赖已注入的 uid);未登录请求跳过。存量/异常无租户者由 EnsureDefaultTenant
|
||
// 幂等兜底补建,保证任何已登录请求都能拿到 tenant_id。
|
||
//
|
||
// 注:当前每请求解析一次(1–2 条按索引查询)。后续可把 tenant_id 嵌入 JWT / 加缓存去掉此开销。
|
||
func TenantContext(db *store.Postgres) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
if v, ok := c.Get(CtxUserID); ok {
|
||
if uid, _ := v.(string); uid != "" {
|
||
if t, err := db.ActiveTenantForUser(c.Request.Context(), uid); err == nil && t != nil {
|
||
c.Set(CtxTenantID, t.ID)
|
||
// 注入请求 context:store 的 gorm 租户插件据此对受租户表自动加 tenant_id 过滤/填充。
|
||
// handler 须用 c.Request.Context() 调 store(现有代码已如此),隔离才会生效。
|
||
c.Request = c.Request.WithContext(store.WithTenant(c.Request.Context(), t.ID))
|
||
}
|
||
}
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|