57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// CORS middleware pour gérer les en-têtes CORS avec whitelist d'origins configurable
|
|
// allowedOrigins: liste des origines autorisées (ex: []string{"http://localhost:3000", "https://example.com"})
|
|
// Si "*" est dans la liste, toutes les origines sont autorisées
|
|
func CORS(allowedOrigins []string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
origin := c.GetHeader("Origin")
|
|
|
|
// Vérifier si l'origine est autorisée
|
|
if isAllowedOrigin(origin, allowedOrigins) {
|
|
c.Header("Access-Control-Allow-Origin", origin)
|
|
}
|
|
|
|
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With")
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
|
c.Header("Access-Control-Max-Age", "86400") // Cache preflight pour 24h
|
|
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// isAllowedOrigin vérifie si une origine est dans la liste des origines autorisées
|
|
func isAllowedOrigin(origin string, allowed []string) bool {
|
|
// Sécurité par défaut : si liste vide, on rejette tout
|
|
if len(allowed) == 0 {
|
|
return false
|
|
}
|
|
|
|
for _, o := range allowed {
|
|
// Permettre toutes les origines si "*" est dans la liste
|
|
// ATTENTION: À utiliser seulement en dev
|
|
if o == "*" {
|
|
return true
|
|
}
|
|
if o == origin {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// CORSDefault crée un middleware CORS avec une whitelist par défaut
|
|
// Utile pour compatibilité avec le code existant
|
|
func CORSDefault() gin.HandlerFunc {
|
|
return CORS([]string{"*"})
|
|
}
|