Skip to content

Commit

Permalink
chore: Update CORS middleware to allow requests from specific origin
Browse files Browse the repository at this point in the history
  • Loading branch information
nilgaar committed Jul 20, 2024
1 parent 5440adc commit 8feff28
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions backend/cors.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package main

import "github.com/gin-gonic/gin"
import (
"strings"

"github.com/gin-gonic/gin"
)

func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
origin := c.GetHeader("Origin")

if strings.HasSuffix(origin, ".pops.cafe") {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
} else {
// Optionally handle requests from disallowed origins
c.JSON(403, gin.H{"error": "Access not allowed"})
c.Abort()
return
}

Expand Down

0 comments on commit 8feff28

Please sign in to comment.