Files
kupshop/bundles/KupShop/RecaptchaBundle/Util/RecaptchaGCloudUtil.php
2025-08-02 16:30:27 +02:00

85 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace KupShop\RecaptchaBundle\Util;
use Google\Cloud\RecaptchaEnterprise\V1\Assessment;
use Google\Cloud\RecaptchaEnterprise\V1\Client\RecaptchaEnterpriseServiceClient;
use Google\Cloud\RecaptchaEnterprise\V1\CreateAssessmentRequest;
use Google\Cloud\RecaptchaEnterprise\V1\Event;
use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason;
use KupShop\KupShopBundle\Config;
class RecaptchaGCloudUtil
{
public const SCORE = 0.5; // Threshold for score to consider the token valid
private ?RecaptchaEnterpriseServiceClient $client = null;
public function validate(string $token, ?string $type): bool
{
$cfg = Config::get();
$siteKey = match ($type) {
'invisible' => $cfg['Modules']['recaptcha']['gcloud_site_invisible'] ?? '',
default => $cfg['Modules']['recaptcha']['gcloud_site'] ?? '',
};
return $this->create_assessment(
siteKey: $siteKey,
token: $token,
project: $cfg['Modules']['recaptcha']['gcloud_project'] ?? '',
);
}
private function getClient()
{
if ($this->client === null) {
$cfg = Config::get();
$this->client = new RecaptchaEnterpriseServiceClient([
'apiKey' => $cfg['Modules']['recaptcha']['gcloud_api_key'] ?? '',
]);
}
return $this->client;
}
private function create_assessment(
string $siteKey,
string $token,
string $project,
): bool {
$projectName = $this->getClient()->projectName($project);
$event = (new Event())
->setSiteKey($siteKey)
->setToken($token);
$assessment = (new Assessment())
->setEvent($event);
$request = (new CreateAssessmentRequest())
->setParent($projectName)
->setAssessment($assessment);
try {
$response = $this->getClient()->createAssessment($request);
if (!$response->getTokenProperties()->getValid()) {
printf('The CreateAssessment() call failed because the token was invalid for the following reason: ');
printf(InvalidReason::name($response->getTokenProperties()->getInvalidReason()));
return false;
}
if ($response->getRiskAnalysis()->getScore() >= self::SCORE) {
return true;
}
} catch (\Exception $e) {
printf('CreateAssessment() call failed with the following error: ');
printf($e->getMessage());
}
return false;
}
}