PHP code example of azymuthia / turnstile-bundle

1. Go to this page and download the library: Download azymuthia/turnstile-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

azymuthia / turnstile-bundle example snippets


return [
    // ...
    Azymuthia\TurnstileBundle\AzymuthiaTurnstileBundle::class => ['all' => true],
];

use Azymuthia\TurnstileBundle\VisitorIp\VisitorIpResolver;
use Symfony\Component\HttpFoundation\Request;

final class CloudflareVisitorIp implements VisitorIpResolver
{
    public function resolve(Request $request): ?string
    {
        return $request->headers->get('CF-Connecting-IP') ?? $request->getClientIp();
    }
}

use Azymuthia\TurnstileBundle\Security\TurnstileAuthenticationException;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Http\Event\LoginFailureEvent;

#[AsEventListener]
final class LogTurnstileFailures
{
    public function __invoke(LoginFailureEvent $event): void
    {
        $exception = $event->getException();

        if ($exception instanceof TurnstileAuthenticationException) {
            // $exception->getErrorCodes(), e.g. ['timeout-or-duplicate'] or ['unreachable']
        }
    }
}

use Azymuthia\TurnstileBundle\Security\TurnstileBadge;

return new Passport(
    new UserBadge($username),
    new PasswordCredentials($password),
    [new TurnstileBadge($request->request->getString('cf-turnstile-response'), 'login')],
);

use Azymuthia\TurnstileBundle\Form\TurnstileType;

$builder->add('turnstile', TurnstileType::class, [
    'turnstile_action' => 'password_reset',
]);

use Azymuthia\TurnstileBundle\Verifier\TurnstileVerifier;

$result = $verifier->verify($form->get('turnstile')->getData(), 'password_reset', $request);

if (!$result->isSuccess()) {
    // $result->getErrorCodes()
}

use Azymuthia\TurnstileBundle\Test\TurnstileMockResponseFactory;

$client->submitForm('Log in', [
    '_username' => 'alice',
    '_password' => 'secret',
    'cf-turnstile-response' => TurnstileMockResponseFactory::token('login'),
]);
twig
<form method="post" action="{{ path('login') }}">
    {# _username, _password, _csrf_token ... #}
    {{ azymuthia_turnstile_widget('login') }}
    <button type="submit">Log in</button>
</form>