Crate hcaptcha_derive

source ·
Expand description

Derive macro for hcaptcha::Hcaptcha

Derives the Hcaptcha trait requirements for a struct such as in the example below of a contact form providing the hcaptcha response token, the client ip address of the client and the Hcaptcha service sitekey.

use hcaptcha::Hcaptcha;

#[derive(Hcaptcha)]
pub struct ContactForm {
    name: String,
    phone: String,
    email: String,
    message: String,
    #[captcha]
    hcaptcha: String,
    #[remoteip]
    ip: String,
    #[sitekey]
    key: String,
}

The derive macro provides code such as the following:

 impl Hcaptcha for ContactForm {
     fn valid_response(
         &self,
         secret: &str,
         uri: Option<String>,
     ) -> std::pin::Pin<
         Box<
             dyn std::future::Future<
                     Output = Result<hcaptcha::HcaptchaResponse,
                                     hcaptcha::HcaptchaError>,
                                     > + Send,
         >,
     > {
         let mut client = hcaptcha::HcaptchaClient::new();
         if let Some(u) = uri {
             match client.set_url(&u) {
                 Ok(c) => client = c,
                 Err(e) => {
                     return Box::pin(async { Err(e) });
                 }
             };
         };
         #[allow(unused_mut)]
         let mut captcha;
         match hcaptcha::HcaptchaCaptcha::new(&self.hcaptcha) {
             Ok(c) => captcha = c,
             Err(e) => {
                 return Box::pin(async { Err(e) });
             }
         };
         match captcha.set_remoteip(&self.ip) {
             Ok(c) => captcha = c,
             Err(e) => {
                 return Box::pin(async { Err(e) });
             }
         };
         match captcha.set_sitekey(&self.key) {
             Ok(c) => captcha = c,
             Err(e) => {
                 return Box::pin(async { Err(e) });
             }
         };
         let request;
         match hcaptcha::HcaptchaRequest::new(&secret, captcha) {
             Ok(r) => request = r,
             Err(e) => {
                 return Box::pin(async { Err(e) });
             }
         };
         Box::pin(client.verify_client_response(request))
     }
 }

Derive Macros§

  • Derive the Hcaptcha trait for a struct.