jwt.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. package api
  2. import (
  3. "box-cost/conf"
  4. "fmt"
  5. "log"
  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. c.Set("userId", claims["id"])
  46. // lg.Debug().Msgf("token: %v\n", claims)
  47. u := &JWTUser{
  48. ID: claims["id"].(string), //uint32(claims["id"].(float64)),
  49. Phone: claims["phone"].(string),
  50. Role: claims["role"].(string),
  51. Parent: claims["parent"].(string),
  52. }
  53. if claims["state"] != nil {
  54. u.State = int32(claims["state"].(float64))
  55. }
  56. return u
  57. },
  58. Authenticator: func(c *gin.Context) (interface{}, error) {
  59. return &JWTUser{Phone: "empty"}, nil
  60. },
  61. Authorizator: func(data interface{}, _ *gin.Context) bool {
  62. u := data.(*JWTUser)
  63. return u.State > 0
  64. },
  65. LoginResponse: func(c *gin.Context, status int, token string, expire time.Time) {
  66. t, _ := jwtImpl.ParseTokenString(token)
  67. fmt.Println("LoginResponse==>", status, token)
  68. ResultSuc(c, map[string]interface{}{
  69. "user": t.Claims,
  70. "token": token,
  71. "expire": expire.Format(time.RFC3339),
  72. })
  73. },
  74. LogoutResponse: func(c *gin.Context, _ int) {
  75. ResultSuc(c, true)
  76. },
  77. RefreshResponse: func(c *gin.Context, status int, token string, expire time.Time) {
  78. ResultSuc(c, map[string]interface{}{
  79. "status": status,
  80. "token": token,
  81. "expire": expire.Format(time.RFC3339),
  82. })
  83. },
  84. Unauthorized: func(c *gin.Context, status int, token string) {
  85. if token == "用户名/密码 不正确" {
  86. ResultFail401(c, "账号密码不对", map[string]interface{}{
  87. "status": -1,
  88. "token": token,
  89. })
  90. return
  91. }
  92. fmt.Println("xxxxx")
  93. fmt.Println(token, status)
  94. ResultFail401(c, token, map[string]interface{}{
  95. "status": status,
  96. "token": token,
  97. })
  98. },
  99. HTTPStatusMessageFunc: func(e error, _ *gin.Context) string {
  100. // if e == jwt.ErrFailedAuthentication {
  101. // return "用户名/密码 不正确"
  102. // }
  103. fmt.Println("HTTPStatusMessageFunc", e)
  104. return e.Error()
  105. },
  106. // TokenLookup is a string in the form of "<source>:<name>" that is used
  107. // to extract token from the request.
  108. // Optional. Default value "header:Authorization".
  109. // Possible values:
  110. // - "header:<name>"
  111. // - "query:<name>"
  112. // - "cookie:<name>"
  113. // - "param:<name>"
  114. TokenLookup: "header: Authorization, query: token, cookie: jwt",
  115. // TokenLookup: "query:token",
  116. // TokenLookup: "cookie:token",
  117. // TokenHeadName is a string in the header. Default value is "Bearer"
  118. TokenHeadName: "Bearer",
  119. // 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.
  120. TimeFunc: time.Now,
  121. })
  122. if err != nil {
  123. log.Fatal("JWT Error:" + err.Error())
  124. }
  125. utils.jwt = jwtImpl
  126. return utils
  127. }