66 lines
2.1 KiB
Go
66 lines
2.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"kra/app/system/internal/conf"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const (
|
|
defaultCORSHeaders = "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id"
|
|
defaultCORSMethods = "POST, GET, OPTIONS,DELETE,PUT"
|
|
defaultCORSExpose = "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At"
|
|
)
|
|
|
|
// CORS applies the current administration CORS rules on every request so a
|
|
// configuration reload takes effect without rebuilding the Gin engine.
|
|
func CORS(runtime *conf.Runtime) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
config := runtime.Admin()
|
|
if config == nil || config.Cors == nil {
|
|
c.Next()
|
|
return
|
|
}
|
|
mode := strings.TrimSpace(config.Cors.Mode)
|
|
origin := c.GetHeader("Origin")
|
|
corsHandled := false
|
|
if mode == "allow-all" {
|
|
setCORSHeaders(c, origin, defaultCORSHeaders, defaultCORSMethods, defaultCORSExpose, true)
|
|
corsHandled = true
|
|
} else if rule := matchingCORSRule(config.Cors.Whitelist, origin); rule != nil {
|
|
setCORSHeaders(c, rule.AllowOrigin, rule.AllowHeaders, rule.AllowMethods, rule.ExposeHeaders, rule.AllowCredentials)
|
|
corsHandled = true
|
|
} else if mode == "strict-whitelist" && !(c.Request.Method == http.MethodGet && c.Request.URL.Path == "/health") {
|
|
c.AbortWithStatus(http.StatusForbidden)
|
|
return
|
|
}
|
|
if corsHandled && c.Request.Method == http.MethodOptions {
|
|
c.AbortWithStatus(http.StatusNoContent)
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func matchingCORSRule(rules []*conf.AdminBackend_CORSRule, origin string) *conf.AdminBackend_CORSRule {
|
|
for _, rule := range rules {
|
|
if rule != nil && origin == rule.AllowOrigin {
|
|
return rule
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func setCORSHeaders(c *gin.Context, origin, headers, methods, expose string, credentials bool) {
|
|
c.Header("Access-Control-Allow-Origin", origin)
|
|
c.Header("Access-Control-Allow-Headers", headers)
|
|
c.Header("Access-Control-Allow-Methods", methods)
|
|
c.Header("Access-Control-Expose-Headers", expose)
|
|
if credentials {
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
|
}
|
|
}
|