jwt.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2020 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package middleware
  4. import (
  5. "net/http"
  6. "smart-enterprise-management-gateway/errors"
  7. "github.com/dgrijalva/jwt-go"
  8. "github.com/gin-gonic/gin"
  9. "github.com/jaryhe/gopkgs/jwtwrapper"
  10. "google.golang.org/grpc/codes"
  11. "google.golang.org/grpc/status"
  12. )
  13. // 响应数据
  14. type Response struct {
  15. Code codes.Code `json:"code" default:"1"`
  16. Message string `json:"message" default:"success"`
  17. }
  18. // JWT is jwt middleware
  19. func Jwt() gin.HandlerFunc {
  20. return func(c *gin.Context) {
  21. s := status.New(1, "内部服务错误")
  22. token := c.GetHeader("token")
  23. if token == "" {
  24. if v, ok := status.FromError(errors.NoTokenError); ok {
  25. s = v
  26. }
  27. c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
  28. c.Abort()
  29. return
  30. }
  31. // 解析token
  32. claims, err := jwtwrapper.ParseToken(token)
  33. if err != nil {
  34. switch err.(*jwt.ValidationError).Errors {
  35. case jwt.ValidationErrorExpired:
  36. if v, ok := status.FromError(errors.TokenExpiredError); ok {
  37. s = v
  38. }
  39. default:
  40. if v, ok := status.FromError(errors.TokenFailedError); ok {
  41. s = v
  42. }
  43. }
  44. c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
  45. c.Abort()
  46. return
  47. }
  48. // 将claims信息保存到上下文,为后续使用
  49. c.Set("claims", claims)
  50. /*
  51. supper := gjson.GetBytes(utils.StrToBytes(claims.Subject), "supper").Bool()
  52. if c.Request.Method == "PUT" || c.Request.Method == "POST" || c.Request.Method == "DELETE" {
  53. if supper == false && strings.Contains(c.Request.RequestURI, "/user") == false {
  54. c.JSON(http.StatusOK, Response{10008, "权限不足"})
  55. }
  56. }
  57. */
  58. // 进行下一次处理
  59. c.Next()
  60. }
  61. }