64 lines
1.8 KiB
Go
64 lines
1.8 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"hfb_sys/backend/internal/config"
|
|
"hfb_sys/backend/internal/platformscope"
|
|
"hfb_sys/backend/internal/sitecode"
|
|
"hfb_sys/backend/internal/tenancy"
|
|
"hfb_sys/backend/pkg/response"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// RequireKnownApplicationHost prevents unknown hosts from falling through to
|
|
// legacy unscoped handlers when the application is reached without the Caddy
|
|
// on-demand TLS guard.
|
|
func RequireKnownApplicationHost(appEnv string, extraKnownHosts ...string) gin.HandlerFunc {
|
|
if !config.IsProductionEnv(appEnv) {
|
|
return func(c *gin.Context) { c.Next() }
|
|
}
|
|
knownHosts := make(map[string]struct{}, len(extraKnownHosts))
|
|
for _, rawHost := range extraKnownHosts {
|
|
if host := normalizeKnownHost(rawHost); host != "" {
|
|
knownHosts[host] = struct{}{}
|
|
}
|
|
}
|
|
return func(c *gin.Context) {
|
|
requestHost := sitecode.ExtractHost(c.Request.Host)
|
|
if _, ok := knownHosts[requestHost]; ok {
|
|
c.Next()
|
|
return
|
|
}
|
|
if platformscope.IsScope(c.Request.Context()) ||
|
|
tenancy.IDFromContext(c.Request.Context()) > 0 ||
|
|
sitecode.HasDomainScope(c.Request.Context()) ||
|
|
isInfrastructureOrCallbackPath(c.Request.URL.Path) {
|
|
c.Next()
|
|
return
|
|
}
|
|
response.Error(c, http.StatusNotFound, "site_not_found", "当前域名未配置站点")
|
|
c.Abort()
|
|
}
|
|
}
|
|
|
|
func normalizeKnownHost(raw string) string {
|
|
host := strings.TrimSpace(raw)
|
|
host = strings.TrimPrefix(host, "https://")
|
|
host = strings.TrimPrefix(host, "http://")
|
|
if slash := strings.IndexByte(host, '/'); slash >= 0 {
|
|
host = host[:slash]
|
|
}
|
|
return sitecode.ExtractHost(host)
|
|
}
|
|
|
|
func isInfrastructureOrCallbackPath(path string) bool {
|
|
switch path {
|
|
case "/health", "/health/ready", "/api/health", "/api/site/check-domain":
|
|
return true
|
|
}
|
|
return strings.HasPrefix(path, "/api/payments/") && strings.HasSuffix(path, "/notify")
|
|
}
|