identity_cache.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. fingerprintKeyPrefix = "fingerprint:"
  12. fingerprintTTL = 7 * 24 * time.Hour // 7天,配合每24小时懒续期可保持活跃账号永不过期
  13. maskedSessionKeyPrefix = "masked_session:"
  14. maskedSessionTTL = 15 * time.Minute
  15. )
  16. // fingerprintKey generates the Redis key for account fingerprint cache.
  17. func fingerprintKey(accountID int64) string {
  18. return fmt.Sprintf("%s%d", fingerprintKeyPrefix, accountID)
  19. }
  20. // maskedSessionKey generates the Redis key for masked session ID cache.
  21. func maskedSessionKey(accountID int64) string {
  22. return fmt.Sprintf("%s%d", maskedSessionKeyPrefix, accountID)
  23. }
  24. type identityCache struct {
  25. rdb *redis.Client
  26. }
  27. func NewIdentityCache(rdb *redis.Client) service.IdentityCache {
  28. return &identityCache{rdb: rdb}
  29. }
  30. func (c *identityCache) GetFingerprint(ctx context.Context, accountID int64) (*service.Fingerprint, error) {
  31. key := fingerprintKey(accountID)
  32. val, err := c.rdb.Get(ctx, key).Result()
  33. if err != nil {
  34. return nil, err
  35. }
  36. var fp service.Fingerprint
  37. if err := json.Unmarshal([]byte(val), &fp); err != nil {
  38. return nil, err
  39. }
  40. return &fp, nil
  41. }
  42. func (c *identityCache) SetFingerprint(ctx context.Context, accountID int64, fp *service.Fingerprint) error {
  43. key := fingerprintKey(accountID)
  44. val, err := json.Marshal(fp)
  45. if err != nil {
  46. return err
  47. }
  48. return c.rdb.Set(ctx, key, val, fingerprintTTL).Err()
  49. }
  50. func (c *identityCache) GetMaskedSessionID(ctx context.Context, accountID int64) (string, error) {
  51. key := maskedSessionKey(accountID)
  52. val, err := c.rdb.Get(ctx, key).Result()
  53. if err != nil {
  54. if err == redis.Nil {
  55. return "", nil
  56. }
  57. return "", err
  58. }
  59. return val, nil
  60. }
  61. func (c *identityCache) SetMaskedSessionID(ctx context.Context, accountID int64, sessionID string) error {
  62. key := maskedSessionKey(accountID)
  63. return c.rdb.Set(ctx, key, sessionID, maskedSessionTTL).Err()
  64. }