Skip to content
New issue

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

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

Already on GitHub? # to your account

Fixes not dispatching SpamDetectedEvent in Livewire #120

Merged
merged 2 commits into from
Jul 17, 2023
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 src/Http/Livewire/Concerns/UsesSpamProtection.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Livewire\Component;
use ReflectionProperty;
use Spatie\Honeypot\Events\SpamDetectedEvent;
use Spatie\Honeypot\Exceptions\SpamException;
use Spatie\Honeypot\SpamProtection;

Expand Down Expand Up @@ -35,6 +36,8 @@ protected function protectAgainstSpam(): void
try {
app(SpamProtection::class)->check($honeypotData->toArray());
} catch (SpamException) {
event(new SpamDetectedEvent(request()));

abort(403, 'Spam detected.');
}
}
Expand Down
38 changes: 24 additions & 14 deletions tests/HoneypotLivewireComponentTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php

use function Pest\Livewire\livewire;
use Illuminate\Support\Facades\Event;
use Spatie\Honeypot\Events\SpamDetectedEvent;
use Spatie\Honeypot\Tests\TestComponents\LivewireHoneypotComponent;
use Spatie\Honeypot\Tests\TestComponents\LivewireHoneypotConfiguredComponent;

Expand All @@ -18,21 +20,29 @@
->call('submit')
->assertOk();

test('permission denied if request is done too early')
->livewire(LivewireHoneypotConfiguredComponent::class)
->call('submit')
->assertStatus(403);
test('permission denied if request is done too early', function () {
Event::fake();

test('permission denied if request is spam')
->tap(function () {
config()->set('honeypot.randomize_name_field_name', false);
config()->set('honeypot.name_field_name', 'firstname');
})
->livewire(LivewireHoneypotConfiguredComponent::class)
->set('extraFields.firstname', 'I am a spammer')
->call('submit')
->assertStatus(403);
;
livewire(LivewireHoneypotConfiguredComponent::class)
->call('submit')
->assertStatus(403);

Event::assertDispatched(SpamDetectedEvent::class);
});

test('permission denied if request is spam', function () {
Event::fake();

livewire(LivewireHoneypotConfiguredComponent::class)
->set('extraFields.firstname', 'I am a spammer')
->call('submit')
->assertStatus(403);

Event::assertDispatched(SpamDetectedEvent::class);
})->tap(function () {
config()->set('honeypot.randomize_name_field_name', false);
config()->set('honeypot.name_field_name', 'firstname');
});

it('works', function () {
TestTime::freeze('Y-m-d H:i:s', '2019-01-01 00:00:00');
Expand Down