Skip to content

Commit

Permalink
Fix cors (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
pablomendezroyo authored Nov 26, 2024
1 parent cd4c69d commit c3a7c97
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 28 deletions.
38 changes: 24 additions & 14 deletions internal/adapters/api/api_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,33 +23,43 @@ type APIHandler struct {
// NewAPIAdapter initializes the APIHandler and sets up routes with CORS enabled
func NewAPIAdapter(storagePort ports.StoragePort, allowedOrigins []string) *APIHandler {
h := &APIHandler{
storagePort,
mux.NewRouter(),
"API",
StoragePort: storagePort,
Router: mux.NewRouter(),
adapterPrefix: "API",
}

// Set up API routes
h.SetupRoutes()

// Add CORS middleware to the router using the provided allowed origins
// Define CORS configuration
corsAllowedOrigins := handlers.AllowedOrigins(allowedOrigins)
corsAllowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})
corsAllowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS", "DELETE"})
corsAllowedHeaders := handlers.AllowedHeaders([]string{"Content-Type", "Authorization"})

h.Router.Use(func(next http.Handler) http.Handler {
return handlers.CORS(corsAllowedOrigins, corsAllowedMethods, corsAllowedHeaders)(next)
})
// Add CORS middleware globally
h.Router.Use(handlers.CORS(
corsAllowedOrigins,
corsAllowedMethods,
corsAllowedHeaders,
))

return h
}

// SetupRoutes sets up all the routes for the API
func (h *APIHandler) SetupRoutes() {
h.Router.HandleFunc("/api/v0/events_indexer/telegramConfig", h.UpdateTelegramConfig).Methods("POST")
h.Router.HandleFunc("/api/v0/events_indexer/telegramConfig", h.GetTelegramConfig).Methods("GET")
h.Router.HandleFunc("/api/v0/events_indexer/operatorId", h.AddOperator).Methods("POST")
h.Router.HandleFunc("/api/v0/events_indexer/operatorId", h.DeleteOperator).Methods("DELETE")
h.Router.HandleFunc("/api/v0/events_indexer/operator_performance", h.GetOperatorPerformance).Methods("GET")
h.Router.HandleFunc("/api/v0/events_indexer/exit_requests", h.GetExitRequests).Methods("GET")
// Define API endpoints
h.Router.HandleFunc("/api/v0/events_indexer/telegramConfig", h.UpdateTelegramConfig).Methods("POST", "OPTIONS")
h.Router.HandleFunc("/api/v0/events_indexer/telegramConfig", h.GetTelegramConfig).Methods("GET", "OPTIONS")
h.Router.HandleFunc("/api/v0/events_indexer/operatorId", h.AddOperator).Methods("POST", "OPTIONS")
h.Router.HandleFunc("/api/v0/events_indexer/operatorId", h.DeleteOperator).Methods("DELETE", "OPTIONS")
h.Router.HandleFunc("/api/v0/events_indexer/operator_performance", h.GetOperatorPerformance).Methods("GET", "OPTIONS")
h.Router.HandleFunc("/api/v0/events_indexer/exit_requests", h.GetExitRequests).Methods("GET", "OPTIONS")

// Add a generic OPTIONS handler to ensure preflight requests are handled
h.Router.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK) // Respond to OPTIONS requests with 200 OK
})
}

// GetTelegramConfig retrieves the Telegram configuration
Expand Down
34 changes: 20 additions & 14 deletions internal/adapters/proxyApi/proxy_api_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,30 @@ type APIHandler struct {
// NewProxyAPIAdapter initializes the APIHandler and sets up routes
func NewProxyAPIAdapter(allowedOrigins []string, proxyApiURL string) *APIHandler {
h := &APIHandler{
mux.NewRouter(),
proxyApiURL,
"PROXY-API",
Router: mux.NewRouter(),
proxyApiURL: proxyApiURL,
adapterPrefix: "PROXY-API",
}

h.SetupRoutes()

// Configure CORS middleware with restricted headers
// Configure CORS middleware
corsAllowedOrigins := handlers.AllowedOrigins(allowedOrigins)
corsAllowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})
corsAllowedHeaders := handlers.AllowedHeaders([]string{"Content-Type", "Authorization"})

h.Router.Use(func(next http.Handler) http.Handler {
return handlers.CORS(corsAllowedMethods, corsAllowedHeaders)(next)
})
h.Router.Use(handlers.CORS(
corsAllowedOrigins,
corsAllowedMethods,
corsAllowedHeaders,
))

return h
}

// SetupRoutes sets up all the routes for the Proxy API
func (h *APIHandler) SetupRoutes() {
h.Router.PathPrefix("/v1/").HandlerFunc(h.proxyHandler)
h.Router.PathPrefix("/v1/").HandlerFunc(h.proxyHandler).Methods("GET", "POST", "OPTIONS")
}

// proxyHandler handles all requests and proxies them to the target API
Expand All @@ -52,7 +55,7 @@ func (h *APIHandler) proxyHandler(w http.ResponseWriter, r *http.Request) {
return
}

// Append the incoming request's path to the target URL
// Append the incoming request's path and query parameters to the target URL
targetURL.Path = r.URL.Path
targetURL.RawQuery = r.URL.RawQuery

Expand All @@ -63,11 +66,8 @@ func (h *APIHandler) proxyHandler(w http.ResponseWriter, r *http.Request) {
return
}

// Copy headers from the original request, excluding the Origin header
// Copy headers from the original request
for key, values := range r.Header {
if key == "Origin" {
continue
}
for _, value := range values {
proxyReq.Header.Add(key, value)
}
Expand All @@ -82,7 +82,13 @@ func (h *APIHandler) proxyHandler(w http.ResponseWriter, r *http.Request) {
}
defer resp.Body.Close()

// Copy response headers, excluding CORS-related headers
// Add CORS headers to the response
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin")) // Reflect the origin for allowed requests
w.Header().Set("Access-Control-Allow-Credentials", "true") // Allow credentials if needed
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

// Copy other response headers, excluding CORS-related headers
for key, values := range resp.Header {
if key == "Access-Control-Allow-Origin" || key == "Origin" {
continue
Expand Down

0 comments on commit c3a7c97

Please sign in to comment.