use std::sync::{Arc, Mutex, PoisonError};
use async_trait::async_trait;
use serde_json::{Map, Value};
use crate::contracts::CaptchaDriver;
use crate::result::VerificationResult;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attempt {
pub token: String,
pub ip: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FakeDriver {
success: bool,
score: Option<f64>,
attempts: Arc<Mutex<Vec<Attempt>>>,
}
impl FakeDriver {
pub fn new(success: bool, score: Option<f64>) -> Self {
Self {
success,
score,
attempts: Arc::default(),
}
}
pub fn attempts(&self) -> Vec<Attempt> {
self.attempts.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
}
#[async_trait]
impl CaptchaDriver for FakeDriver {
fn name(&self) -> &str {
"fake"
}
async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
self.attempts
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(Attempt {
token: token.to_owned(),
ip: ip.map(str::to_owned),
});
VerificationResult {
success: self.success,
score: self.score,
error_codes: if self.success {
Vec::new()
} else {
vec!["fake-failure".to_owned()]
},
raw: Map::from_iter([("fake".to_owned(), Value::Bool(true))]),
}
}
fn site_key(&self) -> String {
"fake-site-key".to_owned()
}
fn script_url(&self) -> String {
String::new()
}
fn response_field(&self) -> String {
"captcha-response".to_owned()
}
}