Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/create ratelimit for api #28 #29

Merged
merged 6 commits into from
Dec 10, 2024
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: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@
"extra": {
"laravel": {
"providers": [
"CSlant\\Blog\\Api\\Providers\\BlogApiServiceProvider"
"CSlant\\Blog\\Api\\Providers\\BlogApiServiceProvider",
"CSlant\\Blog\\Api\\Providers\\RouteServiceProvider"
]
}
},
Expand Down
4 changes: 1 addition & 3 deletions config/blog-api.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
<?php

$routePrefix = env('BLOG_API_ROUTE_PREFIX', 'api');

return [
'defaults' => [
/* Set route prefix for the blog API */
'route_prefix' => $routePrefix,
'route_prefix' => env('BLOG_API_ROUTE_PREFIX', 'api'),
],
];
3 changes: 3 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ parameters:

- message: '#Call to an undefined static method CSlant\\Blog\\Api\\Http\\Resources\\ListPostResource::collection\(\).#'
path: src/Http/Controllers/PostController.php

- message: '#Cannot cast mixed to string#'
path: '*'
32 changes: 32 additions & 0 deletions src/Providers/RouteServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace CSlant\Blog\ApiPackage\Providers;

use CSlant\Blog\Core\Models\User;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

class RouteServiceProvider extends ServiceProvider
{
/**
* Move base routes to a service provider to make sure all filters & actions can hook to base routes
*/
public function boot(): void
{
// add rate limit for api
$this->configureRateLimiting();
}

protected function configureRateLimiting(): void
{
RateLimiter::for((string) config('blog-api.defaults.route_prefix'), function (Request $request) {
/** @var null|User $user */
$user = $request->user();
$identifier = $user ? $user->id : $request->ip();

return Limit::perMinute(40)->by($identifier);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

set rate limit for the API path in urls

});
}
}