Skip to content

Commit

Permalink
Merge pull request #178 from COS301-SE-2024/feat/backend/cors-headers…
Browse files Browse the repository at this point in the history
…-issue

chore: Update CORS configuration in backend main.go file
  • Loading branch information
waveyboym authored Jul 10, 2024
2 parents d1d1073 + 3d128cc commit 53287f6
Show file tree
Hide file tree
Showing 10 changed files with 128 additions and 0 deletions.
12 changes: 12 additions & 0 deletions occupi-backend/cmd/occupi-backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ package main

import (
"flag"
"time"

"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
nrgin "github.com/newrelic/go-agent/v3/integrations/nrgin"
"github.com/newrelic/go-agent/v3/newrelic"
Expand Down Expand Up @@ -60,6 +62,16 @@ func main() {
// Create a Gin router
ginRouter := gin.Default()

// Set CORS
ginRouter.Use(cors.New(cors.Config{
AllowOrigins: configs.GetAllowOrigins(),
AllowMethods: configs.GetAllowMethods(),
AllowHeaders: configs.GetAllowHeaders(),
ExposeHeaders: configs.GetExposeHeaders(),
AllowCredentials: configs.GetAllowCredentials(),
MaxAge: time.Duration(configs.GetMaxAge()) * time.Second,
}))

// Set trusted proxies
err := ginRouter.SetTrustedProxies(configs.GetTrustedProxies())
if err != nil {
Expand Down
58 changes: 58 additions & 0 deletions occupi-backend/configs/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ const (
FrontendURL = "FRONTEND_URL"
ConfigLicense = "CONFIG_LICENSE"
OtpGenReqEviction = "OTP_GEN_REQ_EVICTION"
AllowOriginsVal = "ALLOW_ORIGINS"
AllowMethodsVal = "ALLOW_METHODS"
AllowHeadersVal = "ALLOW_HEADERS"
ExposeHeadersVal = "EXPOSE_HEADERS"
Caval = "ALLOW_CREDENTIALS"
MaxAgeVal = "MAX_AGE"
)

// init viper
Expand Down Expand Up @@ -260,3 +266,55 @@ func GetOTPReqEviction() int {
}
return time
}

// gets allow origins as defined in the config.yaml file
func GetAllowOrigins() []string {
origins := viper.GetString(AllowOriginsVal)
if origins != "" {
originList := strings.Split(origins, ",")
return originList
}
return []string{"*"}
}

// gets allow methods as defined in the config.yaml file
func GetAllowMethods() []string {
methods := viper.GetString(AllowMethodsVal)
if methods != "" {
methodList := strings.Split(methods, ",")
return methodList
}
return []string{"*"}
}

// gets allow headers as defined in the config.yaml file
func GetAllowHeaders() []string {
headers := viper.GetString(AllowHeadersVal)
if headers != "" {
headerList := strings.Split(headers, ",")
return headerList
}
return []string{"*"}
}

// gets expose headers as defined in the config.yaml file
func GetExposeHeaders() []string {
headers := viper.GetString(ExposeHeadersVal)
if headers != "" {
headerList := strings.Split(headers, ",")
return headerList
}
return []string{"*"}
}

// gets allow credentials as defined in the config.yaml file
func GetAllowCredentials() bool {
credentials := viper.GetBool(Caval)
return credentials
}

// gets max age as defined in the config.yaml file
func GetMaxAge() int {
age := viper.GetInt(MaxAgeVal)
return age
}
Binary file modified occupi-backend/configs/config.yaml.gpg
Binary file not shown.
Binary file modified occupi-backend/configs/dev.deployed.yaml.gpg
Binary file not shown.
Binary file modified occupi-backend/configs/dev.localhost.yaml.gpg
Binary file not shown.
Binary file modified occupi-backend/configs/prod.yaml.gpg
Binary file not shown.
Binary file modified occupi-backend/configs/test.yaml.gpg
Binary file not shown.
1 change: 1 addition & 0 deletions occupi-backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ require (
)

require (
github.com/gin-contrib/cors v1.7.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240314234333-6e1732d8331c // indirect
google.golang.org/grpc v1.62.1 // indirect
Expand Down
2 changes: 2 additions & 0 deletions occupi-backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nos
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I=
github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s=
github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw=
github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E=
github.com/gin-contrib/sessions v1.0.1 h1:3hsJyNs7v7N8OtelFmYXFrulAf6zSR7nW/putcPEHxI=
github.com/gin-contrib/sessions v1.0.1/go.mod h1:ouxSFM24/OgIud5MJYQJLpy6AwxQ5EYO9yLhbtObGkM=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
Expand Down
55 changes: 55 additions & 0 deletions occupi-backend/tests/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@ package tests

import (
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"

"github.com/COS301-SE-2024/occupi/occupi-backend/configs"
"github.com/COS301-SE-2024/occupi/occupi-backend/data"
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/utils"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)

func TestMain(m *testing.M) {
Expand All @@ -28,3 +34,52 @@ func TestMain(m *testing.M) {

os.Exit(m.Run())
}

func TestCORS(t *testing.T) {
// set gin run mode
gin.SetMode(configs.GetGinRunMode())

router := gin.Default()

router.Use(cors.New(cors.Config{
AllowOrigins: configs.GetAllowOrigins(),
AllowMethods: configs.GetAllowMethods(),
AllowHeaders: configs.GetAllowHeaders(),
ExposeHeaders: configs.GetExposeHeaders(),
AllowCredentials: configs.GetAllowCredentials(),
MaxAge: time.Duration(configs.GetMaxAge()) * time.Second,
}))

router.GET("/test", func(c *gin.Context) {
c.String(200, "CORS test")
})

testCases := []struct {
origin string
expectedStatus int
expectedHeader string
}{
{"https://localhost", http.StatusOK, "https://localhost"},
{"http://localhost", http.StatusOK, "http://localhost"},
{"https://domain.com", http.StatusOK, "https://domain.com"},
{"https://dev.domain.com", http.StatusOK, "https://dev.domain.com"},
{"https://app.domain.com", http.StatusOK, "https://app.domain.com"},
{"https://invalid.com", http.StatusForbidden, ""},
}

for _, tc := range testCases {
t.Run(tc.origin, func(t *testing.T) {
req, _ := http.NewRequest("GET", "/test", nil)
req.Header.Set("Origin", tc.origin)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)

assert.Equal(t, tc.expectedStatus, w.Code)
if tc.expectedHeader != "" {
assert.Equal(t, tc.expectedHeader, w.Header().Get("Access-Control-Allow-Origin"))
} else {
assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
}
})
}
}

0 comments on commit 53287f6

Please sign in to comment.