Crate captval

Source
Expand description

captval

§Build the request and verify

Initialise a client using the Client builder to submit requests to the captval service validation.

For each request build the request using the Request builder.

Submit the request using the Client struct’s Client::verify method.

A Response is returned if the validation was successful or the method fails with a set of Error Codes if the validation failed.

§Examples

§Enterprise example (requires enterprise feature)

Token needs to be supplied by the client. This example will fail as a client-provided token is not used.

    use captval::{Client, Request};


    let request = Request::new(&secret, captcha)?
        .set_remoteip(&remoteip)?;

    let client = Client::new();

    let response = client.verify(request).await?;

    let score = match &response.score() {
        Some(v) => *v,
        None => 0.0,
    };

    let score_reasons = match &response.score_reason() {
        Some(v) => v.iter().join(", "),
        None => "".to_owned(),
    };

    println!("\tScore: {:?}\n\tReasons: {:?}", score, score_reasons);

§Lambda backend implementation.

See examples for more detail.

mod handler {

    pub async fn my_handler(e: CustomEvent, _c: Context) -> Result<CustomOutput,  Error> {
        debug!("The event logged is: {:?}", e);

        let body_str = e.body.unwrap_or_else(|| "".to_owned());
        let captcha: Captcha = serde_json::from_str(&body_str)?;

        let captval_secret = param::get_parameter(HCAPTCHA_SECRET).await?;

        let request = Request::new(&captval_secret,
            captcha)?;
        
        let client = Client::new();
        let _response = client.verify(request).await?;

        let contact_form: ContactForm = serde_json::from_str(&body_str)?;

        let notify_office_fut = send::notify_office(&contact_form);
        let notify_contact_fut = send::notify_contact(&contact_form);
        let write_fut = record::write(&contact_form);

        let (notify_office, notify_contact, write) =
            join!(notify_office_fut, notify_contact_fut, write_fut);

        if let Err(e) = notify_contact {
            error!("Notification to the contact not sent: {}", e);
            return Err("Notification not sent".into());
        }

        if let Err(e) = notify_office {
            error!("Notification to the office not sent: {}", e);
            return Err("Info not sent to office".into());
        }

        if let Err(e) = write {
            error!("Contact information not written to database: {}", e);
        }

        Ok(CustomOutput::new(
            200,
            format!("{}, thank you for your contact request.", contact_form.name),
        ))
    }
}

#[tokio::main]
async fn main() -> Result<(), Error> {

    lambda_runtime::run(lambda_runtime::handler_fn(handler::my_handler)).await?;
    Ok(())
}

§Feature Flags

The default library includes extended validation for the secret field and use of rustls TLS as the TLS backend. Disable this validation by setting default-features = false and enable rustls with features=[“nativetls-backend”].

[dependency]
captval = { version = "0.1.2", default-features = false }

The following feature flags are available:

  • enterprise - Enable methods to access enterprise service fields in the Response
  • ext - Enables extended validation of secret
  • trace - Enables tracing instrumentation on all functions. Traces are logged at the debug level. The value of the secret is not logged.
  • nativetls-backend - Enables native-tls backend in reqwests
  • rustls-backend - Enables rustls backend in reqwests

§Rust Version

This version of captval requires Rust v1.82 or later.

Structs§

Captcha
Capture the Captcha data coming from the client.
Client
Client to submit a request to a Captval validation endpoint.
ClientResponse
Request
Capture the required and optional data for a call to the captval API
Response
Result from call to verify the client’s response

Enums§

Code
Error code mapping for the error responses from the captval API. Returned in the [enum@Error] type.
Error
The error type for captval. Provides error types to capture error codes from the captcha APIs and errors output from crates used by the library.

Constants§

VERIFY_URL
Endpoint url for the Hcaptcha siteverify API.

Traits§

Captval
Captval trait

Derive Macros§

Captval
Derive the Captval trait for a struct.