Skip to content

Commit

Permalink
add test, fix logic
Browse files Browse the repository at this point in the history
  • Loading branch information
dbhoot committed Feb 23, 2024
1 parent 239063e commit 906e08c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ func (cors *cors) applyCors(c *gin.Context) {
return
}

if !cors.validateOrigin(origin) || (cors.allowOriginWithContextFunc != nil && !cors.allowOriginWithContextFunc(c, origin)) {
validOrigin := cors.validateOrigin(origin) || (cors.allowOriginWithContextFunc != nil && cors.allowOriginWithContextFunc(c, origin))

Check failure on line 84 in config.go

View workflow job for this annotation

GitHub Actions / lint

line is 133 characters (lll)
if !validOrigin {
c.AbortWithStatus(http.StatusForbidden)
return
}
Expand Down
12 changes: 12 additions & 0 deletions cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,9 @@ func TestPassesAllowOrigins(t *testing.T) {
AllowOriginFunc: func(origin string) bool {
return origin == "http://github.com"
},
AllowOriginWithContextFunc: func(c *gin.Context, origin string) bool {
return origin == "http://sample.com"
},
})

// no CORS request, origin == ""
Expand Down Expand Up @@ -329,6 +332,15 @@ func TestPassesAllowOrigins(t *testing.T) {
assert.Equal(t, "Content-Type,Timestamp", w.Header().Get("Access-Control-Allow-Headers"))
assert.Equal(t, "43200", w.Header().Get("Access-Control-Max-Age"))

// allowed CORS prefligh request: allowed via AllowOriginWithContextFunc
w = performRequest(router, "OPTIONS", "http://sample.com")
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Equal(t, "http://sample.com", w.Header().Get("Access-Control-Allow-Origin"))
assert.Equal(t, "", w.Header().Get("Access-Control-Allow-Credentials"))
assert.Equal(t, "GET,POST,PUT,HEAD", w.Header().Get("Access-Control-Allow-Methods"))
assert.Equal(t, "Content-Type,Timestamp", w.Header().Get("Access-Control-Allow-Headers"))
assert.Equal(t, "43200", w.Header().Get("Access-Control-Max-Age"))

// deny CORS prefligh request
w = performRequest(router, "OPTIONS", "http://example.com")
assert.Equal(t, http.StatusForbidden, w.Code)
Expand Down

0 comments on commit 906e08c

Please sign in to comment.