package middleware import ( "gitee.com/xuyiping_admin/pkg/logger/zaplog" "go.uber.org/zap" "kpt-tmr-group/config" commonPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/common" "gitee.com/xuyiping_admin/pkg/apierr" "gitee.com/xuyiping_admin/pkg/jwt" "net/http" "strings" "github.com/gin-gonic/gin" ) const ( Authorization = "Authorization" ToKenPrefix = "Bearer " UserName = "userName" XRequestId = "X-Request-Id" ) func GetToken(c *gin.Context) string { value := c.Request.Header.Get(Authorization) if value != "" && strings.HasPrefix(value, ToKenPrefix) { return strings.TrimPrefix(value, ToKenPrefix) } return "" } func GetXRequestId(c *gin.Context) string { item := c.Request.Header.Get(XRequestId) return item } func unauthorized(c *gin.Context) { c.AbortWithStatusJSON(http.StatusBadRequest, apierr.WithContext(c, commonPb.Error_UNAUTHORIZED)) } // RequireAdmin ... func RequireAdmin() gin.HandlerFunc { return func(c *gin.Context) { token := GetToken(c) if token == "" { unauthorized(c) return } tokenVerifier := jwt.JWTTokenVerifier{PublicKey: config.Options().JwtTokenKeyConfig.PublicKey} userName, err := tokenVerifier.ParseToken(token) if err != nil { zaplog.Error("unauthorized", zap.Any("err", err)) unauthorized(c) return } c.Set(UserName, userName) c.Set(XRequestId, GetXRequestId(c)) c.Next() } }