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

Reset Captcha Event #12

Merged
merged 2 commits into from
Apr 1, 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
71 changes: 70 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

</br>

![Login Screen screenshot](https://github.com/coderflexx/filament-turnstile/raw/main/art/thumbnail.png)
<img src="https://github.com/coderflexx/filament-turnstile/raw/main/art/thumbnail.png" alt="Login Screen screenshot" class="filament-hidden"/>

</br>

Expand Down Expand Up @@ -59,6 +59,67 @@ For a list of supported languages, refer to the [supported languages section](ht

The `Turnstile` field offers various options; you can learn more about them in [the Cloudflare configuration section](https://developers.cloudflare.com/turnstile/get-started/client-side-rendering/#configurations).

## Turnstile Events

The Turnstile package provides events that you can leverage to manage the behavior of the captcha in various scenarios.

**Reset Event**

The `reset-captcha` event allows you to programmatically reset the captcha challenge. This can be useful when you want to:

- **Clear the challenge after a successful form submission:** This ensures a fresh captcha for the next user.
- **Reset the challenge upon validation errors:** Prevents users from being stuck with a previously solved captcha after encountering errors during form submission.

**Dispatching the Reset Event:**

There are two primary ways to dispatch the `reset-captcha` event:

**1. Using `onValidationError` Method:**

Filament provides the `onValidationError` method within your form's Livewire component. This method is automatically triggered whenever form [validation fails](https://filamentphp.com/docs/3.x/forms/validation#sending-validation-notifications). Here's how to utilize it:

```php
protected function onValidationError(ValidationException $exception): void
{
$this->dispatch('reset-captcha');

// Perform additional actions as necessary (e.g., display error messages)
}
```

In this example, the `reset-captcha` event is dispatched upon validation errors, ensuring the captcha is reset for the user's next attempt.

**2. Manual Dispatching:**

For scenarios where resetting the captcha is not directly tied to validation, you can manually dispatch the event using Filament's event dispatcher:

```php
$this->dispatch('reset-captcha');
```

**Using Reset Event in Login Page:**

To automatically reset the captcha on a failed login attempt in your login form's Livewire component, leverage the `throwFailureValidationException` method:

```php
protected function authenticate(): void
{
// Perform authentication logic
// ...

if (! Auth::attempt($this->data)) {
$this->throwFailureValidationException(
[
'email' => 'Invalid email or password.',
]
);
}

// Redirect to success page or perform other actions
}
```

By throwing a validation exception with appropriate error messages, you trigger the `onValidationError` method, which in turn dispatches the `reset-captcha` event, effectively resetting the captcha for the next login attempt.

## Real-Life Example:

Expand Down Expand Up @@ -97,6 +158,14 @@ class Login extends AuthLogin
),
];
}

// if you want to reset the captcha in case of validation error
protected function throwFailureValidationException(): never
{
$this->dispatch('reset-captcha');

parent::throwFailureValidationException();
}
}
```

Expand Down
14 changes: 14 additions & 0 deletions resources/views/components/turnstile.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
window.onloadTurnstileCallback = () => {
turnstile.render($refs.turnstile, options)
}

resetCaptcha = () => {
turnstile.reset($refs.turnstile)
}
})()"
>
<div data-sitekey="{{config('turnstile.turnstile_site_key')}}"
Expand All @@ -39,4 +43,14 @@
</div>

<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onloadTurnstileCallback" defer></script>

@push('scripts')
<script>
document.addEventListener('livewire:init', () => {
Livewire.on('reset-captcha', (event) => {
resetCaptcha()
})
})
</script>
@endpush
</x-dynamic-component>
6 changes: 6 additions & 0 deletions tests/Fixtures/ContactUs.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\FormsComponent;
use Illuminate\Validation\ValidationException;

class ContactUs extends FormsComponent
{
Expand Down Expand Up @@ -55,4 +56,9 @@ public function render()
{
return 'fixtures.contact-us';
}

protected function onValidationError(ValidationException $exception): void
{
$this->dispatch('reset-captcha');
}
}
20 changes: 20 additions & 0 deletions tests/TurnstileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use Coderflex\FilamentTurnstile\Tests\Models\Contact;
use Coderflex\LaravelTurnstile\Facades\LaravelTurnstile;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event;

use function Pest\Livewire\livewire;

Expand Down Expand Up @@ -94,3 +95,22 @@
expect(Contact::get())
->toHaveCount(0);
});

it('reset captcha event sent, on validation error ', function () {
Event::fake();

Config::set('turnstile', [
'turnstile_site_key' => '2x00000000000000000000AB',
'turnstile_secret_key' => '2x0000000000000000000000000000000AA',
]);

livewire(ContactUs::class)
->fillForm([
'name' => null,
'email' => 'john@example.com',
'content' => 'This is a simple message',
])
->call('send')
->assertHasFormErrors(['name'])
->assertDispatched('reset-captcha');
});
Loading