package auth import ( "context" "time" "github.com/redis/go-redis/v9" ) // Limiter counts attempts per key in fixed windows stored in Redis. type Limiter struct { rdb redis.UniversalClient } // NewLimiter returns a Limiter backed by rdb. func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} } var incrWithTTL = redis.NewScript(` local n = redis.call("INCR", KEYS[1]) if n == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end return n`) // Allow counts one attempt in a fixed window shared by all replicas. func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (bool, error) { n, err := incrWithTTL.Run(ctx, l.rdb, []string{"rl:" + key}, window.Milliseconds()).Int() if err != nil { return false, err } return n <= limit, nil } // Reset clears the counter for key, e.g. after a successful login. func (l *Limiter) Reset(ctx context.Context, key string) error { return l.rdb.Del(ctx, "rl:"+key).Err() }