92 lines
1.8 KiB
Go
92 lines
1.8 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,
|
|
}
|
|
|
|
TokenRateLimit = RateLimitConfig{
|
|
Max: 20,
|
|
Window: time.Minute,
|
|
BlockFor: 5 * time.Minute,
|
|
}
|
|
|
|
RevokeRateLimit = RateLimitConfig{
|
|
Max: 30,
|
|
Window: time.Minute,
|
|
}
|
|
|
|
RefreshRateLimit = RateLimitConfig{
|
|
Max: 30,
|
|
Window: time.Minute,
|
|
BlockFor: 5 * time.Minute,
|
|
}
|
|
)
|
|
|
|
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 false, 0, fmt.Errorf("rate limiter: %w", err)
|
|
}
|
|
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 false, 0, fmt.Errorf("rate limiter: %w", err)
|
|
}
|
|
|
|
count := int(incrCmd.Val())
|
|
remaining := max(cfg.Max-count, 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))
|
|
}
|