package middleware import ( "mime" "net" "net/http" "net/url" "strings" "github.com/gin-gonic/gin" ) func CORS() gin.HandlerFunc { return func(c *gin.Context) { hostURL, hostErr := url.Parse("http://" + c.Request.Host) if hostErr != nil || hostURL.Host != c.Request.Host || hostURL.Path != "" || hostURL.RawQuery != "" || !isLoopbackOrigin("http://"+c.Request.Host) { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Invalid request host"}) return } if c.GetHeader("Sec-Fetch-Site") == "cross-site" { c.AbortWithStatus(http.StatusForbidden) return } if referer := c.GetHeader("Referer"); referer != "" && !isLoopbackOrigin(referer) { c.AbortWithStatus(http.StatusForbidden) return } origin := strings.TrimSpace(c.GetHeader("Origin")) if origin != "" { if isLoopbackOrigin(origin) { c.Header("Access-Control-Allow-Origin", origin) c.Header("Vary", "Origin") c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization") c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Disposition") c.Header("Access-Control-Max-Age", "86400") } else { c.AbortWithStatus(http.StatusForbidden) return } } if c.Request.Method == http.MethodOptions { c.AbortWithStatus(http.StatusNoContent) return } if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead && strings.HasPrefix(c.Request.URL.Path, "/api/") && c.Request.ContentLength != 0 { mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type")) isUpload := strings.HasPrefix(c.FullPath(), "/api/projects/") && strings.HasSuffix(c.FullPath(), "/vendor-import") if err != nil || (mediaType != "application/json" && !(isUpload && mediaType == "multipart/form-data")) { c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, gin.H{"error": "Unsupported content type"}) return } } c.Next() } } func isLoopbackOrigin(origin string) bool { u, err := url.Parse(origin) if err != nil { return false } if u.Scheme != "http" && u.Scheme != "https" { return false } if u.User != nil || u.Opaque != "" { return false } host := strings.TrimSpace(u.Hostname()) if host == "" { return false } if strings.EqualFold(host, "localhost") { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() }