use laravel::config::{Env, Section};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DriverConfig {
pub key: String,
pub secret: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RecaptchaV3Config {
pub key: String,
pub secret: String,
pub min_score: f64,
}
impl Default for RecaptchaV3Config {
fn default() -> Self {
Self {
key: String::new(),
secret: String::new(),
min_score: 0.5,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Drivers {
pub turnstile: DriverConfig,
pub recaptcha_v2: DriverConfig,
pub recaptcha_v3: RecaptchaV3Config,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Messages {
pub required: String,
pub invalid: String,
pub used: String,
pub unreachable: String,
}
impl Default for Messages {
fn default() -> Self {
Self {
required: "Please complete the captcha challenge.".to_owned(),
invalid: "The captcha verification failed. Please try again.".to_owned(),
used: "This captcha has already been used. Please refresh the page and try again.".to_owned(),
unreachable: "The captcha could not be checked right now. Please try again in a moment.".to_owned(),
}
}
}
impl Messages {
pub fn spanish() -> Self {
Self {
required: "Por favor, completa el desafío captcha.".to_owned(),
invalid: "La verificación del captcha ha fallado. Inténtalo de nuevo.".to_owned(),
used: "Este captcha ya se ha usado. Recarga la página e inténtalo de nuevo.".to_owned(),
unreachable: "No se ha podido comprobar el captcha ahora mismo. Inténtalo de nuevo en un momento."
.to_owned(),
}
}
}
#[derive(Debug, Clone, Section)]
pub struct LaracaptchaConfig {
#[env("CAPTCHA_DRIVER", default = "turnstile")]
pub default: String,
#[env("CAPTCHA_PREVENT_REUSE", default = true)]
pub prevent_reuse: bool,
#[section(default = 5)]
pub reuse_ttl: u64,
#[env("CAPTCHA_LOG_FAILURES", default = false)]
pub log_failures: bool,
#[section(default = 5)]
pub timeout: u64,
#[env("CAPTCHA_HOSTNAMES", separator = ",")]
pub hostnames: Vec<String>,
#[env(with = drivers_from_env)]
pub drivers: Drivers,
pub messages: Messages,
}
fn text(env: &Env, key: &str) -> Option<String> {
env.get::<String>(key)
}
fn drivers_from_env(env: &Env) -> Option<Drivers> {
let recaptcha_key = text(env, "RECAPTCHA_KEY");
let recaptcha_secret = text(env, "RECAPTCHA_SECRET");
Some(Drivers {
turnstile: DriverConfig {
key: text(env, "TURNSTILE_KEY").unwrap_or_default(),
secret: text(env, "TURNSTILE_SECRET").unwrap_or_default(),
},
recaptcha_v2: DriverConfig {
key: recaptcha_key.clone().unwrap_or_default(),
secret: recaptcha_secret.clone().unwrap_or_default(),
},
recaptcha_v3: RecaptchaV3Config {
key: text(env, "RECAPTCHA_V3_KEY").or(recaptcha_key).unwrap_or_default(),
secret: text(env, "RECAPTCHA_V3_SECRET")
.or(recaptcha_secret)
.unwrap_or_default(),
min_score: env.get::<f64>("RECAPTCHA_V3_MIN_SCORE").unwrap_or(0.5),
},
})
}