Turnstile CAPTCHA

Javascript

Head over to the official Turnstile documentation to read more about how to integrate Cloudflare's CAPTCHA solution.

Insert the Turnstile script snippet in your HTML’s <head> element:

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

Configuration

Within your Cloudflare account under Turnstile create a new Site and get the site key and site secret. Set both in your .env file.

.env
TURNSTILE_SITE_KEY=sitekey
TURNSTILE_SECRET_KEY=sitesecret
Alternatively you could use the turnstile.sitekey and turnstile.secretkey config options. But using the .env file is safer.

Widget

Render the Turnstile widget with the code from the documentation or use the following snippet klub/turnstile/widget.

<?php snippet('klub/turnstile/widget') ?>

Securing Forms

It might suffice to only secure routes accessible before the user is logged in, like the Login- and Register/Sign-Up-Forms. That is assuming bots do not create valid logins.

Use the code from the documentation or use the following snippet klub/turnstile/form.

<form action="<?= site()->url() ?>/klub/login" method="POST">
    <input type="email" name="email" placeholder="Email" required
           value="<?= get('email') ?>">
    <input type="hidden" name="redirect" value="<?= page('account')->url() ?>">
    <input type="hidden" name="token" value="<?= csrf() ?>">
    <?php snippet('klub/turnstile/form') ?>
    <button type="submit">Login</button>
</form>

Behind the Scenes

The endpoints intended for public use, which are most likely targeted by bots (login, register/signup, magic-link), are preconfigured with a check for the Turnstile token.

If posted with the form the klub()->turnstile()-helper will query the https://challenges.cloudflare.com/turnstile/v0/siteverify endpoint with your secretkey and check if the form request is legit or not.

On success the form will continue as intended. If not, it will yield a 401 HTTP status code.

Kirby Klub is not affiliated with the developers of Kirby CMS. We are merely standing on the shoulder of giants.
© 2024 Bruno Meilick All rights reserved.