sso.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package middleware
  2. import (
  3. "kpt-tmr-group/pkg/apierr"
  4. "kpt-tmr-group/pkg/jwt"
  5. commonPb "kpt-tmr-group/proto/go/backend/common"
  6. "net/http"
  7. "strings"
  8. "github.com/gin-gonic/gin"
  9. )
  10. const (
  11. Authorization = "Authorization"
  12. ToKenPrefix = "Bearer "
  13. UserName = "userName"
  14. XRequestId = "X-Request-Id"
  15. )
  16. func GetToken(c *gin.Context) string {
  17. value := c.Request.Header.Get(Authorization)
  18. if value != "" && strings.HasPrefix(value, ToKenPrefix) {
  19. return strings.TrimPrefix(value, ToKenPrefix)
  20. }
  21. return ""
  22. }
  23. func GetXRequestId(c *gin.Context) string {
  24. item := c.Request.Header.Get(XRequestId)
  25. return item
  26. }
  27. func unauthorized(c *gin.Context) {
  28. c.AbortWithStatusJSON(http.StatusBadRequest, apierr.WithContext(c, commonPb.Error_UNAUTHORIZED))
  29. }
  30. // RequireAdmin ...
  31. func RequireAdmin() gin.HandlerFunc {
  32. return func(c *gin.Context) {
  33. token := GetToken(c)
  34. if token == "" {
  35. unauthorized(c)
  36. return
  37. }
  38. claims, err := jwt.ParseToken(token)
  39. if err != nil || claims == nil || claims.Username == "" {
  40. unauthorized(c)
  41. return
  42. }
  43. c.Set(UserName, claims.Username)
  44. c.Set(XRequestId, GetXRequestId(c))
  45. c.Next()
  46. }
  47. }