diff --git a/app/Livewire/Comment.php b/app/Livewire/Comment.php index bc632cf..66b68e0 100644 --- a/app/Livewire/Comment.php +++ b/app/Livewire/Comment.php @@ -8,6 +8,7 @@ use App\Models\User; use Livewire\Component; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\RateLimiter; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Maize\Markable\Models\Like; @@ -77,12 +78,24 @@ class Comment extends Component return; } + $user = auth()->user(); + $rateLimitKey = "send-comment:{$user->id}"; + + if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) { + $seconds = RateLimiter::availableIn($rateLimitKey); + + $this->addError('replyState.body', "Too many comments. Try again in {$seconds} seconds."); + return; + } + + RateLimiter::hit($rateLimitKey, 60); + $this->validate([ 'replyState.body' => 'required' ]); $reply = $this->comment->children()->make($this->replyState); - $reply->user()->associate(auth()->user()); + $reply->user()->associate($user); $reply->commentable()->associate($this->comment->commentable); $reply->save(); diff --git a/app/Livewire/Comments.php b/app/Livewire/Comments.php index b263330..75d499a 100644 --- a/app/Livewire/Comments.php +++ b/app/Livewire/Comments.php @@ -5,6 +5,8 @@ namespace App\Livewire; use Livewire\Component; use Livewire\WithPagination; +use Illuminate\Support\Facades\RateLimiter; + class Comments extends Component { use WithPagination; @@ -29,8 +31,23 @@ class Comments extends Component 'newCommentState.body' => 'required' ]); + $this->addError('newCommentState.body', "Too many comments. Try again in 1 seconds."); + return; + + $user = auth()->user(); + $rateLimitKey = "send-comment:{$user->id}"; + + if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) { + $seconds = RateLimiter::availableIn($rateLimitKey); + + $this->addError('newCommentState.body', "Too many comments. Try again in {$seconds} seconds."); + return; + } + + RateLimiter::hit($rateLimitKey, 60); + $comment = $this->model->comments()->make($this->newCommentState); - $comment->user()->associate(auth()->user()); + $comment->user()->associate($user); $comment->save(); $this->newCommentState = [