|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Shopware\Storefront\Framework\Captcha; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\ClientInterface; |
|
6
|
|
|
use Psr\Http\Client\ClientExceptionInterface; |
|
7
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* @package storefront |
|
11
|
|
|
*/ |
|
12
|
|
|
class GoogleReCaptchaV2 extends AbstractCaptcha |
|
13
|
|
|
{ |
|
14
|
|
|
public const CAPTCHA_NAME = 'googleReCaptchaV2'; |
|
15
|
|
|
public const CAPTCHA_REQUEST_PARAMETER = '_grecaptcha_v2'; |
|
16
|
|
|
private const GOOGLE_CAPTCHA_VERIFY_ENDPOINT = 'https://www.google.com/recaptcha/api/siteverify'; |
|
17
|
|
|
|
|
18
|
|
|
private ClientInterface $client; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @internal |
|
22
|
|
|
*/ |
|
23
|
|
|
public function __construct(ClientInterface $client) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->client = $client; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* {@inheritdoc} |
|
30
|
|
|
*/ |
|
31
|
|
|
public function isValid(Request $request, array $captchaConfig): bool |
|
32
|
|
|
{ |
|
33
|
|
|
if (!$request->get(self::CAPTCHA_REQUEST_PARAMETER)) { |
|
34
|
|
|
return false; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$captchaConfig = \func_get_args()[1] ?? []; |
|
38
|
|
|
|
|
39
|
|
|
$secretKey = !empty($captchaConfig['config']['secretKey']) ? $captchaConfig['config']['secretKey'] : null; |
|
40
|
|
|
|
|
41
|
|
|
if (!\is_string($secretKey)) { |
|
42
|
|
|
return false; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
try { |
|
46
|
|
|
$response = $this->client->request('POST', self::GOOGLE_CAPTCHA_VERIFY_ENDPOINT, [ |
|
47
|
|
|
'form_params' => [ |
|
48
|
|
|
'secret' => $secretKey, |
|
49
|
|
|
'response' => $request->get(self::CAPTCHA_REQUEST_PARAMETER), |
|
50
|
|
|
'remoteip' => $request->getClientIp(), |
|
51
|
|
|
], |
|
52
|
|
|
]); |
|
53
|
|
|
|
|
54
|
|
|
$responseRaw = $response->getBody()->getContents(); |
|
55
|
|
|
$response = json_decode($responseRaw, true); |
|
56
|
|
|
|
|
57
|
|
|
return $response && (bool) $response['success']; |
|
58
|
|
|
} catch (ClientExceptionInterface $exception) { |
|
59
|
|
|
return false; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* {@inheritdoc} |
|
65
|
|
|
*/ |
|
66
|
|
|
public function getName(): string |
|
67
|
|
|
{ |
|
68
|
|
|
return self::CAPTCHA_NAME; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|