jwt.go 3.9 KB

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