package middleware import ( "context" "fmt" "net/http" "strconv" "time" "github.com/redis/go-redis/v9" "gavrilenko-sxdees/lab7/internal/dto" "gavrilenko-sxdees/lab7/internal/httpx" ) const ( loginLimitKeyPrefix = "login:attempt:" loginLimitWindow = time.Minute loginLimitMax = 20 ) type LoginLimiter struct { rdb *redis.Client } func NewLoginLimiter(rdb *redis.Client) *LoginLimiter { return &LoginLimiter{rdb: rdb} } func (l *LoginLimiter) Limit(next http.Handler) http.Handler { if l == nil || l.rdb == nil { return next } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost || r.URL.Path != "/api/v1/auth/sessions" { next.ServeHTTP(w, r) return } username, _, ok := r.BasicAuth() if !ok { next.ServeHTTP(w, r) return } key := loginLimitKeyPrefix + username ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond) defer cancel() n, err := l.rdb.Incr(ctx, key).Result() if err != nil { next.ServeHTTP(w, r) return } if n == 1 { _ = l.rdb.Expire(ctx, key, loginLimitWindow).Err() } if n > loginLimitMax { ttl, _ := l.rdb.TTL(ctx, key).Result() if ttl < 0 { ttl = loginLimitWindow } w.Header().Set("Retry-After", strconv.Itoa(int(ttl.Seconds()))) httpx.WriteError(w, http.StatusTooManyRequests, dto.ErrorCodeRateLimited, fmt.Sprintf("too many login attempts; retry in %ds", int(ttl.Seconds())), GetRequestID(r.Context())) return } next.ServeHTTP(w, r) }) }