jwt.go 3.5 KB

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