Skip to content

Commit f586165

Browse files
authored
[Feature] Implement configurable API rate limiting (alexjustesen#1984)
1 parent cf13ecb commit f586165

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed

app/Providers/AppServiceProvider.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,7 @@ public function register(): void
3939
public function boot(): void
4040
{
4141
$this->defineCustomIfStatements();
42-
43-
RateLimiter::for('api', function (Request $request) {
44-
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
45-
});
42+
$this->setApiRateLimit();
4643

4744
if (config('app.force_https')) {
4845
URL::forceScheme('https');
@@ -77,4 +74,11 @@ protected function defineCustomIfStatements(): void
7774
return filled($value);
7875
});
7976
}
77+
78+
protected function setApiRateLimit(): void
79+
{
80+
RateLimiter::for('api', function (Request $request) {
81+
return Limit::perMinute(config('api.rate_limit'));
82+
});
83+
}
8084
}

config/api.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
return [
4+
5+
'rate_limit' => env('API_RATE_LIMIT', 60),
6+
7+
];

routes/api.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,6 @@
2424
Route::get('/speedtest/latest', GetLatestController::class)
2525
->name('speedtest.latest');
2626

27-
Route::middleware('auth:sanctum')->group(function () {
27+
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
2828
require __DIR__.'/api/v1/routes.php';
2929
});

0 commit comments

Comments
 (0)