修复短信登录限流处理

This commit is contained in:
yml2213
2026-06-12 20:30:43 +08:00
parent 4344b1d07c
commit 8cfb63a3e7
4 changed files with 92 additions and 4 deletions
+27 -1
View File
@@ -25,6 +25,12 @@ var (
ErrUserDisabled = errors.New("user disabled")
)
const (
smsLoginCooldown = 60 * time.Second
smsLoginHourlyLimit = 5
smsLoginHourlyWindow = time.Hour
)
type Service struct {
users *UserRepository
redis *redis.Client
@@ -59,6 +65,15 @@ func (s *Service) SendSMSCode(ctx context.Context, phone string) error {
return ErrCodeRateLimited
}
hourlyKey := "sms:hourly:login:" + phone
hourlyCount, err := s.redis.Get(ctx, hourlyKey).Int()
if err != nil && !errors.Is(err, redis.Nil) {
return err
}
if hourlyCount >= smsLoginHourlyLimit {
return ErrCodeRateLimited
}
code, err := randomDigits(6)
if err != nil {
return err
@@ -71,12 +86,23 @@ func (s *Service) SendSMSCode(ctx context.Context, phone string) error {
if s.log != nil {
s.log.Warn("sms login code send failed", zap.String("phone", PublicPhone(phone)), zap.Error(err))
}
if smsprovider.IsProviderRateLimited(err) {
pipe := s.redis.TxPipeline()
pipe.Set(ctx, cooldownKey, "1", smsLoginCooldown)
pipe.Set(ctx, hourlyKey, smsLoginHourlyLimit, smsLoginHourlyWindow)
if _, pipeErr := pipe.Exec(ctx); pipeErr != nil {
return pipeErr
}
return ErrCodeRateLimited
}
return ErrSMSSendFailed
}
pipe := s.redis.TxPipeline()
pipe.Set(ctx, codeKey(phone), code, 5*time.Minute)
pipe.Set(ctx, cooldownKey, "1", 60*time.Second)
pipe.Set(ctx, cooldownKey, "1", smsLoginCooldown)
pipe.Incr(ctx, hourlyKey)
pipe.Expire(ctx, hourlyKey, smsLoginHourlyWindow)
pipe.Incr(ctx, "sms:daily:login:"+phone)
pipe.Expire(ctx, "sms:daily:login:"+phone, 24*time.Hour)
if _, err := pipe.Exec(ctx); err != nil {