Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.docker.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ LOG_STACK=daily
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

# API Rate Limiting Configuration
DEFAULT_API_RATE_LIMIT=60

# Docker MySQL Configuration
DB_CONNECTION=mysql
DB_HOST=mysql
Expand Down
14 changes: 14 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
namespace App\Providers;

use Carbon\CarbonImmutable;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
Expand All @@ -28,5 +31,16 @@ public function boot(): void
Date::use(CarbonImmutable::class);
Model::shouldBeStrict(! $this->app->isProduction());
DB::prohibitDestructiveCommands($this->app->isProduction());

// Disable rate limiting during testing
if ($this->app->environment('testing')) {
RateLimiter::for('api', fn () => Limit::none());
} else {
// Rate Limiting for API routes
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute((int) config('rate-limiting.api.default_rate_limit'))
->by($request->user()?->id ?: $request->ip());
});
}
}
}
1 change: 1 addition & 0 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'ability' => \App\Http\Middleware\CheckTokenAbility::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
Expand Down
7 changes: 7 additions & 0 deletions config/rate-limiting.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

return [
'api' => [
'default_rate_limit' => env('DEFAULT_API_RATE_LIMIT', 60),
],
];
2 changes: 1 addition & 1 deletion routes/api_v1.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::prefix('v1')->group(function () {
Route::prefix('v1')->middleware(['throttle:api'])->group(function () {
Route::get('/', function (Request $request) {
return 'Laravel Blog API V1 Root is working';
})->name('api.v1.status');
Expand Down