package middleware import ( "kpt-pasture/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.StatusUnauthorized, apierr.WithContext(c, commonPb.Error_UNAUTHORIZED)) } func authorization(c *gin.Context) string { if v := c.GetHeader("Authorization"); v != "" { return v } if v := c.GetHeader("authorization"); v != "" { return v } return "" } // 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 { unauthorized(c) return } c.Set(UserName, userName) c.Set(XRequestId, GetXRequestId(c)) c.Next() } }