use laravel::http::client;
use laravel::time::ToSpan;
use serde_json::{Map, Value};
use crate::result::VerificationResult;
use crate::support::{config, float, truthy};
pub(crate) async fn ask_provider(
endpoint: &str,
secret: &str,
token: &str,
ip: Option<&str>,
) -> Option<Map<String, Value>> {
let fields: Vec<(&str, &str)> = [
("secret", secret),
("response", token),
("remoteip", ip.unwrap_or_default()),
]
.into_iter()
.filter(|(_, value)| !value.is_empty())
.collect();
let response = client::post(endpoint)
.timeout((config().timeout as i64).seconds())
.form(fields)
.await
.ok()?;
Some(match response.json::<Value>() {
Ok(Value::Object(payload)) => payload,
_ => Map::new(),
})
}
pub(crate) fn check_hostname(result: VerificationResult, data: &Map<String, Value>) -> VerificationResult {
let allowed: Vec<String> = config().hostnames.iter().map(|host| host.to_lowercase()).collect();
if !result.success || allowed.is_empty() {
return result;
}
let hostname = data
.get("hostname")
.and_then(Value::as_str)
.unwrap_or_default()
.to_lowercase();
if allowed.contains(&hostname) {
return result;
}
result.refused("hostname-mismatch")
}
pub(crate) fn interpret(data: &Map<String, Value>) -> VerificationResult {
let error_codes = match data.get("error-codes") {
Some(Value::Array(codes)) => codes
.iter()
.map(|code| code.as_str().map_or_else(|| code.to_string(), str::to_owned))
.collect(),
_ => Vec::new(),
};
VerificationResult {
success: truthy(data.get("success")),
score: float(data.get("score")),
error_codes,
raw: data.clone(),
}
}