captcha-sdk 0.0.1

Unified server-side CAPTCHA verification for Rust
Documentation
use std::net::IpAddr;

use crate::CaptchaToken;

/// Provider-independent input for one verification attempt.
#[derive(Debug)]
#[non_exhaustive]
pub struct VerificationRequest {
    /// Opaque token produced by the provider's client-side widget.
    token: CaptchaToken,
    /// End-user IP address, when available and appropriate to forward.
    remote_ip: Option<IpAddr>,
}

impl VerificationRequest {
    /// Creates a request containing the required client token.
    #[must_use]
    pub const fn new(token: CaptchaToken) -> Self {
        Self {
            token,
            remote_ip: None,
        }
    }

    /// Returns the opaque client token.
    #[must_use]
    pub const fn token(&self) -> &CaptchaToken {
        &self.token
    }

    /// Returns the end-user IP address, when one was supplied.
    #[must_use]
    pub const fn remote_ip(&self) -> Option<IpAddr> {
        self.remote_ip
    }

    /// Adds the end-user IP address.
    #[must_use]
    pub const fn with_remote_ip(mut self, remote_ip: IpAddr) -> Self {
        self.remote_ip = Some(remote_ip);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::VerificationRequest;
    use crate::CaptchaToken;

    #[test]
    fn request_preserves_the_supplied_token() {
        let raw_token = "request-preservation-test-token";
        let token = CaptchaToken::new(raw_token).expect("token should be valid");

        let request = VerificationRequest::new(token);

        assert_eq!(request.token().expose(), raw_token);
    }
}