123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package middleware
- import (
- "kpt-tmr-group/pkg/apierr"
- "kpt-tmr-group/pkg/jwt"
- commonPb "kpt-tmr-group/proto/go/backend/common"
- "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
- }
- claims, err := jwt.ParseToken(token)
- if err != nil || claims == nil || claims.Username == "" {
- unauthorized(c)
- return
- }
- c.Set(UserName, claims.Username)
- c.Set(XRequestId, GetXRequestId(c))
- c.Next()
- }
- }
|