feat(tenant): 增加租户基础与域名解析
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
ContextTenantID = "tenant_id"
|
||||
ContextTenantCode = "tenant_code"
|
||||
tenantCodeHeader = "X-Tenant-Code"
|
||||
)
|
||||
|
||||
type TenantResolver interface {
|
||||
ResolveHost(ctx context.Context, host string) (*tenancy.Scope, error)
|
||||
ResolveCode(ctx context.Context, code string) (*tenancy.Scope, error)
|
||||
}
|
||||
|
||||
func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
return func(c *gin.Context) { c.Next() }
|
||||
}
|
||||
production := config.IsProductionEnv(appEnv)
|
||||
return func(c *gin.Context) {
|
||||
var (
|
||||
scope *tenancy.Scope
|
||||
err error
|
||||
)
|
||||
if !production {
|
||||
code := strings.TrimSpace(firstNonEmpty(c.GetHeader(tenantCodeHeader), c.Query("tenant_code")))
|
||||
if code != "" {
|
||||
scope, err = resolver.ResolveCode(c.Request.Context(), code)
|
||||
}
|
||||
}
|
||||
if scope == nil && err == nil {
|
||||
scope, err = resolver.ResolveHost(c.Request.Context(), c.Request.Host)
|
||||
}
|
||||
if err != nil && logger != nil {
|
||||
logger.Warn("经营租户解析失败,按旧站点上下文继续",
|
||||
zap.String("host", sitecode.ExtractHost(c.Request.Host)),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
if scope != nil {
|
||||
c.Request = c.Request.WithContext(tenancy.WithScope(c.Request.Context(), *scope))
|
||||
c.Set(ContextTenantID, scope.TenantID)
|
||||
c.Set(ContextTenantCode, scope.TenantCode)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func newTenantContextTestEngine(t *testing.T, appEnv string) (*gin.Engine, model.Tenant) {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
tenant := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("create tenant: %v", err)
|
||||
}
|
||||
repo := tenancy.NewRepository(db)
|
||||
if err := repo.UpsertDomain(t.Context(), tenant.Code, "hao858.com", "storefront"); err != nil {
|
||||
t.Fatalf("create domain: %v", err)
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(TenantContext(repo, appEnv, nil))
|
||||
engine.GET("/probe", func(c *gin.Context) {
|
||||
scope, ok := tenancy.FromContext(c.Request.Context())
|
||||
if !ok {
|
||||
c.JSON(http.StatusNotFound, gin.H{"found": false})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"tenant_id": scope.TenantID, "tenant_code": scope.TenantCode})
|
||||
})
|
||||
return engine, tenant
|
||||
}
|
||||
|
||||
func TestTenantContextResolvesHost(t *testing.T) {
|
||||
engine, tenant := newTenantContextTestEngine(t, "production")
|
||||
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
req.Host = "hao858.com"
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if body := rec.Body.String(); body == "" || !contains(body, `"tenant_id":`) {
|
||||
t.Fatalf("unexpected body: %s", body)
|
||||
}
|
||||
if tenant.ID == 0 {
|
||||
t.Fatal("tenant ID should not be zero")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantContextAllowsDevelopmentCodeAndIgnoresItInProduction(t *testing.T) {
|
||||
engine, _ := newTenantContextTestEngine(t, "development")
|
||||
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
req.Host = "localhost"
|
||||
req.Header.Set(tenantCodeHeader, "dachui")
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("development code status = %d, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
engine, _ = newTenantContextTestEngine(t, "production")
|
||||
req = httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
req.Host = "localhost"
|
||||
req.Header.Set(tenantCodeHeader, "dachui")
|
||||
rec = httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("production header status = %d, want 404", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(value, target string) bool {
|
||||
for i := 0; i+len(target) <= len(value); i++ {
|
||||
if value[i:i+len(target)] == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user