fusonic / rate-limit-bundle
Simple rate limiting based on routes.
Installs: 13 490
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 6
Forks: 1
Open Issues: 1
Type:symfony-bundle
Requires
- php: >=7.4
- psr/log: ^1.1
- symfony/cache: ^4.4 || ^5.0
- symfony/config: ^4.4 || ^5.0
- symfony/dependency-injection: ^4.4 || ^5.0
- symfony/event-dispatcher: ^4.4 || ^5.0
- symfony/framework-bundle: ^4.4 || ^5.0
- symfony/http-foundation: ^4.4 || ^5.0
- symfony/http-kernel: ^4.4 || ^5.0
- symfony/monolog-bridge: ^4.4 || ^5.0
- symfony/monolog-bundle: ^3.5
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.17
- phpstan/phpstan: ^0.11 || ^0.12.50
- symfony/browser-kit: ^4.4 || ^5.0
- symfony/phpunit-bridge: ^4.4 || ^5.0
- symfony/yaml: ^4.4 || ^5.0
README
This bundle provides simple rate limiting based on routes.
Getting started
- Install bundle:
composer require fusonic/rate-limit-bundle
- Add RateLimitBundle to kernel:
Fusonic\RateLimitBundle\RateLimitBundle::class => ['prod' => true],
- Add cache config
framework: cache: app: cache.adapter.array
- Add rate limit config
fusonic_rate_limit: cache_provider: "cache.app" enabled: true routes: foo: limit: 2 period: 3600
How does it work
The bundle makes use of Symfony's event system. Therefore some events exist under Fusonic/RateLimitBundle/Event
:
- RateLimitAttemptsUpdatedEvent will be emitted when a request for a rate limited route is detected.
- RateLimitExceededEvent will be emitted when a route limit is exceeded.
- RateLimitResetAttemptsEvent can be used to reset the state for a specific route (e.g. after a successful login)
Example
Create an event listener or subscriber:
<?php namespace AppBundle\EventListener; use Fusonic\RateLimitBundle\Event\RateLimitEvents; use Fusonic\RateLimitBundle\Event\RateLimitExceededEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException; final class RateLimitSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ RateLimitEvents::ROUTE_LIMIT_EXCEEDED => 'onLimitExceeded', ]; } public function onLimitExceeded(RateLimitExceededEvent $event): void { $config = $event->getRouteLimitConfig(); $message = 'You sent too many requests for this endpoint.'; throw new TooManyRequestsHttpException($config->getPeriod(), $message); } }
And register it as service.
app.rate_limit_subscriber: class: AppBundle\EventListener\RateLimitSubscriber tags: - { name: kernel.event_subscriber }
Execute tests
Run the the tests by executing:
vendor/bin/simple-phpunit