Passed
Push — trunk ( c83b87...a87e38 )
by Christian
22:40 queued 02:13
created

GoogleReCaptchaV2::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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