2024-08-12 11:00:25 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
2025-03-28 02:00:55 -07:00
|
|
|
"net/http"
|
|
|
|
|
|
2024-08-12 11:00:25 +02:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
2024-08-17 21:57:14 +02:00
|
|
|
type CorsMiddleware struct{}
|
|
|
|
|
|
|
|
|
|
func NewCorsMiddleware() *CorsMiddleware {
|
|
|
|
|
return &CorsMiddleware{}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (m *CorsMiddleware) Add() gin.HandlerFunc {
|
2024-11-15 15:00:25 +01:00
|
|
|
return func(c *gin.Context) {
|
2025-05-08 21:56:17 +02:00
|
|
|
path := c.FullPath()
|
|
|
|
|
if path == "" {
|
|
|
|
|
// The router doesn't map preflight requests, so we need to use the raw URL path
|
|
|
|
|
path = c.Request.URL.Path
|
2025-04-09 09:18:03 +02:00
|
|
|
}
|
|
|
|
|
|
2025-05-08 21:56:17 +02:00
|
|
|
if !isCorsPath(path) {
|
|
|
|
|
c.Next()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
2025-06-02 15:55:29 +02:00
|
|
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization")
|
2025-05-08 21:56:17 +02:00
|
|
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST")
|
2024-11-15 15:00:25 +01:00
|
|
|
|
2025-05-08 21:56:17 +02:00
|
|
|
// Preflight request
|
2025-03-28 02:00:55 -07:00
|
|
|
if c.Request.Method == http.MethodOptions {
|
2024-11-15 15:00:25 +01:00
|
|
|
c.AbortWithStatus(204)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
|
}
|
2024-08-12 11:00:25 +02:00
|
|
|
}
|
2025-05-08 21:56:17 +02:00
|
|
|
|
|
|
|
|
func isCorsPath(path string) bool {
|
|
|
|
|
switch path {
|
|
|
|
|
case "/api/oidc/token",
|
|
|
|
|
"/api/oidc/userinfo",
|
|
|
|
|
"/oidc/end-session",
|
|
|
|
|
"/api/oidc/introspect",
|
|
|
|
|
"/.well-known/jwks.json",
|
|
|
|
|
"/.well-known/openid-configuration":
|
|
|
|
|
return true
|
|
|
|
|
default:
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|