Skip to content

Commit

Permalink
feat: add CORS middleware to manager (#2304)
Browse files Browse the repository at this point in the history
Signed-off-by: Gaius <[email protected]>
  • Loading branch information
gaius-qi authored Apr 26, 2023
1 parent 571ab93 commit 7f0ebf9
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 7 deletions.
51 changes: 51 additions & 0 deletions manager/middlewares/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2023 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package middlewares

import (
"net/http"
"strings"

"github.com/gin-gonic/gin"
"github.com/go-http-utils/headers"
)

func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.GetHeader(headers.Origin)
if origin == "" {
c.Next()
return
}

c.Header(headers.AccessControlAllowOrigin, origin)
c.Header(headers.AccessControlAllowCredentials, "true")

if c.Request.Method != http.MethodOptions {
c.Next()
return
}

// Preflight OPTIONS request.
c.Header(headers.AccessControlAllowHeaders, c.GetHeader("Access-Control-Request-Headers"))
c.Header(headers.AccessControlAllowMethods, strings.Join([]string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPost, http.MethodDelete, http.MethodPatch}, ","))
c.Header(headers.AccessControlMaxAge, "600000")
c.Status(http.StatusNoContent)

c.Abort()
}
}
8 changes: 1 addition & 7 deletions manager/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"time"

"github.com/casbin/casbin/v2"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/static"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -66,17 +65,12 @@ func Init(cfg *config.Config, logDir string, service service.Service, enforcer *
r.Use(otelgin.Middleware(OtelServiceName))
}

// CORS
corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
corsConfig.AllowCredentials = true

// Middleware
r.Use(gin.Recovery())
r.Use(ginzap.Ginzap(logger.GinLogger.Desugar(), time.RFC3339, true))
r.Use(ginzap.RecoveryWithZap(logger.GinLogger.Desugar(), true))
r.Use(middlewares.Error())
r.Use(cors.New(corsConfig))
r.Use(middlewares.CORS())

rbac := middlewares.RBAC(enforcer)
jwt, err := middlewares.Jwt(cfg.Auth.JWT, service)
Expand Down

0 comments on commit 7f0ebf9

Please sign in to comment.