refresh_token_cache.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. package repository
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. "github.com/Wei-Shaw/sub2api/internal/service"
  8. "github.com/redis/go-redis/v9"
  9. )
  10. const (
  11. refreshTokenKeyPrefix = "refresh_token:"
  12. userRefreshTokensPrefix = "user_refresh_tokens:"
  13. tokenFamilyPrefix = "token_family:"
  14. )
  15. // refreshTokenKey generates the Redis key for a refresh token.
  16. func refreshTokenKey(tokenHash string) string {
  17. return refreshTokenKeyPrefix + tokenHash
  18. }
  19. // userRefreshTokensKey generates the Redis key for user's token set.
  20. func userRefreshTokensKey(userID int64) string {
  21. return fmt.Sprintf("%s%d", userRefreshTokensPrefix, userID)
  22. }
  23. // tokenFamilyKey generates the Redis key for token family set.
  24. func tokenFamilyKey(familyID string) string {
  25. return tokenFamilyPrefix + familyID
  26. }
  27. type refreshTokenCache struct {
  28. rdb *redis.Client
  29. }
  30. // NewRefreshTokenCache creates a new RefreshTokenCache implementation.
  31. func NewRefreshTokenCache(rdb *redis.Client) service.RefreshTokenCache {
  32. return &refreshTokenCache{rdb: rdb}
  33. }
  34. func (c *refreshTokenCache) StoreRefreshToken(ctx context.Context, tokenHash string, data *service.RefreshTokenData, ttl time.Duration) error {
  35. key := refreshTokenKey(tokenHash)
  36. val, err := json.Marshal(data)
  37. if err != nil {
  38. return fmt.Errorf("marshal refresh token data: %w", err)
  39. }
  40. return c.rdb.Set(ctx, key, val, ttl).Err()
  41. }
  42. func (c *refreshTokenCache) GetRefreshToken(ctx context.Context, tokenHash string) (*service.RefreshTokenData, error) {
  43. key := refreshTokenKey(tokenHash)
  44. val, err := c.rdb.Get(ctx, key).Result()
  45. if err != nil {
  46. if err == redis.Nil {
  47. return nil, service.ErrRefreshTokenNotFound
  48. }
  49. return nil, err
  50. }
  51. var data service.RefreshTokenData
  52. if err := json.Unmarshal([]byte(val), &data); err != nil {
  53. return nil, fmt.Errorf("unmarshal refresh token data: %w", err)
  54. }
  55. return &data, nil
  56. }
  57. func (c *refreshTokenCache) DeleteRefreshToken(ctx context.Context, tokenHash string) error {
  58. key := refreshTokenKey(tokenHash)
  59. return c.rdb.Del(ctx, key).Err()
  60. }
  61. func (c *refreshTokenCache) DeleteUserRefreshTokens(ctx context.Context, userID int64) error {
  62. // Get all token hashes for this user
  63. tokenHashes, err := c.GetUserTokenHashes(ctx, userID)
  64. if err != nil && err != redis.Nil {
  65. return fmt.Errorf("get user token hashes: %w", err)
  66. }
  67. if len(tokenHashes) == 0 {
  68. return nil
  69. }
  70. // Build keys to delete
  71. keys := make([]string, 0, len(tokenHashes)+1)
  72. for _, hash := range tokenHashes {
  73. keys = append(keys, refreshTokenKey(hash))
  74. }
  75. keys = append(keys, userRefreshTokensKey(userID))
  76. // Delete all keys in a pipeline
  77. pipe := c.rdb.Pipeline()
  78. for _, key := range keys {
  79. pipe.Del(ctx, key)
  80. }
  81. _, err = pipe.Exec(ctx)
  82. return err
  83. }
  84. func (c *refreshTokenCache) DeleteTokenFamily(ctx context.Context, familyID string) error {
  85. // Get all token hashes in this family
  86. tokenHashes, err := c.GetFamilyTokenHashes(ctx, familyID)
  87. if err != nil && err != redis.Nil {
  88. return fmt.Errorf("get family token hashes: %w", err)
  89. }
  90. if len(tokenHashes) == 0 {
  91. return nil
  92. }
  93. // Build keys to delete
  94. keys := make([]string, 0, len(tokenHashes)+1)
  95. for _, hash := range tokenHashes {
  96. keys = append(keys, refreshTokenKey(hash))
  97. }
  98. keys = append(keys, tokenFamilyKey(familyID))
  99. // Delete all keys in a pipeline
  100. pipe := c.rdb.Pipeline()
  101. for _, key := range keys {
  102. pipe.Del(ctx, key)
  103. }
  104. _, err = pipe.Exec(ctx)
  105. return err
  106. }
  107. func (c *refreshTokenCache) AddToUserTokenSet(ctx context.Context, userID int64, tokenHash string, ttl time.Duration) error {
  108. key := userRefreshTokensKey(userID)
  109. pipe := c.rdb.Pipeline()
  110. pipe.SAdd(ctx, key, tokenHash)
  111. pipe.Expire(ctx, key, ttl)
  112. _, err := pipe.Exec(ctx)
  113. return err
  114. }
  115. func (c *refreshTokenCache) AddToFamilyTokenSet(ctx context.Context, familyID string, tokenHash string, ttl time.Duration) error {
  116. key := tokenFamilyKey(familyID)
  117. pipe := c.rdb.Pipeline()
  118. pipe.SAdd(ctx, key, tokenHash)
  119. pipe.Expire(ctx, key, ttl)
  120. _, err := pipe.Exec(ctx)
  121. return err
  122. }
  123. func (c *refreshTokenCache) GetUserTokenHashes(ctx context.Context, userID int64) ([]string, error) {
  124. key := userRefreshTokensKey(userID)
  125. return c.rdb.SMembers(ctx, key).Result()
  126. }
  127. func (c *refreshTokenCache) GetFamilyTokenHashes(ctx context.Context, familyID string) ([]string, error) {
  128. key := tokenFamilyKey(familyID)
  129. return c.rdb.SMembers(ctx, key).Result()
  130. }
  131. func (c *refreshTokenCache) IsTokenInFamily(ctx context.Context, familyID string, tokenHash string) (bool, error) {
  132. key := tokenFamilyKey(familyID)
  133. return c.rdb.SIsMember(ctx, key, tokenHash).Result()
  134. }