diff --git a/api/middleware/cors_middleware.go b/api/middleware/cors_middleware.go new file mode 100644 index 0000000..937c5a7 --- /dev/null +++ b/api/middleware/cors_middleware.go @@ -0,0 +1,23 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" +) + +func CORSMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + + c.Writer.Header().Set("Content-Type", "application/json") + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") + 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, GET, OPTIONS, PUT, DELETE, UPDATE") + c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") + + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + + c.Next() + } +} diff --git a/api/route/route.go b/api/route/route.go index 0c764ff..8e652b0 100644 --- a/api/route/route.go +++ b/api/route/route.go @@ -10,13 +10,17 @@ import ( ) func Setup(env *bootstrap.Env, timeout time.Duration, db mongo.Database, gin *gin.Engine) { - publicRouter := gin.Group("") + router := gin.Group("") + // Middleware to allow CORS + router.Use(middleware.CORSMiddleware()) + + publicRouter := router.Group("") // All Public APIs NewSignupRouter(env, timeout, db, publicRouter) NewLoginRouter(env, timeout, db, publicRouter) NewRefreshTokenRouter(env, timeout, db, publicRouter) - protectedRouter := gin.Group("") + protectedRouter := router.Group("") // Middleware to verify AccessToken protectedRouter.Use(middleware.JwtAuthMiddleware(env.AccessTokenSecret)) // All Private APIs