auth.go 1.6 KB

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