jwt_utils.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package jwt
  2. import (
  3. logger "eta/eta_mini_ht_api/common/component/log"
  4. "eta/eta_mini_ht_api/common/exception"
  5. "github.com/dgrijalva/jwt-go"
  6. "time"
  7. )
  8. type Claims struct {
  9. OpenId string `json:"open_id"`
  10. Mobile string `json:"mobile"`
  11. TokenType string `json:"tokenType"`
  12. jwt.StandardClaims
  13. }
  14. const (
  15. AccessToken = "access_token"
  16. GuestToken = "guest_token"
  17. )
  18. var (
  19. KEY = []byte("5Mb5Gdmb5y")
  20. )
  21. // CreateToken 生成token
  22. func CreateToken(openId string, mobile string, tokenType string) (tokenString string, err error) {
  23. claims := &Claims{
  24. openId,
  25. mobile,
  26. tokenType,
  27. jwt.StandardClaims{
  28. NotBefore: time.Now().Unix(),
  29. ExpiresAt: time.Now().Add(time.Hour * 24 * 90).Unix(),
  30. },
  31. }
  32. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  33. tokenString, err = token.SignedString(KEY)
  34. if err != nil {
  35. logger.Error("生成token失败", err)
  36. }
  37. return
  38. }
  39. type JwtInfo struct {
  40. OpenId string
  41. Mobile string
  42. TokenType string
  43. }
  44. // CheckToken 校验token
  45. func CheckToken(tokenStr string) (info JwtInfo, err error) {
  46. token, err := jwt.Parse(tokenStr, func(*jwt.Token) (interface{}, error) {
  47. return KEY, nil
  48. })
  49. if err != nil {
  50. logger.Error("解析Token失败:%v", err)
  51. err = exception.New(exception.JWTTokenDecodeFailed)
  52. return
  53. }
  54. if claims, ok := token.Claims.(jwt.MapClaims); ok {
  55. nbf, _ := claims["nbf"].(float64)
  56. exp, _ := claims["exp"].(float64)
  57. if float64(time.Now().Unix()) < nbf {
  58. logger.Error("Token无效")
  59. err = exception.New(exception.JWTTokenInvalid)
  60. return
  61. }
  62. if float64(time.Now().Unix()) >= exp {
  63. logger.Error("Token已过期")
  64. err = exception.New(exception.JWTTokenExpired)
  65. return
  66. }
  67. info = JwtInfo{
  68. OpenId: claims["open_id"].(string),
  69. Mobile: claims["mobile"].(string),
  70. TokenType: claims["tokenType"].(string),
  71. }
  72. return
  73. }
  74. logger.Error("claims解析失败")
  75. err = exception.New(exception.JWTTokenDecodeFailed)
  76. return
  77. }