tg_bind_service.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. package services
  2. import (
  3. "app/commons/core/redisclient"
  4. "app/commons/model/entity"
  5. "context"
  6. "crypto/rand"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "math/big"
  11. "time"
  12. "gorm.io/gorm"
  13. )
  14. type TgBindService struct {
  15. CommonService
  16. }
  17. const (
  18. redisKeyBindToken = "tg_bind_token:%s" // 绑定令牌
  19. redisKeyBindLimit = "tg_bind_limit:%d" // 生成限频
  20. redisKeyBindCache = "tg_bind_cache:%d" // 绑定缓存
  21. bindTokenExpire = 5 * time.Minute // 令牌有效期
  22. bindLimitExpire = 60 * time.Second // 限频间隔
  23. bindCacheExpire = 1 * time.Hour // 缓存有效期
  24. )
  25. type bindTokenData struct {
  26. TelegramId int64 `json:"telegramId"`
  27. TelegramUsername string `json:"telegramUsername"`
  28. }
  29. // GenerateBindToken 生成绑定令牌
  30. func (s *TgBindService) GenerateBindToken(telegramId int64, telegramUsername string) (string, error) {
  31. ctx := context.Background()
  32. rdb := redisclient.DefaultClient()
  33. // 限频检查
  34. limitKey := fmt.Sprintf(redisKeyBindLimit, telegramId)
  35. if rdb.Exists(ctx, limitKey).Val() > 0 {
  36. return "", errors.New("请稍后再试(60秒内只能生成一次)")
  37. }
  38. // 生成6位码
  39. token := s.randomAlphanumeric(6)
  40. // 存 Redis
  41. tokenKey := fmt.Sprintf(redisKeyBindToken, token)
  42. data := bindTokenData{
  43. TelegramId: telegramId,
  44. TelegramUsername: telegramUsername,
  45. }
  46. jsonBytes, _ := json.Marshal(data)
  47. rdb.Set(ctx, tokenKey, string(jsonBytes), bindTokenExpire)
  48. // 存 DB
  49. bindToken := &entity.TgBindToken{
  50. Token: token,
  51. TelegramId: telegramId,
  52. TelegramUsername: telegramUsername,
  53. Status: 0,
  54. ExpireAt: time.Now().Add(bindTokenExpire),
  55. }
  56. s.DB().Create(bindToken)
  57. // 设置限频
  58. rdb.Set(ctx, limitKey, "1", bindLimitExpire)
  59. return token, nil
  60. }
  61. // BindTelegramUser 使用令牌绑定 Telegram 用户到平台账户
  62. func (s *TgBindService) BindTelegramUser(userId int64, token string) (*entity.TgUserBind, error) {
  63. ctx := context.Background()
  64. rdb := redisclient.DefaultClient()
  65. // 从 Redis 查令牌
  66. tokenKey := fmt.Sprintf(redisKeyBindToken, token)
  67. val, err := rdb.Get(ctx, tokenKey).Result()
  68. var data bindTokenData
  69. if err == nil {
  70. json.Unmarshal([]byte(val), &data)
  71. } else {
  72. // Redis 没有,查 DB
  73. var dbToken entity.TgBindToken
  74. if err := s.DB().Where("token = ? AND status = 0", token).First(&dbToken).Error; err != nil {
  75. return nil, errors.New("绑定码无效或已过期")
  76. }
  77. if time.Now().After(dbToken.ExpireAt) {
  78. return nil, errors.New("绑定码已过期")
  79. }
  80. data.TelegramId = dbToken.TelegramId
  81. data.TelegramUsername = dbToken.TelegramUsername
  82. }
  83. // 检查 telegramId 是否已绑定其他用户
  84. var existBind entity.TgUserBind
  85. err = s.DB().Where("telegram_id = ? AND bind_status = 1", data.TelegramId).First(&existBind).Error
  86. if err == nil && existBind.UserId != userId {
  87. return nil, errors.New("该Telegram账户已绑定其他平台账户")
  88. }
  89. if err == nil && existBind.UserId == userId {
  90. // 已绑定同一用户,直接返回
  91. return &existBind, nil
  92. }
  93. // 检查 userId 是否已绑定其他 telegramId
  94. err = s.DB().Where("user_id = ? AND bind_status = 1", userId).First(&existBind).Error
  95. if err == nil && existBind.TelegramId != data.TelegramId {
  96. return nil, errors.New("该平台账户已绑定其他Telegram账户")
  97. }
  98. // 创建绑定记录
  99. bind := &entity.TgUserBind{
  100. UserId: userId,
  101. TelegramId: data.TelegramId,
  102. TelegramUsername: data.TelegramUsername,
  103. TelegramFirstName: "",
  104. BindStatus: 1,
  105. BindTime: time.Now(),
  106. }
  107. if err := s.DB().Create(bind).Error; err != nil {
  108. return nil, fmt.Errorf("绑定失败: %w", err)
  109. }
  110. // 更新令牌状态
  111. s.DB().Model(&entity.TgBindToken{}).Where("token = ?", token).Updates(map[string]interface{}{
  112. "status": 1,
  113. "user_id": userId,
  114. })
  115. // 删除 Redis 令牌,设置绑定缓存
  116. rdb.Del(ctx, tokenKey)
  117. cacheKey := fmt.Sprintf(redisKeyBindCache, data.TelegramId)
  118. rdb.Set(ctx, cacheKey, fmt.Sprintf("%d", userId), bindCacheExpire)
  119. return bind, nil
  120. }
  121. // IsUserBound 检查 telegramId 是否已绑定,返回 (是否绑定, userId)
  122. func (s *TgBindService) IsUserBound(telegramId int64) (bool, int64) {
  123. ctx := context.Background()
  124. rdb := redisclient.DefaultClient()
  125. // 查 Redis 缓存
  126. cacheKey := fmt.Sprintf(redisKeyBindCache, telegramId)
  127. val, err := rdb.Get(ctx, cacheKey).Result()
  128. if err == nil && val != "" {
  129. var userId int64
  130. fmt.Sscanf(val, "%d", &userId)
  131. if userId > 0 {
  132. return true, userId
  133. }
  134. }
  135. // 查 DB
  136. var bind entity.TgUserBind
  137. err = s.DB().Where("telegram_id = ? AND bind_status = 1", telegramId).First(&bind).Error
  138. if err != nil {
  139. if errors.Is(err, gorm.ErrRecordNotFound) {
  140. return false, 0
  141. }
  142. return false, 0
  143. }
  144. // 写入缓存
  145. rdb.Set(ctx, cacheKey, fmt.Sprintf("%d", bind.UserId), bindCacheExpire)
  146. return true, bind.UserId
  147. }
  148. // GetBindByUserId 根据平台 userId 查询绑定记录
  149. func (s *TgBindService) GetBindByUserId(userId int64) (*entity.TgUserBind, error) {
  150. var bind entity.TgUserBind
  151. if err := s.DB().Where("user_id = ? AND bind_status = 1", userId).First(&bind).Error; err != nil {
  152. return nil, err
  153. }
  154. return &bind, nil
  155. }
  156. // randomAlphanumeric 生成 n 位大写字母+数字随机码
  157. func (s *TgBindService) randomAlphanumeric(n int) string {
  158. const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  159. result := make([]byte, n)
  160. for i := range result {
  161. num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
  162. result[i] = charset[num.Int64()]
  163. }
  164. return string(result)
  165. }