eXpl0it3r / kirby-uniform-recaptcha

Kirby 3 Plugin Extension for the Uniform Plugin
MIT License
3 stars 2 forks source link

Uniform reCAPTCHA

A Kirby 3 & 4 plugin implementing a Google reCAPTCHA v3 guard for the Uniform plugin.

Installation

Download

Git Submodule

Add the plugin as Git submodule:

git submodule add https://github.com/eXpl0it3r/kirby-uniform-recaptcha.git site/plugins/uniform-recaptcha

Composer

Add the plugin to your repository:

composer require expl0it3r/kirby-uniform-recaptcha

Configuration

Set the configuration in your config.php file:

return [
  'expl0it3r.uniform-recaptcha.siteKey' => 'my-site-key',
  'expl0it3r.uniform-recaptcha.secretKey' => 'my-secret-key',
  'expl0it3r.uniform-recaptcha.acceptableScore' => 0.5
];

Usage

Template

reCAPTCHA v3 requires the form submission to happen through JavaScript. You can use the provided helper function, which creates a JavaScript callback function and an HTML <button>:

<?= recaptchaButton('Submit', 'btn', 'ContactForm') ?>

Where the parameters are in order:

If you want full control, you can write something like the following:

<script>
  function onRecaptchaFormSubmit(token) {
    document.getElementById("ContactForm").submit();
  }
</script>
<button class="g-recaptcha btn"
        data-sitekey="<?= option('expl0it3r.uniform-recaptcha.siteKey') ?>"
        data-callback="onRecaptchaFormSubmit"
        data-action="UniformAction">Submit</button>

Note: The data-action is critical as it will be checked in the backend as well.

In order for reCAPTCHA to work, you need to provide the reCAPTCHA JavaScript file from Google.

Either include the script yourself or use the helper function recaptchaScript() in your template.

Example

<form action="<?= $page->url() ?>" method="post" id="ContactForm">
    <label for="name" class="required">Name</label>
    <input<?php if ($form->error('name')): ?> class="erroneous"<?php endif; ?> name="name" type="text" value="<?= $form->old('name') ?>">

    <!-- ... -->

    <?= csrf_field() ?>
    <?= recaptchaButton('Submit', 'btn', 'ContactForm') ?>
</form>
<?= recaptchaScript() ?>

Controller

In your controller you can use the magic method recaptchaGuard() to enable the reCAPTCHA guard:

$form = new Form(/* ... */);

if ($kirby->request()->is('POST'))
{
    $form->recaptchaGuard()
         ->emailAction(/* ... */);
}

Credits