feat(tenant): 增加租户基础与域名解析
This commit is contained in:
@@ -21,6 +21,10 @@ REDIS_DB=0
|
||||
|
||||
JWT_SECRET=change-me
|
||||
|
||||
# 经营租户域名;本地留空时通过 X-Tenant-Code 或旧分销站点方式调试。
|
||||
CADDY_DOMAIN=
|
||||
TENANT_JIEYOU_DOMAIN=
|
||||
|
||||
# 前端后台页面入口;本地默认 /admin,生产建议改成不公开的单段路径。
|
||||
VITE_ADMIN_BASE_PATH=/admin
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ APP_ADDR=:8080
|
||||
# Caddy 自动申请和续签 HTTPS 证书使用。
|
||||
CADDY_DOMAIN=hfb.221329.cc.cd
|
||||
CADDY_EMAIL=admin@example.com
|
||||
# 解忧商行前台域名;未启用解忧时留空。
|
||||
TENANT_JIEYOU_DOMAIN=zuhaox.com
|
||||
# 选号网(hfb_show)独立域名,与主站同机;不部署选号网可留空。
|
||||
# CADDY_SHOW_DOMAIN=show.example.com
|
||||
# 选号网源码目录(相对 hfb_sys 根或绝对路径),默认 ../hfb_show
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/paymentconfig"
|
||||
"hfb_sys/backend/internal/modules/systemconfig"
|
||||
"hfb_sys/backend/internal/router"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
@@ -84,6 +85,12 @@ func main() {
|
||||
}); err != nil {
|
||||
logger.Fatal("初始管理员创建失败", zap.Error(err))
|
||||
}
|
||||
if err := tenancy.BootstrapDomains(context.Background(), db, tenancy.BootstrapConfig{
|
||||
PrimaryDomain: cfg.PrimaryDomain,
|
||||
JieyouDomain: cfg.TenantJieyouDomain,
|
||||
}); err != nil {
|
||||
logger.Fatal("经营租户域名初始化失败", zap.Error(err))
|
||||
}
|
||||
}
|
||||
redisClient, err := database.OpenRedis(context.Background(), database.RedisConfig{
|
||||
Addr: cfg.RedisAddr,
|
||||
|
||||
@@ -24,6 +24,8 @@ type Config struct {
|
||||
BootstrapAdminUsername string
|
||||
BootstrapAdminPassword string
|
||||
BootstrapAdminNickname string
|
||||
PrimaryDomain string
|
||||
TenantJieyouDomain string
|
||||
Storage StorageConfig
|
||||
StorageMirror StorageConfig
|
||||
SMS SMSConfig
|
||||
@@ -102,6 +104,8 @@ func Load() Config {
|
||||
BootstrapAdminUsername: getEnv("ADMIN_BOOTSTRAP_USERNAME", ""),
|
||||
BootstrapAdminPassword: getEnv("ADMIN_BOOTSTRAP_PASSWORD", ""),
|
||||
BootstrapAdminNickname: getEnv("ADMIN_BOOTSTRAP_NICKNAME", "超级管理员"),
|
||||
PrimaryDomain: strings.TrimSpace(getEnv("CADDY_DOMAIN", "")),
|
||||
TenantJieyouDomain: strings.TrimSpace(getEnv("TENANT_JIEYOU_DOMAIN", "")),
|
||||
Storage: StorageConfig{
|
||||
Endpoint: getEnv("STORAGE_ENDPOINT", "http://localhost:19090"),
|
||||
Bucket: getEnv("STORAGE_BUCKET", "hfb-sys"),
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type Tenant struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
Code string `gorm:"size:32;not null;uniqueIndex:uk_tenants_code" json:"code"`
|
||||
Name string `gorm:"size:64;not null" json:"name"`
|
||||
Status string `gorm:"size:16;not null;default:'active';index" json:"status"`
|
||||
ProfileJSON datatypes.JSON `gorm:"type:json" json:"profile_json"`
|
||||
FeaturesJSON datatypes.JSON `gorm:"type:json" json:"features_json"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Tenant) TableName() string {
|
||||
return "tenants"
|
||||
}
|
||||
|
||||
type TenantDomain struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;index:idx_tenant_domains_tenant" json:"tenant_id"`
|
||||
Host string `gorm:"size:255;not null;uniqueIndex:uk_tenant_domains_host" json:"host"`
|
||||
DomainType string `gorm:"size:32;not null;default:'storefront'" json:"domain_type"`
|
||||
Status string `gorm:"size:16;not null;default:'active';index:idx_tenant_domains_tenant" json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (TenantDomain) TableName() string {
|
||||
return "tenant_domains"
|
||||
}
|
||||
|
||||
type TenantListingOffer struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;uniqueIndex:uk_tenant_listing_offers_listing;index:idx_tenant_listing_offers_display" json:"tenant_id"`
|
||||
ListingID uint64 `gorm:"not null;uniqueIndex:uk_tenant_listing_offers_listing;index:idx_tenant_listing_offers_display" json:"listing_id"`
|
||||
DisplayStatus string `gorm:"size:16;not null;default:'enabled';index:idx_tenant_listing_offers_display" json:"display_status"`
|
||||
PriceCent *int64 `json:"price_cent"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (TenantListingOffer) TableName() string {
|
||||
return "tenant_listing_offers"
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
@@ -43,6 +44,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/user"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/modules/withdrawal"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
_ "hfb_sys/backend/docs" // Swagger 文档
|
||||
|
||||
@@ -64,6 +66,12 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
engine.Use(middleware.RequestID())
|
||||
engine.Use(middleware.RequestLogger(logger))
|
||||
engine.Use(middleware.Recovery(logger))
|
||||
var tenantRepo *tenancy.Repository
|
||||
if deps.DB != nil {
|
||||
tenantRepo = tenancy.NewRepository(deps.DB)
|
||||
engine.Use(middleware.TenantContext(tenantRepo, cfg.AppEnv, logger))
|
||||
}
|
||||
tenantHandler := tenancy.NewHandler()
|
||||
jwtManager := auth.NewJWTManager(cfg.JWTSecret)
|
||||
|
||||
health := handler.NewHealthHandler(newReadinessChecks(deps))
|
||||
@@ -462,6 +470,33 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
api.GET("/home-announcements", systemConfigHandler.HomeAnnouncements)
|
||||
api.GET("/mobile-home-config", systemConfigHandler.HomeConfig)
|
||||
api.GET("/public/files/object", fileHandler.PublicObject)
|
||||
api.GET("/site/context", tenantHandler.SiteContext)
|
||||
api.GET("/site/check-domain", func(c *gin.Context) {
|
||||
domain := strings.TrimSpace(c.Query("domain"))
|
||||
if domain == "" {
|
||||
c.String(http.StatusBadRequest, "domain required")
|
||||
return
|
||||
}
|
||||
if tenantRepo != nil {
|
||||
allowed, err := tenantRepo.IsActiveDomain(c.Request.Context(), domain)
|
||||
if err != nil {
|
||||
c.String(http.StatusServiceUnavailable, "tenant domain check failed")
|
||||
return
|
||||
}
|
||||
if allowed {
|
||||
c.String(http.StatusOK, "ok")
|
||||
return
|
||||
}
|
||||
}
|
||||
if distributionService != nil {
|
||||
info, err := distributionService.GetPublicSiteInfo(c.Request.Context(), "", domain)
|
||||
if err == nil && info != nil && info.Status == "active" {
|
||||
c.String(http.StatusOK, "ok")
|
||||
return
|
||||
}
|
||||
}
|
||||
c.String(http.StatusNotFound, "domain not allowed")
|
||||
})
|
||||
// Gin 同一前缀只能有一种通配符名;管理端已用 /sites/:id/*,公开列表必须同名。
|
||||
api.GET("/distribution/sites/:id/listings", distributionHandler.ListPublicSiteListings)
|
||||
api.GET("/distribution/site-info", distributionHandler.GetPublicSiteInfo)
|
||||
|
||||
@@ -3,10 +3,12 @@ package router
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -56,6 +58,8 @@ func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) {
|
||||
"PUT /api/admin/roles/:id/permissions",
|
||||
"PUT /api/admin/admin-users/:id/password",
|
||||
"POST /api/admin/announcements/:id/publish",
|
||||
"GET /api/site/context",
|
||||
"GET /api/site/check-domain",
|
||||
"GET /api/distribution/sites/:id/listings",
|
||||
"GET /api/distribution/sites/:id/wallet",
|
||||
} {
|
||||
@@ -64,3 +68,71 @@ func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSiteContextRouteUsesTenantHost(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenant := model.Tenant{
|
||||
Code: "jieyou",
|
||||
Name: "解忧商行",
|
||||
Status: "active",
|
||||
ProfileJSON: []byte(`{"site_name":"解忧商行","logo_url":"https://cdn.example/logo.png"}`),
|
||||
FeaturesJSON: []byte(
|
||||
`{"rental_listing":true}`,
|
||||
),
|
||||
}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("create tenant: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.TenantDomain{
|
||||
TenantID: tenant.ID,
|
||||
Host: "zuhaox.com",
|
||||
DomainType: "storefront",
|
||||
Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create tenant domain: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.DistributionSite{
|
||||
SiteCode: "legacy_dist",
|
||||
SiteName: "历史分销站",
|
||||
Domain: "legacy.example.com",
|
||||
Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create legacy distribution site: %v", err)
|
||||
}
|
||||
|
||||
engine := New(testConfig(), Dependencies{DB: db}, zap.NewNop())
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/site/context", nil)
|
||||
req.Host = "zuhaox.com"
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, want := range []string{`"tenant_code":"jieyou"`, `"site_name":"解忧商行"`, `"rental_listing":true`} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("body missing %s: %s", want, body)
|
||||
}
|
||||
}
|
||||
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/site/context", nil)
|
||||
req.Host = "unknown.example.com"
|
||||
rec = httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("unknown host status = %d, want 404", rec.Code)
|
||||
}
|
||||
|
||||
for domain, wantStatus := range map[string]int{
|
||||
"zuhaox.com": http.StatusOK,
|
||||
"legacy.example.com": http.StatusOK,
|
||||
"unknown.example.com": http.StatusNotFound,
|
||||
} {
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/site/check-domain?domain="+domain, nil)
|
||||
rec = httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != wantStatus {
|
||||
t.Fatalf("check domain %s status = %d, want %d; body=%s", domain, rec.Code, wantStatus, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
type Scope struct {
|
||||
TenantID uint64
|
||||
TenantCode string
|
||||
TenantName string
|
||||
TenantStatus string
|
||||
Host string
|
||||
DomainType string
|
||||
ProfileJSON datatypes.JSON
|
||||
FeaturesJSON datatypes.JSON
|
||||
}
|
||||
|
||||
func WithScope(ctx context.Context, scope Scope) context.Context {
|
||||
return context.WithValue(ctx, contextKey{}, scope)
|
||||
}
|
||||
|
||||
func FromContext(ctx context.Context) (Scope, bool) {
|
||||
scope, ok := ctx.Value(contextKey{}).(Scope)
|
||||
return scope, ok && scope.TenantID > 0
|
||||
}
|
||||
|
||||
func MustFromContext(ctx context.Context) Scope {
|
||||
scope, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
panic("tenant scope missing from context")
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
func (s Scope) Profile() map[string]any {
|
||||
return decodeJSONMap(s.ProfileJSON)
|
||||
}
|
||||
|
||||
func (s Scope) Features() map[string]any {
|
||||
return decodeJSONMap(s.FeaturesJSON)
|
||||
}
|
||||
|
||||
func decodeJSONMap(raw datatypes.JSON) map[string]any {
|
||||
if len(raw) == 0 {
|
||||
return map[string]any{}
|
||||
}
|
||||
var value map[string]any
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type SiteContextDTO struct {
|
||||
Mode string `json:"mode"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TenantCode string `json:"tenant_code"`
|
||||
TenantName string `json:"tenant_name"`
|
||||
Host string `json:"host"`
|
||||
DomainType string `json:"domain_type"`
|
||||
Status string `json:"status"`
|
||||
Profile map[string]any `json:"profile"`
|
||||
Features map[string]any `json:"features"`
|
||||
}
|
||||
|
||||
type Handler struct{}
|
||||
|
||||
func NewHandler() *Handler {
|
||||
return &Handler{}
|
||||
}
|
||||
|
||||
func (h *Handler) SiteContext(c *gin.Context) {
|
||||
scope, ok := FromContext(c.Request.Context())
|
||||
if !ok {
|
||||
response.Error(c, http.StatusNotFound, "site_not_found", "当前域名未配置站点")
|
||||
return
|
||||
}
|
||||
response.OK(c, SiteContextDTO{
|
||||
Mode: "tenant",
|
||||
TenantID: scope.TenantID,
|
||||
TenantCode: scope.TenantCode,
|
||||
TenantName: scope.TenantName,
|
||||
Host: scope.Host,
|
||||
DomainType: scope.DomainType,
|
||||
Status: scope.TenantStatus,
|
||||
Profile: scope.Profile(),
|
||||
Features: scope.Features(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("tenancy dependency unavailable")
|
||||
ErrTenantNotFound = errors.New("tenant not found")
|
||||
ErrDomainConflict = errors.New("tenant domain belongs to another tenant")
|
||||
)
|
||||
|
||||
const domainCacheTTL = time.Minute
|
||||
|
||||
type domainCacheEntry struct {
|
||||
scope *Scope
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
mu sync.RWMutex
|
||||
cache map[string]domainCacheEntry
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db, cache: make(map[string]domainCacheEntry)}
|
||||
}
|
||||
|
||||
func (r *Repository) ResolveHost(ctx context.Context, rawHost string) (*Scope, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
host := sitecode.ExtractHost(rawHost)
|
||||
if host == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if cached, ok := r.cachedHost(host); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
var row struct {
|
||||
TenantID uint64 `gorm:"column:tenant_id"`
|
||||
TenantCode string `gorm:"column:tenant_code"`
|
||||
TenantName string `gorm:"column:tenant_name"`
|
||||
TenantStatus string `gorm:"column:tenant_status"`
|
||||
Host string `gorm:"column:host"`
|
||||
DomainType string `gorm:"column:domain_type"`
|
||||
ProfileJSON []byte `gorm:"column:profile_json"`
|
||||
FeaturesJSON []byte `gorm:"column:features_json"`
|
||||
}
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("tenant_domains AS d").
|
||||
Select(`t.id AS tenant_id, t.code AS tenant_code, t.name AS tenant_name, t.status AS tenant_status,
|
||||
d.host, d.domain_type, t.profile_json, t.features_json`).
|
||||
Joins("JOIN tenants AS t ON t.id = d.tenant_id").
|
||||
Where("d.host = ? AND d.status = ? AND t.status = ?", host, "active", "active").
|
||||
Take(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
r.cacheHost(host, nil)
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
scope := &Scope{
|
||||
TenantID: row.TenantID,
|
||||
TenantCode: row.TenantCode,
|
||||
TenantName: row.TenantName,
|
||||
TenantStatus: row.TenantStatus,
|
||||
Host: row.Host,
|
||||
DomainType: row.DomainType,
|
||||
ProfileJSON: row.ProfileJSON,
|
||||
FeaturesJSON: row.FeaturesJSON,
|
||||
}
|
||||
r.cacheHost(host, scope)
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ResolveCode(ctx context.Context, code string) (*Scope, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
code = strings.TrimSpace(strings.ToLower(code))
|
||||
if code == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var tenant model.Tenant
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("code = ? AND status = ?", code, "active").
|
||||
First(&tenant).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &Scope{
|
||||
TenantID: tenant.ID,
|
||||
TenantCode: tenant.Code,
|
||||
TenantName: tenant.Name,
|
||||
TenantStatus: tenant.Status,
|
||||
DomainType: "development",
|
||||
ProfileJSON: tenant.ProfileJSON,
|
||||
FeaturesJSON: tenant.FeaturesJSON,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) IsActiveDomain(ctx context.Context, rawHost string) (bool, error) {
|
||||
scope, err := r.ResolveHost(ctx, rawHost)
|
||||
return scope != nil, err
|
||||
}
|
||||
|
||||
func (r *Repository) Invalidate() {
|
||||
r.mu.Lock()
|
||||
r.cache = make(map[string]domainCacheEntry)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *Repository) cachedHost(host string) (*Scope, bool) {
|
||||
r.mu.RLock()
|
||||
entry, ok := r.cache[host]
|
||||
r.mu.RUnlock()
|
||||
if !ok || time.Now().After(entry.expiresAt) {
|
||||
return nil, false
|
||||
}
|
||||
if entry.scope == nil {
|
||||
return nil, true
|
||||
}
|
||||
copied := *entry.scope
|
||||
return &copied, true
|
||||
}
|
||||
|
||||
func (r *Repository) cacheHost(host string, scope *Scope) {
|
||||
r.mu.Lock()
|
||||
r.cache[host] = domainCacheEntry{scope: scope, expiresAt: time.Now().Add(domainCacheTTL)}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
type BootstrapConfig struct {
|
||||
PrimaryDomain string
|
||||
JieyouDomain string
|
||||
}
|
||||
|
||||
func BootstrapDomains(ctx context.Context, db *gorm.DB, cfg BootstrapConfig) error {
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
primary := sitecode.ExtractHost(cfg.PrimaryDomain)
|
||||
jieyou := sitecode.ExtractHost(cfg.JieyouDomain)
|
||||
|
||||
if primary != "" {
|
||||
if err := repo.UpsertDomain(ctx, "dachui", primary, "storefront"); err != nil {
|
||||
return err
|
||||
}
|
||||
h5 := "h5." + primary
|
||||
if err := repo.UpsertDomain(ctx, "dachui", h5, "storefront_alias"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if jieyou != "" && jieyou != primary {
|
||||
if err := repo.UpsertDomain(ctx, "jieyou", jieyou, "storefront"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpsertDomain(ctx context.Context, tenantCode, rawHost, domainType string) error {
|
||||
if r == nil || r.db == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
host := sitecode.ExtractHost(rawHost)
|
||||
if host == "" {
|
||||
return nil
|
||||
}
|
||||
var tenant model.Tenant
|
||||
if err := r.db.WithContext(ctx).Where("code = ?", tenantCode).First(&tenant).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrTenantNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var existing model.TenantDomain
|
||||
err := tx.Where("host = ?", host).First(&existing).Error
|
||||
if err == nil {
|
||||
if existing.TenantID != tenant.ID {
|
||||
return ErrDomainConflict
|
||||
}
|
||||
return tx.Model(&existing).Updates(map[string]any{
|
||||
"domain_type": domainType,
|
||||
"status": "active",
|
||||
}).Error
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.TenantDomain{
|
||||
TenantID: tenant.ID,
|
||||
Host: host,
|
||||
DomainType: domainType,
|
||||
Status: "active",
|
||||
}).Error
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Invalidate()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
func setupTenantRepoTest(t *testing.T) (*Repository, model.Tenant, model.Tenant) {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
dachui := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
|
||||
jieyou := model.Tenant{Code: "jieyou", Name: "解忧商行", Status: "active"}
|
||||
if err := db.Create(&dachui).Error; err != nil {
|
||||
t.Fatalf("create dachui tenant: %v", err)
|
||||
}
|
||||
if err := db.Create(&jieyou).Error; err != nil {
|
||||
t.Fatalf("create jieyou tenant: %v", err)
|
||||
}
|
||||
return NewRepository(db), dachui, jieyou
|
||||
}
|
||||
|
||||
func TestResolveHostNormalizesAndIgnoresInactiveDomains(t *testing.T) {
|
||||
repo, dachui, jieyou := setupTenantRepoTest(t)
|
||||
if err := repo.UpsertDomain(t.Context(), "dachui", "hao858.com", "storefront"); err != nil {
|
||||
t.Fatalf("upsert dachui domain: %v", err)
|
||||
}
|
||||
if err := repo.db.Create(&model.TenantDomain{
|
||||
TenantID: jieyou.ID,
|
||||
Host: "disabled.example.com",
|
||||
DomainType: "storefront",
|
||||
Status: "disabled",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create disabled domain: %v", err)
|
||||
}
|
||||
|
||||
scope, err := repo.ResolveHost(t.Context(), "HAO858.COM:443")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve host: %v", err)
|
||||
}
|
||||
if scope == nil || scope.TenantID != dachui.ID || scope.TenantCode != "dachui" {
|
||||
t.Fatalf("resolved scope = %#v, want dachui", scope)
|
||||
}
|
||||
|
||||
scope, err = repo.ResolveHost(t.Context(), "disabled.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve disabled host: %v", err)
|
||||
}
|
||||
if scope != nil {
|
||||
t.Fatalf("disabled domain resolved to %#v", scope)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapDomainsIsIdempotentAndRejectsHostConflict(t *testing.T) {
|
||||
repo, _, _ := setupTenantRepoTest(t)
|
||||
cfg := BootstrapConfig{PrimaryDomain: "hao858.com", JieyouDomain: "zuhaox.com"}
|
||||
if err := BootstrapDomains(t.Context(), repo.db, cfg); err != nil {
|
||||
t.Fatalf("bootstrap domains: %v", err)
|
||||
}
|
||||
if err := BootstrapDomains(t.Context(), repo.db, cfg); err != nil {
|
||||
t.Fatalf("bootstrap domains second run: %v", err)
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := repo.db.Model(&model.TenantDomain{}).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count domains: %v", err)
|
||||
}
|
||||
if count != 3 {
|
||||
t.Fatalf("domain count = %d, want 3", count)
|
||||
}
|
||||
if err := repo.UpsertDomain(t.Context(), "jieyou", "hao858.com", "storefront"); !errors.Is(err, ErrDomainConflict) {
|
||||
t.Fatalf("conflicting domain error = %v, want ErrDomainConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveCode(t *testing.T) {
|
||||
repo, dachui, _ := setupTenantRepoTest(t)
|
||||
scope, err := repo.ResolveCode(t.Context(), " DAC HUI ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve empty code: %v", err)
|
||||
}
|
||||
if scope != nil {
|
||||
t.Fatalf("invalid code resolved to %#v", scope)
|
||||
}
|
||||
scope, err = repo.ResolveCode(t.Context(), "DACHUI")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve code: %v", err)
|
||||
}
|
||||
if scope == nil || scope.TenantID != dachui.ID {
|
||||
t.Fatalf("resolved scope = %#v, want dachui", scope)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenants (
|
||||
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||
code VARCHAR(32) NOT NULL,
|
||||
name VARCHAR(64) NOT NULL,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'active',
|
||||
profile_json JSON NULL,
|
||||
features_json JSON NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uk_tenants_code (code),
|
||||
KEY idx_tenants_status (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经营租户';
|
||||
|
||||
INSERT INTO tenants (code, name, status, profile_json, features_json)
|
||||
VALUES
|
||||
('dachui', '大锤商行', 'active', JSON_OBJECT('site_name', '大锤商行'), JSON_OBJECT()),
|
||||
('jieyou', '解忧商行', 'active', JSON_OBJECT('site_name', '解忧商行'), JSON_OBJECT())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
name = VALUES(name),
|
||||
status = VALUES(status),
|
||||
updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenant_domains (
|
||||
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||
tenant_id BIGINT UNSIGNED NOT NULL,
|
||||
host VARCHAR(255) NOT NULL,
|
||||
domain_type VARCHAR(32) NOT NULL DEFAULT 'storefront',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'active',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uk_tenant_domains_host (host),
|
||||
KEY idx_tenant_domains_tenant (tenant_id, domain_type, status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经营租户域名';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenant_listing_offers (
|
||||
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||
tenant_id BIGINT UNSIGNED NOT NULL,
|
||||
listing_id BIGINT UNSIGNED NOT NULL,
|
||||
display_status VARCHAR(16) NOT NULL DEFAULT 'enabled',
|
||||
price_cent BIGINT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uk_tenant_listing_offers_listing (tenant_id, listing_id),
|
||||
KEY idx_tenant_listing_offers_display (tenant_id, display_status, listing_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经营租户商品货架';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS tenant_listing_offers;
|
||||
DROP TABLE IF EXISTS tenant_domains;
|
||||
DROP TABLE IF EXISTS tenants;
|
||||
Reference in New Issue
Block a user