Skip to content

Commit

Permalink
Merge pull request #208 from gobitfly/NOBIDS/better-cors
Browse files Browse the repository at this point in the history
configure cors for sessions
  • Loading branch information
guybrush authored Apr 17, 2024
2 parents e6f0598 + 0856901 commit 27e9eb2
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 14 deletions.
2 changes: 1 addition & 1 deletion backend/cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func main() {
sessionManager := api.NewSessionManager(cfg.RedisCacheEndpoint, !cfg.Frontend.Debug)

router := api.NewApiRouter(dataAccessor, sessionManager)
router.Use(api.CorsMiddleware, api.GetAuthMiddleware(cfg.ApiKeySecret))
router.Use(api.GetCorsMiddleware(cfg.CorsAllowedHosts), api.GetAuthMiddleware(cfg.ApiKeySecret))

srv := &http.Server{
Handler: router,
Expand Down
1 change: 1 addition & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ require (
github.com/google/s2a-go v0.1.7 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
github.com/gorilla/handlers v1.5.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 // indirect
github.com/herumi/bls-eth-go-binary v1.31.0 // indirect
github.com/holiman/uint256 v1.2.4 // indirect
Expand Down
2 changes: 2 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,8 @@ github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qK
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gopherjs/gopherjs v0.0.0-20190430165422-3e4dfb77656c h1:7lF+Vz0LqiRidnzC1Oq86fpX1q/iEv2KJdrCtttYjT4=
github.com/gopherjs/gopherjs v0.0.0-20190430165422-3e4dfb77656c/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
Expand Down
29 changes: 17 additions & 12 deletions backend/pkg/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"github.com/alexedwards/scs/v2"
dataaccess "github.com/gobitfly/beaconchain/pkg/api/data_access"
handlers "github.com/gobitfly/beaconchain/pkg/api/handlers"
"github.com/gobitfly/beaconchain/pkg/commons/log"
gorillaHandlers "github.com/gorilla/handlers"
"github.com/gorilla/mux"
)

Expand All @@ -29,18 +31,21 @@ func NewApiRouter(dataAccessor dataaccess.DataAccessor, sessionManager *scs.Sess
return router
}

func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
func GetCorsMiddleware(allowedHosts []string) func(http.Handler) http.Handler {
if len(allowedHosts) == 0 {
log.Warn("CORS allowed hosts not set, allowing all origins")
return gorillaHandlers.CORS(
gorillaHandlers.AllowedOrigins([]string{"*"}),
gorillaHandlers.AllowedMethods([]string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions, http.MethodHead}),
gorillaHandlers.AllowedHeaders([]string{"Content-Type", "Authorization"}),
)
}
return gorillaHandlers.CORS(
gorillaHandlers.AllowedOrigins(allowedHosts),
gorillaHandlers.AllowedMethods([]string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions, http.MethodHead}),
gorillaHandlers.AllowedHeaders([]string{"Content-Type", "Authorization"}),
gorillaHandlers.AllowCredentials(),
)
}

func addRoutes(hs *handlers.HandlerService, publicRouter, internalRouter *mux.Router) {
Expand Down
8 changes: 8 additions & 0 deletions backend/pkg/commons/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ func WarnWithStackTrace(err error, errorMsg interface{}, callerSkip int, additio
logErrorInfo(err, callerSkip, additionalInfos...).Warn(errorMsg)
}

func Info(args ...interface{}) {
logrus.Info(args...)
}

func Infof(format string, args ...interface{}) {
logrus.Infof(format, args...)
}
Expand All @@ -39,6 +43,10 @@ func InfoWithFields(additionalInfos Fields, msg string) {
logFields.Infof(msg)
}

func Warn(args ...interface{}) {
logrus.Warn(args...)
}

func Warnf(format string, args ...interface{}) {
logrus.Warnf(format, args...)
}
Expand Down
3 changes: 2 additions & 1 deletion backend/pkg/commons/types/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,8 @@ type Config struct {
ApiKey string `yaml:"apiKey" envconfig:"MONITORING_API_KEY"`
ServiceMonitoringConfigurations []ServiceMonitoringConfiguration `yaml:"serviceMonitoringConfigurations" envconfig:"SERVICE_MONITORING_CONFIGURATIONS"`
} `yaml:"monitoring"`
ApiKeySecret string `yaml:"apiKeySecret" envconfig:"API_KEY_SECRET"`
ApiKeySecret string `yaml:"apiKeySecret" envconfig:"API_KEY_SECRET"`
CorsAllowedHosts []string `yaml:"corsAllowedHosts" envconfig:"CORS_ALLOWED_HOSTS"`
}

type DatabaseConfig struct {
Expand Down

0 comments on commit 27e9eb2

Please sign in to comment.