SecurityCaptchaVerifier::verifyReCaptcha()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 2
dl 0
loc 13
ccs 0
cts 9
cp 0
crap 12
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace App\Module\Security\Captcha\Service;
4
5
use App\Infrastructure\Settings\Settings;
6
use App\Module\Security\Enum\SecurityType;
7
use App\Module\Security\Exception\SecurityException;
8
9
class SecurityCaptchaVerifier
10
{
11
    private array $googleSettings;
12
13 42
    public function __construct(
14
        Settings $settings,
15
    ) {
16 42
        $this->googleSettings = $settings->get('google');
17
    }
18
19
    /**
20
     * Ask google API if reCAPTCHA user response is correct or not.
21
     *
22
     * @param string $reCaptchaResponse
23
     * @param SecurityType $exceptionType Exception type (email, login, global)
24
     *
25
     * @throws SecurityException
26
     *
27
     * @return bool true when correct otherwise SecurityException
28
     */
29
    public function verifyReCaptcha(string $reCaptchaResponse, SecurityType $exceptionType): bool
30
    {
31
        $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
32
            urlencode($this->googleSettings['recaptcha']) . '&response=' . urlencode($reCaptchaResponse);
33
        $verificationResponse = file_get_contents($url);
34
        if (
35
            $verificationResponse !== false
36
            && json_decode($verificationResponse, true, 512, JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR)['success']
37
        ) {
38
            return true;
39
        }
40
        $errMsg = 'reCAPTCHA verification failed';
41
        throw new SecurityException('captcha', $exceptionType, $errMsg);
42
    }
43
}
44