jwt.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. package utils
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "mtp20access/global"
  7. "mtp20access/model/common/request"
  8. "time"
  9. "github.com/golang-jwt/jwt/v4"
  10. )
  11. type JWT struct {
  12. SigningKey []byte
  13. }
  14. var (
  15. ErrTokenExpired = errors.New("token is expired")
  16. ErrTokenNotValidYet = errors.New("token not active yet")
  17. ErrTokenMalformed = errors.New("that's not even a token")
  18. ErrTokenInvalid = errors.New("couldn't handle this token ")
  19. )
  20. func NewJWT() *JWT {
  21. return &JWT{
  22. []byte(global.M2A_CONFIG.JWT.SigningKey),
  23. }
  24. }
  25. func (j *JWT) CreateClaims(baseClaims request.BaseClaims) request.CustomClaims {
  26. claims := request.CustomClaims{
  27. BaseClaims: baseClaims,
  28. BufferTime: global.M2A_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
  29. RegisteredClaims: jwt.RegisteredClaims{
  30. IssuedAt: jwt.NewNumericDate(time.Now()), // 签发时间
  31. NotBefore: jwt.NewNumericDate(time.Now()), // 签名生效时间
  32. ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(global.M2A_CONFIG.JWT.ExpiresTime))), // 过期时间 7天 配置文件
  33. Issuer: global.M2A_CONFIG.JWT.Issuer, // 签名的发行者
  34. },
  35. }
  36. return claims
  37. }
  38. // 创建一个token
  39. func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
  40. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  41. return token.SignedString(j.SigningKey)
  42. }
  43. // CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
  44. func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
  45. v, err, _ := global.M2A_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
  46. return j.CreateToken(claims)
  47. })
  48. return v.(string), err
  49. }
  50. // 解析 token
  51. func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
  52. token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
  53. return j.SigningKey, nil
  54. })
  55. if err != nil {
  56. if ve, ok := err.(*jwt.ValidationError); ok {
  57. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  58. return nil, ErrTokenMalformed
  59. } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
  60. // Token is expired
  61. return nil, ErrTokenExpired
  62. } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
  63. return nil, ErrTokenNotValidYet
  64. } else {
  65. return nil, ErrTokenInvalid
  66. }
  67. }
  68. }
  69. if token != nil {
  70. if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
  71. return claims, nil
  72. }
  73. return nil, ErrTokenInvalid
  74. } else {
  75. return nil, ErrTokenInvalid
  76. }
  77. }
  78. //@function: GetRedis
  79. //@description: 从redis取目标用户登录信息
  80. //@param: userName int
  81. //@return: redisJWT string, err error
  82. func (j *JWT) GetRedisLogin(loginID int, group int) (values map[string]string, err error) {
  83. key := fmt.Sprintf("m2a:login:%d:%d", loginID, group)
  84. values, err = global.M2A_REDIS.HGetAll(context.Background(), key).Result()
  85. return
  86. }
  87. //@function: SetRedisJWT
  88. //@description: jwt存入redis并设置过期时间
  89. //@param: loginID string, jwt string
  90. //@return: err error
  91. func (j *JWT) SetRedisLogin(loginID int, group int, values map[string]interface{}) (err error) {
  92. key := fmt.Sprintf("m2a:login:%d:%d", loginID, group)
  93. // 此处过期时间等于jwt过期时间
  94. // timer := time.Duration(global.M2A_CONFIG.JWT.ExpiresTime) * time.Second
  95. err = global.M2A_REDIS.HMSet(context.Background(), key, values).Err()
  96. return
  97. }
  98. // SetOriRedisToken 设置原登录服务Redis Token
  99. func (j *JWT) SetOriRedisToken(loginID int, group int) (err error) {
  100. key := fmt.Sprintf("monitor:online_loginid:%d:%d", loginID, group)
  101. // 生成原登录服务Token
  102. token := fmt.Sprintf("%d_%d_%d", loginID, time.Now().Unix(), group)
  103. err = global.M2A_REDIS.HSet(context.Background(), key, "Token", token).Err()
  104. return
  105. }