jwt.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package middlewares
  2. import (
  3. "github.com/dgrijalva/jwt-go"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. "zhiyuan/pkg/app"
  7. "zhiyuan/pkg/errcode"
  8. "zhiyuan/pkg/utils"
  9. )
  10. func JWT() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. code := errcode.Success
  13. token := c.GetHeader("token")
  14. if token == "" {
  15. code = errcode.TokenEmpty
  16. } else {
  17. _, err := utils.ParseToken(token)
  18. if err != nil {
  19. switch err.(*jwt.ValidationError).Errors {
  20. case jwt.ValidationErrorExpired:
  21. code = errcode.TokenExpired
  22. default:
  23. code = errcode.TokenInvalid
  24. }
  25. }
  26. }
  27. if code.Code != errcode.Success.Code {
  28. app.Response(c, http.StatusUnauthorized, code, nil)
  29. c.Abort()
  30. return
  31. }
  32. c.Next()
  33. }
  34. }
  35. //var identityKey = "id"
  36. //
  37. //func GinJWTMiddlewareInit() (authMiddleware *jwt.GinJWTMiddleware) {
  38. //
  39. // authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{
  40. // Realm: "test zone",
  41. // Key: []byte("secret key"),
  42. // Timeout: time.Hour * 12,
  43. // MaxRefresh: time.Hour,
  44. // IdentityKey: identityKey,
  45. // PayloadFunc: func(data interface{}) jwt.MapClaims {
  46. // if v, ok := data.(*models.User); ok {
  47. // return jwt.MapClaims{
  48. // identityKey: v.ID,
  49. // }
  50. // }
  51. // return jwt.MapClaims{}
  52. // },
  53. // IdentityHandler: func(c *gin.Context) interface{} {
  54. // claims := jwt.ExtractClaims(c)
  55. // return &models.User{
  56. // ID: int(claims[identityKey].(float64)),
  57. // }
  58. // },
  59. // Authenticator: func(c *gin.Context) (interface{}, error) {
  60. // var loginVals models.User
  61. // if err := c.ShouldBind(&loginVals); err != nil {
  62. // return "", jwt.ErrMissingLoginValues
  63. // }
  64. // username := loginVals.Username
  65. // password := loginVals.Password
  66. //
  67. // fmt.Println(username + "---" + password)
  68. // userID := models.CheckLogin(username, password)
  69. // fmt.Println(userID)
  70. // if userID > 0 {
  71. // return &models.User{
  72. // ID: userID,
  73. // }, nil
  74. // }
  75. //
  76. // return nil, jwt.ErrFailedAuthentication
  77. // },
  78. // LoginResponse: func(c *gin.Context, code int, token string, expire time.Time) {
  79. // c.JSON(code, utils.EchoSuc(gin.H{"token": token, "expire": expire}))
  80. // },
  81. // Authorizator: func(data interface{}, c *gin.Context) bool {
  82. // return true
  83. // },
  84. // Unauthorized: func(c *gin.Context, code int, message string) {
  85. // c.JSON(code, gin.H{
  86. // "code": code,
  87. // "message": message,
  88. // })
  89. // },
  90. // // TokenLookup is a string in the form of "<source>:<name>" that is used
  91. // // to extract token from the request.
  92. // // Optional. Default value "header:Authorization".
  93. // // Possible values:
  94. // // - "header:<name>"
  95. // // - "query:<name>"
  96. // // - "cookie:<name>"
  97. // // - "param:<name>"
  98. // TokenLookup: "header: Authorization, query: token, cookie: jwt",
  99. // // TokenLookup: "query:token",
  100. // // TokenLookup: "cookie:token",
  101. //
  102. // // TokenHeadName is a string in the header. Default value is "Bearer"
  103. // TokenHeadName: "Bearer",
  104. //
  105. // // TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
  106. // TimeFunc: time.Now,
  107. // })
  108. // if err != nil {
  109. // log.Fatal("JWT Error:" + err.Error())
  110. // }
  111. // return
  112. //}
  113. //
  114. //func NoRouteHandler(c *gin.Context) {
  115. // claims := jwt.ExtractClaims(c)
  116. // log.Printf("NoRoute claims: %#v\n", claims)
  117. // c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
  118. //}