tg_bind_service.go 6.0 KB

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