From 29292fd98bfcba6ae43099d7b0659a7e395e87c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leandro=20Ant=C3=B4nio=20Farias=20Machado?= Date: Sat, 13 May 2023 12:47:15 -0300 Subject: [PATCH] chore(api): cors config --- .../services/controller/internal/api/api.go | 7 ++++- .../controller/internal/api/cors/cors.go | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 backend/services/controller/internal/api/cors/cors.go diff --git a/backend/services/controller/internal/api/api.go b/backend/services/controller/internal/api/api.go index 126b267..b2c4270 100644 --- a/backend/services/controller/internal/api/api.go +++ b/backend/services/controller/internal/api/api.go @@ -4,6 +4,7 @@ import ( "encoding/json" "github.com/gorilla/mux" "github.com/leandrofars/oktopus/internal/api/auth" + "github.com/leandrofars/oktopus/internal/api/cors" "github.com/leandrofars/oktopus/internal/api/middleware" "github.com/leandrofars/oktopus/internal/db" "github.com/leandrofars/oktopus/internal/mtp" @@ -49,17 +50,21 @@ func StartApi(a Api) { //TODO: Create operation action handler iot.HandleFunc("/device/{sn}/act", a.deviceUpdateMsg).Methods("PUT") + // Middleware for requests which requires user to be authenticated iot.Use(func(handler http.Handler) http.Handler { return middleware.Middleware(handler) }) + // Verifies CORS configs for requests + corsOpts := cors.GetCorsConfig() + srv := &http.Server{ Addr: "0.0.0.0:" + a.Port, // Good practice to set timeouts to avoid Slowloris attacks. WriteTimeout: time.Second * 15, ReadTimeout: time.Second * 15, IdleTimeout: time.Second * 60, - Handler: r, // Pass our instance of gorilla/mux in. + Handler: corsOpts.Handler(r), // Pass our instance of gorilla/mux in. } // Run our server in a goroutine so that it doesn't block. diff --git a/backend/services/controller/internal/api/cors/cors.go b/backend/services/controller/internal/api/cors/cors.go new file mode 100644 index 0000000..92e9205 --- /dev/null +++ b/backend/services/controller/internal/api/cors/cors.go @@ -0,0 +1,27 @@ +package cors + +import ( + "github.com/rs/cors" + "net/http" +) + +func GetCorsConfig() cors.Cors { + return *cors.New(cors.Options{ + AllowedOrigins: []string{ + "http://localhost:3000", + }, + AllowedMethods: []string{ + http.MethodGet, + http.MethodPost, + http.MethodPut, + http.MethodPatch, + http.MethodDelete, + http.MethodOptions, + http.MethodHead, + }, + + AllowedHeaders: []string{ + "*", //or you can your header key values which you are using in your application + }, + }) +}