use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Map, Value};
use crate::config::{DriverConfig, RecaptchaV3Config};
use crate::contracts::CaptchaDriver;
use crate::provider_client::{ask_provider, check_hostname, interpret};
use crate::result::VerificationResult;
const ENDPOINT: &str = "https://www.google.com/recaptcha/api/siteverify";
#[derive(Debug, Clone)]
pub struct RecaptchaV2Driver {
config: DriverConfig,
}
impl RecaptchaV2Driver {
pub fn new(config: DriverConfig) -> Self {
Self { config }
}
fn to_result(data: &Map<String, Value>) -> VerificationResult {
check_hostname(interpret(data), data)
}
async fn ask(secret: &str, token: &str, ip: Option<&str>) -> Result<Map<String, Value>, VerificationResult> {
ask_provider(ENDPOINT, secret, token, ip)
.await
.ok_or_else(|| VerificationResult::failure("unreachable"))
}
}
#[async_trait]
impl CaptchaDriver for RecaptchaV2Driver {
fn name(&self) -> &str {
"recaptcha_v2"
}
async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
match Self::ask(&self.config.secret, token, ip).await {
Ok(data) => Self::to_result(&data),
Err(unreachable) => unreachable,
}
}
fn site_key(&self) -> String {
self.config.key.clone()
}
fn script_url(&self) -> String {
"https://www.google.com/recaptcha/api.js".to_owned()
}
fn response_field(&self) -> String {
"g-recaptcha-response".to_owned()
}
}
#[derive(Debug, Clone)]
pub struct RecaptchaV3Driver {
config: RecaptchaV3Config,
expected_action: Option<String>,
}
impl RecaptchaV3Driver {
pub fn new(config: RecaptchaV3Config) -> Self {
Self {
config,
expected_action: None,
}
}
fn to_result(&self, data: &Map<String, Value>) -> VerificationResult {
let result = RecaptchaV2Driver::to_result(data);
if !result.success {
return result;
}
if let Some(expected) = &self.expected_action
&& data.get("action").and_then(Value::as_str) != Some(expected.as_str())
{
return result.refused("action-mismatch");
}
if result.score.is_some_and(|score| score < self.config.min_score) {
return result.refused("low-score");
}
result
}
}
#[async_trait]
impl CaptchaDriver for RecaptchaV3Driver {
fn name(&self) -> &str {
"recaptcha_v3"
}
async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
match RecaptchaV2Driver::ask(&self.config.secret, token, ip).await {
Ok(data) => self.to_result(&data),
Err(unreachable) => unreachable,
}
}
fn site_key(&self) -> String {
self.config.key.clone()
}
fn script_url(&self) -> String {
"https://www.google.com/recaptcha/api.js".to_owned()
}
fn response_field(&self) -> String {
"g-recaptcha-response".to_owned()
}
fn expecting_action(&self, action: Option<&str>) -> Option<Arc<dyn CaptchaDriver>> {
Some(Arc::new(Self {
config: self.config.clone(),
expected_action: action.map(str::to_owned),
}))
}
}