ProtectedRoute.php
67 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\DonorDashboards\Routes\Captcha; |
| 4 | |
| 5 | use WP_REST_Request; |
| 6 | |
| 7 | /** |
| 8 | * Note: Functionality forked from `give_email_access_login()`. |
| 9 | * |
| 10 | * @since 2.10.2 |
| 11 | */ |
| 12 | trait ProtectedRoute |
| 13 | { |
| 14 | |
| 15 | /** |
| 16 | * @since 2.10.2 |
| 17 | * |
| 18 | * @return bool |
| 19 | */ |
| 20 | public function isCaptchaEnabled(): bool |
| 21 | { |
| 22 | $recaptcha_key = give_get_option('recaptcha_key'); |
| 23 | $recaptcha_secret = give_get_option('recaptcha_secret'); |
| 24 | |
| 25 | return (give_is_setting_enabled(give_get_option('enable_recaptcha'))) && |
| 26 | !empty($recaptcha_key) && |
| 27 | !empty($recaptcha_secret); |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * @since 2.10.2 |
| 32 | */ |
| 33 | public function validateRecaptcha(string $value, WP_REST_Request $request, string $param): bool |
| 34 | { |
| 35 | if (!$this->isCaptchaEnabled()) { |
| 36 | return true; |
| 37 | } |
| 38 | |
| 39 | if (!$value) { |
| 40 | return false; |
| 41 | } |
| 42 | |
| 43 | $request = wp_remote_post( |
| 44 | 'https://www.google.com/recaptcha/api/siteverify', |
| 45 | [ |
| 46 | 'body' => [ |
| 47 | 'secret' => give_get_option('recaptcha_secret'), |
| 48 | 'response' => $value, |
| 49 | 'remoteip' => $request->get_param('give_ip'), |
| 50 | ], |
| 51 | ] |
| 52 | ); |
| 53 | |
| 54 | if (is_wp_error($request)) { |
| 55 | return false; |
| 56 | } |
| 57 | |
| 58 | if (200 !== wp_remote_retrieve_response_code($request)) { |
| 59 | return false; |
| 60 | } |
| 61 | |
| 62 | $response = json_decode($request['body'], true); |
| 63 | |
| 64 | return (bool)$response['success']; |
| 65 | } |
| 66 | } |
| 67 |