| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 | 
							- 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()
 
- 	}
 
- }
 
 
  |