Files
AuthCentral/api/middlewares/dynamic_cors_middleware.go
Beyhan Oğur 8b1fbdee99 first commit
2026-04-26 21:37:58 +03:00

54 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middlewares
import (
"gauth-central/internal/services"
"net/http"
"github.com/gin-gonic/gin"
)
// DynamicCorsMiddleware - Database'den okunan CORS ayarlarıyla çalışan middleware
func DynamicCorsMiddleware(settingsService *services.SettingsService) gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
// If no origin header, skip CORS
if origin == "" {
c.Next()
return
}
// Check if origin is allowed
allowed, err := settingsService.IsOriginAllowed(origin)
if err != nil {
// On error, log and deny
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"error": "Failed to verify CORS policy",
})
return
}
if !allowed {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Origin not allowed by CORS policy",
})
return
}
// Set CORS headers
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Max-Age", "86400") // 24 hours
// Handle preflight requests
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}