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 }