package middleware import ( "context" "net/http" "strings" "aggios-app/backend/internal/repository" ) type tenantContextKey string const TenantIDKey tenantContextKey = "tenantID" const SubdomainKey tenantContextKey = "subdomain" // TenantDetector detects tenant from subdomain func TenantDetector(tenantRepo *repository.TenantRepository) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { host := r.Host // Extract subdomain // Examples: // - agencia-xyz.localhost -> agencia-xyz // - agencia-xyz.aggios.app -> agencia-xyz // - dash.localhost -> dash (master admin) // - localhost -> (institutional site) parts := strings.Split(host, ".") var subdomain string if len(parts) >= 2 { // Has subdomain subdomain = parts[0] // Remove port if present if strings.Contains(subdomain, ":") { subdomain = strings.Split(subdomain, ":")[0] } } // Add subdomain to context ctx := context.WithValue(r.Context(), SubdomainKey, subdomain) // If subdomain is not empty and not "dash" or "api", try to find tenant if subdomain != "" && subdomain != "dash" && subdomain != "api" && subdomain != "localhost" { tenant, err := tenantRepo.FindBySubdomain(subdomain) if err == nil && tenant != nil { ctx = context.WithValue(ctx, TenantIDKey, tenant.ID.String()) } } next.ServeHTTP(w, r.WithContext(ctx)) }) } }