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::{Map, Value};

/// The outcome of verifying one captcha token.
///
/// Provider agnostic: every driver flattens its own response shape into these fields, and the raw
/// payload stays in `raw` for whoever needs a provider specific detail. `success` is the package's
/// verdict, not the provider's: reCAPTCHA v3 reports success on a token that scores below the
/// configured threshold, and the driver turns that into a failure with a `low-score` error code.
#[derive(Debug, Clone, PartialEq)]
pub struct VerificationResult {
    /// Whether the token passed verification, score checks included.
    pub success: bool,
    /// Score reported by the provider (reCAPTCHA v3), `None` otherwise.
    pub score: Option<f64>,
    /// Provider error codes, if any.
    pub error_codes: Vec<String>,
    /// The raw provider response.
    pub raw: Map<String, Value>,
}

impl VerificationResult {
    /// A result with no score, no codes and no raw payload.
    pub fn new(success: bool) -> Self {
        Self {
            success,
            score: None,
            error_codes: Vec::new(),
            raw: Map::new(),
        }
    }

    /// A failure carrying a single error code, such as `unreachable`.
    pub fn failure(code: impl Into<String>) -> Self {
        Self {
            error_codes: vec![code.into()],
            ..Self::new(false)
        }
    }

    /// The token is good and the request may go through.
    pub fn passed(&self) -> bool {
        self.success
    }

    /// The token was refused, scored too low, or could not be checked at all.
    pub fn failed(&self) -> bool {
        !self.success
    }

    /// This result, refused, with one more error code.
    #[must_use]
    pub fn refused(&self, code: &str) -> Self {
        let mut error_codes = self.error_codes.clone();

        error_codes.push(code.to_owned());

        Self {
            success: false,
            score: self.score,
            error_codes,
            raw: self.raw.clone(),
        }
    }

    /// Whether the provider, or the package, reported this error code.
    pub fn has_error(&self, code: &str) -> bool {
        self.error_codes.iter().any(|candidate| candidate == code)
    }
}