Document every package and exported identifier, return the log level from NewLogger instead of keeping it in a package variable, and stop tests from mutating the argon2 parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
36 lines
983 B
Go
36 lines
983 B
Go
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()
|
|
}
|