Files
hfb_sys/backend/internal/tenancy/context.go
T

76 lines
1.5 KiB
Go

package tenancy
import (
"context"
"encoding/json"
"fmt"
"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 IDFromContext(ctx context.Context) uint64 {
scope, ok := FromContext(ctx)
if !ok {
return 0
}
return scope.TenantID
}
// ScopeKey returns a stable cache scope suffix. An empty string keeps legacy
// callers and tests on their existing unqualified keys.
func ScopeKey(ctx context.Context) string {
if tenantID := IDFromContext(ctx); tenantID > 0 {
return fmt.Sprintf("tenant:%d", tenantID)
}
return ""
}
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
}