laracaptcha 0.1.0

Driver-based captcha for Laravel Rust: Cloudflare Turnstile and Google reCAPTCHA v2 and v3 behind one API.
Documentation
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::config::LaracaptchaConfig;

/// The package's configuration, as the running application has it.
pub fn config() -> LaracaptchaConfig {
    laravel::config().section::<LaracaptchaConfig>().clone()
}

/// The cache key a spent token is remembered under. The token itself is never stored.
pub(crate) fn token_key(token: &str) -> String {
    let digest = Sha256::digest(token.as_bytes());

    format!("laracaptcha|{digest:x}")
}

/// PHP's `(bool)` on a decoded JSON value.
pub(crate) fn truthy(value: Option<&Value>) -> bool {
    match value {
        None | Some(Value::Null) => false,
        Some(Value::Bool(flag)) => *flag,
        Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.0),
        Some(Value::String(text)) => !text.is_empty() && text != "0",
        Some(Value::Array(items)) => !items.is_empty(),
        Some(Value::Object(fields)) => !fields.is_empty(),
    }
}

/// PHP's `(float)` on a decoded JSON value that is `isset`, `None` when it is missing or null.
pub(crate) fn float(value: Option<&Value>) -> Option<f64> {
    match value? {
        Value::Number(number) => number.as_f64(),
        Value::String(text) => Some(text.trim().parse().unwrap_or(0.0)),
        Value::Bool(flag) => Some(f64::from(u8::from(*flag))),
        _ => None,
    }
}

/// HTML-escape text for an element or an attribute value.
pub(crate) fn escape(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());

    for character in text.chars() {
        match character {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#039;"),
            other => escaped.push(other),
        }
    }

    escaped
}