web-base/Core/API/VerifyCaptcha.class.php

66 lines
2.0 KiB
PHP
Raw Normal View History

2020-06-26 23:32:45 +02:00
<?php
2022-11-18 18:06:46 +01:00
namespace Core\API;
2020-06-26 23:32:45 +02:00
2022-11-18 18:06:46 +01:00
use Core\API\Parameter\StringType;
use Core\Objects\Context;
2020-06-26 23:32:45 +02:00
class VerifyCaptcha extends Request {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, array(
2020-06-26 23:32:45 +02:00
"captcha" => new StringType("captcha"),
"action" => new StringType("action"),
));
$this->isPublic = false;
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2022-06-20 19:52:31 +02:00
$settings = $this->context->getSettings();
2022-06-17 20:53:35 +02:00
if (!$settings->isRecaptchaEnabled()) {
return $this->createError("Google reCaptcha is not enabled.");
}
2020-06-26 23:32:45 +02:00
$url = "https://www.google.com/recaptcha/api/siteverify";
$secret = $settings->getRecaptchaSecretKey();
$captcha = $this->getParam("captcha");
$action = $this->getParam("action");
$params = array(
"secret" => $secret,
"response" => $captcha
);
$ch = curl_init();
2022-06-17 20:53:35 +02:00
curl_setopt($ch, CURLOPT_URL, $url);
2020-06-26 23:32:45 +02:00
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = @json_decode(curl_exec($ch), true);
2022-06-17 20:53:35 +02:00
curl_close($ch);
2020-06-26 23:32:45 +02:00
$this->success = false;
$this->lastError = "Could not verify captcha: No response from google received.";
2021-11-11 14:25:26 +01:00
if ($response) {
2020-06-26 23:32:45 +02:00
$this->success = $response["success"];
2021-11-11 14:25:26 +01:00
if (!$this->success) {
2020-06-26 23:32:45 +02:00
$this->lastError = "Could not verify captcha: " . implode(";", $response["error-codes"]);
} else {
$score = $response["score"];
2022-06-17 20:53:35 +02:00
if ($action !== $response["action"]) {
2020-06-26 23:32:45 +02:00
$this->createError("Could not verify captcha: Action does not match");
2022-06-17 20:53:35 +02:00
} else if ($score < 0.7) {
2020-06-26 23:32:45 +02:00
$this->createError("Could not verify captcha: Google ReCaptcha Score < 0.7 (Your score: $score), you are likely a bot");
}
}
}
return $this->success;
}
2024-04-23 12:14:28 +02:00
public static function getDescription(): string {
return "Verifies a captcha response. This API is for internal use only.";
}
2020-06-26 23:32:45 +02:00
}