Jake Vanderwerf
2025-09-30 e5f67ddb413a1bb4f9cc191c782058dcfef2e72b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
<?php
namespace JVBase\managers;
 
use WP_User;
use WP_Error;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
/**
 * Cloudflare Turnstile Integration for WordPress
 *
 * Adds Turnstile protection to login and registration forms
 */
 
class CloudflareTurnstile
{
 
    private string $site_key;
    private string $secret_key;
 
    /**
     * Constructor
     */
    public function __construct()
    {
        return;
        // Set your Cloudflare Turnstile keys here
 
//        $this->site_key = JVB_CLOUDFLARE_SITE_KEY;
//        $this->secret_key = JVB_CLOUDFLARE_SECRET_KEY;
 
        // Add hooks for login and registration forms
        add_action('login_enqueue_scripts', [$this, 'enqueueTurnstileScripts']);
        add_action('login_form', [$this, 'addTurnstileToLogin']);
        add_action('register_form', [$this, 'addTurnstileToRegister']);
 
        // Add verification hooks
        add_filter('authenticate', [$this, 'verifyLoginTurnstile'], 99, 3);
        add_filter('registration_errors', [$this, 'verifyRegisterTurnstile'], 10, 3);
 
        // Add hook for lost password form
        add_action('lostpassword_form', [$this, 'addTurnstileToLogin']);
        add_action('lostpassword_post', [$this, 'verifyLostpasswordTurnstile']);
    }
 
    /**
     * Enqueue Turnstile script
     * @return void
     */
    public function enqueueTurnstileScripts():void
    {
        wp_enqueue_script(
            'cloudflare-turnstile',
            'https://challenges.cloudflare.com/turnstile/v0/api.js',
            [],
            null,
            true
        );
        // Add this line to set the async and defer attributes
        wp_script_add_data('cloudflare-turnstile', 'async', true);
        wp_script_add_data('cloudflare-turnstile', 'defer', true);
    }
 
    /**
     * Add Turnstile to login form
     * @return void
     */
    public function addTurnstileToLogin():void
    {
        echo '<div class="cf-turnstile-wrapper" style="margin: 1em 0;">';
        echo '<div class="cf-turnstile" data-sitekey="' . esc_attr($this->site_key) . '" data-theme="light"></div>';
        echo '</div>';
    }
 
    /**
     * Add Turnstile to registration form
     * @return void
     */
    public function addTurnstileToRegister():void
    {
        echo '<div class="cf-turnstile-wrapper" style="margin: 1em 0;">';
        echo '<div class="cf-turnstile" data-sitekey="' . esc_attr($this->site_key) . '" data-theme="light"></div>';
        echo '<style>.register .cf-turnstile-wrapper { clear: both; }</style>';
        echo '</div>';
    }
 
    /**
     * Verify Turnstile token
     * @param $token
     *
     * @return bool
     */
    public function verifyTurnstile($token = null):bool
    {
        // If no token is provided, try to get it from the request
        if (!$token && isset($_POST['cf-turnstile-response'])) {
            $token = $_POST['cf-turnstile-response'];
        }
 
        // If still no token, verification fails
        if (!$token) {
            return false;
        }
 
        $data = [
            'secret' => $this->secret_key,
            'response' => $token,
            'remoteip' => $_SERVER['REMOTE_ADDR']
        ];
 
        $url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
        $response = wp_remote_post($url, [
            'body' => $data,
            'timeout' => 30
        ]);
 
 
 
        if (is_wp_error($response)) {
            return false;
        }
 
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body, true);
 
        return isset($result['success']) && $result['success'] === true;
    }
 
    /**
     * Verify login form
     * @param null|WP_User|WP_Error $user
     * @param string $username
     * @param string $password
     *
     * @return WP_Error|WP_User
     */
    public function verifyLoginTurnstile(null|WP_User|WP_Error $user, string $username, string $password):WP_Error|WP_User
    {
        global $_POST;
        // Skip verification if already logged in or if no username/password
        if (is_user_logged_in() || empty($username) || empty($password)) {
            return $user;
        }
 
        // Skip on AJAX requests (for better compatibility with other plugins)
        if (wp_doing_ajax()) {
            return $user;
        }
 
        // If already have an error, just return it
        if (is_wp_error($user)) {
            return $user;
        }
 
        // Check Turnstile
        if (!$this->verifyTurnstile()) {
            return new WP_Error('turnstile_verification_failed', '<strong>ERROR</strong>: Please complete the security check.');
        }
 
        return $user;
    }
 
    /**
     * Verify registration form
     * @param WP_Error $errors
     * @param string $sanitized_user_login
     * @param string $user_email
     *
     * @return WP_Error
     */
    public function verifyRegisterTurnstile(WP_Error $errors, string $sanitized_user_login, string $user_email):WP_Error
    {
        // Skip on AJAX requests (for better compatibility with other plugins)
        if (wp_doing_ajax()) {
            return $errors;
        }
 
        // Check Turnstile
        if (!$this->verifyTurnstile()) {
            $errors->add('turnstile_verification_failed', '<strong>ERROR</strong>: Please complete the security check.');
        }
 
        return $errors;
    }
 
    /**
     * Verify lost password form
     * @param WP_Error $errors
     *
     * @return WP_Error
     */
    public function verifyLostpasswordTurnstile(WP_Error $errors):WP_Error
    {
        // Skip on AJAX requests (for better compatibility with other plugins)
        if (wp_doing_ajax()) {
            return $errors;
        }
 
        // Check if the form was submitted
        if (!isset($_POST['user_login']) || empty($_POST['user_login'])) {
            return $errors ;
        }
 
        // Check Turnstile
        if (!$this->verifyTurnstile()) {
            $redirect_to = isset($_POST['redirect_to']) ? $_POST['redirect_to'] : '';
            $errors = new WP_Error('turnstile_verification_failed', '<strong>ERROR</strong>: Please complete the security check.');
 
            // WP's lost password form handling
            wp_die($errors->get_error_message(), __('Security Check Failed', 'edmonton-ink'), [
                'response' => 403,
                'back_link' => wp_lostpassword_url($redirect_to)
            ]);
        }
        return $errors;
    }
}