livewire-rate-limiting

repository·2.x·Indexed 19 days ago

https://github.com/danharrin/livewire-rate-limiting

A Laravel Livewire package for applying rate limiting to specific component actions to prevent spam and brute-force attacks. Provides the WithRateLimiting trait with methods to rateLimit, hitRateLimiter, and clearRateLimiter. Requires Laravel v8.x, PHP 8.0+, and supports file or redis cache drivers.

Tokens
1.4K
Snippets
4
Records
5
Agent score
15%

What's inside livewire-rate-limiting

  1. How to use rate limiting in Livewire components

    2.x

    To enable rate limiting in a Livewire component, apply the DanHarrin\LivewireRateLimiting\WithRateLimiting trait.

    Once the trait is included, you can call $this->rateLimit() within your component methods to throttle execution. If the limit is exceeded, the package throws a TooManyRequestsException. It is recommended to catch this exception and convert it into a ValidationException to provide user-friendly feedback.

    <?php
    
    namespace App\Http\Livewire\Login;
    
    use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
    use DanHarrin\LivewireRateLimiting\WithRateLimiting;
    use Illuminate\Validation\ValidationException;
    use Livewire\Component;
    
    class Login extends Component
    {
        use WithRateLimiting;
        
        public function submit()
        {
            try {
                // Limit to 10 attempts every 60 seconds
                $this->rateLimit(10);
            } catch (TooManyRequestsException $exception) {
                throw ValidationException::withMessages([
                    'email' => "Slow down! Please wait another {$exception->secondsUntilAvailable} seconds to log in.",
                ]);
            }
            
            // ... logic after successful rate limit check
        }
    }
  2. Install livewire-rate-limiting via Composer

    2.x

    Install the package into your Laravel application using Composer:

    composer require danharrin/livewire-rate-limiting

    Requirements & Compatibility:

    • Laravel: Requires at least v8.x.
    • PHP: Requires PHP 8.0+.
    • Cache Drivers: Tested and supported with file and redis. The array driver is not supported.
  3. RateLimit component methods

    2.x

    The WithRateLimiting trait provides the following methods to manage rate limits within your component:

    rateLimit($maxAttempts, $decaySeconds = 60, $method = null)

    Rate limit a Livewire method.

    • $maxAttempts: The number of times the limit can be hit in the decay period.
    • $decaySeconds: The length of the decay period in seconds (default is 60).
    • $method: The name of the method being limited. If null, it defaults to the method currently being called.
    • Throws: DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException if the limit is exceeded.

    hitRateLimiter($method = null, $decaySeconds = 60)

    Increments the rate limiter for a specific method without performing a check. Use this to manually record an attempt (e.g., after a failed login).

    • $method: The name of the method to hit. Defaults to the current method.
    • $decaySeconds: The decay period in seconds (default is 60).

    clearRateLimiter($method = null)

    Clears the rate limiter for the specified method.

    • $method: The name of the method to clear. Defaults to the current method.
    // Example usage of component methods
    $this->rateLimit(10);           // Check limit
    $this->hitRateLimiter('submit'); // Manually hit the 'submit' limiter
    $this->clearRateLimiter('submit'); // Reset the 'submit' limiter
  4. Handle TooManyRequestsException when rate limits are exceeded

    2.x

    When a user exceeds the defined rate limit for a Livewire component method, the package throws a DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException.

    You can catch this exception to provide custom feedback to the user. The exception object contains metadata about the rate-limited request, allowing you to display exactly how long the user must wait.

    Key properties available on the exception instance:

    • $component: The name of the Livewire component being accessed.
    • $method: The specific method that was rate-limited.
    • $ip: The IP address of the requester.
    • $secondsUntilAvailable: The number of seconds remaining before the user can retry.
    • $minutesUntilAvailable: The number of minutes remaining (calculated as ceil($secondsUntilAvailable / 60)).
  5. Handle TooManyRequestsException

    2.x

    When a rate limit is exceeded, a DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException is thrown. This exception contains metadata about the violation that you can use to inform the user.

    Available Properties:

    • $exception->component: The class of the component where the limit was hit.
    • $exception->ip: The IP address of the user.
    • $exception->method: The name of the method that triggered the limit.
    • $exception->minutesUntilAvailable: Minutes remaining until the limit is lifted (rounded up).
    • $exception->secondsUntilAvailable: Seconds remaining until the limit is lifted.
    try {
        $this->rateLimit(10);
    } catch (TooManyRequestsException $exception) {
        echo $exception->secondsUntilAvailable;
        echo $exception->minutesUntilAvailable;
    }