Skip to content

Commit

Permalink
Added logic to handle CORS allowed origins and aborting request for n…
Browse files Browse the repository at this point in the history
…on-allowed origins
  • Loading branch information
mayank2424 committed Dec 26, 2024
1 parent b0302d9 commit 7ea1922
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,36 @@ func main() {

// CORS middleware
router.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
origin := c.Request.Header.Get("Origin")
allowedOrigins := configValue.Server.AllowedOrigins
isAllowed := false

if len(allowedOrigins) == 0 {
// Allow all origins, if none are specified in config
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
} else {
for _, allowedOrigin := range allowedOrigins {
if origin == allowedOrigin {
isAllowed = true
break
}
}

if isAllowed {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
} else {
http.Error(c.Writer, "403 - Forbidden", http.StatusForbidden)
c.Abort()
return
}
}
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

if c.Request.Method == "OPTIONS" {
if len(allowedOrigins) == 0 || isAllowed {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
}
c.AbortWithStatus(http.StatusOK)
return
}
Expand Down

0 comments on commit 7ea1922

Please sign in to comment.