Files
kotosoft-id/kotosoft-id-backend/internal/services/ratelimiter.go
T
2026-03-09 12:50:29 +03:00

78 lines
1.5 KiB
Go

package services
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
type RateLimitConfig struct {
Max int
Window time.Duration
BlockFor time.Duration
}
var (
LoginRateLimit = RateLimitConfig{
Max: 10,
Window: 15 * time.Minute,
BlockFor: 15 * time.Minute,
}
RegisterRateLimit = RateLimitConfig{
Max: 5,
Window: time.Hour,
}
)
type RateLimiter struct {
redis *redis.Client
}
func NewRateLimiter(rdb *redis.Client) *RateLimiter {
return &RateLimiter{redis: rdb}
}
func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig) (bool, int, error) {
blockKey := fmt.Sprintf("rl_block:%s", key)
counterKey := fmt.Sprintf("rl_count:%s", key)
if cfg.BlockFor > 0 {
blocked, err := r.redis.Exists(ctx, blockKey).Result()
if err != nil {
return true, 0, nil
}
if blocked > 0 {
return false, 0, nil
}
}
pipe := r.redis.Pipeline()
incrCmd := pipe.Incr(ctx, counterKey)
pipe.Expire(ctx, counterKey, cfg.Window)
if _, err := pipe.Exec(ctx); err != nil {
return true, 0, nil
}
count := int(incrCmd.Val())
remaining := cfg.Max - count
if remaining < 0 {
remaining = 0
}
if count > cfg.Max {
if cfg.BlockFor > 0 {
_ = r.redis.Set(ctx, blockKey, 1, cfg.BlockFor).Err()
}
return false, 0, nil
}
return true, remaining, nil
}
func (r *RateLimiter) Reset(ctx context.Context, key string) {
_ = r.redis.Del(ctx, fmt.Sprintf("rl_count:%s", key), fmt.Sprintf("rl_block:%s", key))
}