jwt.go 1.9 KB

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