sso.go 1.2 KB

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