Files
mtusi2026lab7/internal/adapter/postgres/login_rate_limit.go
T
d1frend cc41f601e3
Skeleton contracts / contracts (pull_request) Canceled after 0s
на оценку 4
2026-11-22 23:33:11 +03:00

76 lines
1.8 KiB
Go

package postgres
import (
"context"
"fmt"
"time"
)
func (s *PostgreSQLStore) AllowLoginAttempt(
ctx context.Context,
identifierHash [32]byte,
now time.Time,
window time.Duration,
limit int,
) (bool, time.Duration, error) {
if err := s.maybePruneExpiredState(ctx, now); err != nil {
return false, 0, err
}
if err := s.maybePruneExpiredLoginRateState(ctx, now, window); err != nil {
return false, 0, err
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attempts int
var windowStartedAt time.Time
err := s.pool.QueryRow(queryContext, `
INSERT INTO login_rate_limits (
identifier_hash, window_started_at, attempts
)
VALUES ($1, $2, 1)
ON CONFLICT (identifier_hash) DO UPDATE
SET
window_started_at = CASE
WHEN login_rate_limits.window_started_at <= $3
THEN EXCLUDED.window_started_at
ELSE login_rate_limits.window_started_at
END,
attempts = CASE
WHEN login_rate_limits.window_started_at <= $3 THEN 1
ELSE login_rate_limits.attempts + 1
END
RETURNING attempts, window_started_at
`, identifierHash[:], now.UTC(), now.UTC().Add(-window)).Scan(
&attempts,
&windowStartedAt,
)
if err != nil {
return false, 0, fmt.Errorf("update login rate limit: %w", err)
}
if attempts <= limit {
return true, 0, nil
}
retryAfter := windowStartedAt.Add(window).Sub(now.UTC())
if retryAfter < time.Second {
retryAfter = time.Second
}
return false, retryAfter, nil
}
func (s *PostgreSQLStore) ResetLoginAttempts(
ctx context.Context,
identifierHash [32]byte,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
if _, err := s.pool.Exec(
queryContext,
`DELETE FROM login_rate_limits WHERE identifier_hash = $1`,
identifierHash[:],
); err != nil {
return fmt.Errorf("reset login rate limit: %w", err)
}
return nil
}