jwt.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package api
  2. import (
  3. "fmt"
  4. "log"
  5. "mesh/conf"
  6. "time"
  7. jwt "github.com/appleboy/gin-jwt/v2"
  8. "github.com/gin-gonic/gin"
  9. )
  10. var identityKey = "id"
  11. type UtilsJwt struct {
  12. jwt *jwt.GinJWTMiddleware
  13. }
  14. func (j *UtilsJwt) MiddleFunc() gin.HandlerFunc {
  15. return j.jwt.MiddlewareFunc()
  16. }
  17. func (j *UtilsJwt) JwtCreateToken(data interface{}) (string, time.Time, error) {
  18. return j.jwt.TokenGenerator(data)
  19. }
  20. func NewUitlsJwt(app *conf.AppConf) *UtilsJwt {
  21. var utils = &UtilsJwt{
  22. jwt: nil,
  23. }
  24. var jwtImpl *jwt.GinJWTMiddleware
  25. jwtImpl, err := jwt.New(&jwt.GinJWTMiddleware{
  26. Realm: app.Jwt.Realm,
  27. Key: []byte(app.Jwt.Key),
  28. Timeout: time.Hour * time.Duration(app.Jwt.TimeoutHour),
  29. MaxRefresh: time.Hour * time.Duration(app.Jwt.TimeoutHour),
  30. IdentityKey: identityKey,
  31. PayloadFunc: func(data interface{}) jwt.MapClaims {
  32. if v, ok := data.(*JWTUser); ok {
  33. return jwt.MapClaims{
  34. "id": v.ID,
  35. "phone": v.Phone,
  36. "role": v.Role,
  37. "parent": v.Parent,
  38. "state": v.State,
  39. }
  40. }
  41. return jwt.MapClaims{}
  42. },
  43. IdentityHandler: func(c *gin.Context) interface{} {
  44. claims := jwt.ExtractClaims(c)
  45. // lg.Debug().Msgf("token: %v\n", claims)
  46. u := &JWTUser{
  47. ID: claims["id"].(string), //uint32(claims["id"].(float64)),
  48. Phone: claims["phone"].(string),
  49. Role: claims["role"].(string),
  50. Parent: claims["parent"].(string),
  51. }
  52. if claims["state"] != nil {
  53. u.State = int32(claims["state"].(float64))
  54. }
  55. return u
  56. },
  57. Authenticator: func(c *gin.Context) (interface{}, error) {
  58. return &JWTUser{Phone: "empty"}, nil
  59. },
  60. Authorizator: func(data interface{}, _ *gin.Context) bool {
  61. u := data.(*JWTUser)
  62. return u.State > 0
  63. },
  64. LoginResponse: func(c *gin.Context, status int, token string, expire time.Time) {
  65. t, _ := jwtImpl.ParseTokenString(token)
  66. fmt.Println("LoginResponse==>", status, token)
  67. ResultSuc(c, map[string]interface{}{
  68. "user": t.Claims,
  69. "token": token,
  70. "expire": expire.Format(time.RFC3339),
  71. })
  72. },
  73. LogoutResponse: func(c *gin.Context, _ int) {
  74. ResultSuc(c, true)
  75. },
  76. RefreshResponse: func(c *gin.Context, status int, token string, expire time.Time) {
  77. ResultSuc(c, map[string]interface{}{
  78. "status": status,
  79. "token": token,
  80. "expire": expire.Format(time.RFC3339),
  81. })
  82. },
  83. Unauthorized: func(c *gin.Context, status int, token string) {
  84. if token == "用户名/密码 不正确" {
  85. ResultFail401(c, "账号密码不对", map[string]interface{}{
  86. "status": -1,
  87. "token": token,
  88. })
  89. return
  90. }
  91. fmt.Println("xxxxx")
  92. fmt.Println(token, status)
  93. ResultFail401(c, token, map[string]interface{}{
  94. "status": status,
  95. "token": token,
  96. })
  97. },
  98. HTTPStatusMessageFunc: func(e error, _ *gin.Context) string {
  99. // if e == jwt.ErrFailedAuthentication {
  100. // return "用户名/密码 不正确"
  101. // }
  102. fmt.Println("HTTPStatusMessageFunc", e)
  103. return e.Error()
  104. },
  105. // TokenLookup is a string in the form of "<source>:<name>" that is used
  106. // to extract token from the request.
  107. // Optional. Default value "header:Authorization".
  108. // Possible values:
  109. // - "header:<name>"
  110. // - "query:<name>"
  111. // - "cookie:<name>"
  112. // - "param:<name>"
  113. TokenLookup: "header: Authorization, query: token, cookie: jwt",
  114. // TokenLookup: "query:token",
  115. // TokenLookup: "cookie:token",
  116. // TokenHeadName is a string in the header. Default value is "Bearer"
  117. TokenHeadName: "Bearer",
  118. // 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.
  119. TimeFunc: time.Now,
  120. })
  121. if err != nil {
  122. log.Fatal("JWT Error:" + err.Error())
  123. }
  124. utils.jwt = jwtImpl
  125. return utils
  126. }