Install the crate, register its provider and protect your first form with an image captcha.
Install
Add the crate:
cargo add laravel-rust-captcha
Register the provider and configure the input exemptions in src/app.rs:
use laravel_rust_captcha::CaptchaServiceProvider;
Application::configure()
.with_providers(|providers| {
providers.add(CaptchaServiceProvider::new());
})
.with_middleware(|middleware, config| {
CaptchaServiceProvider::configure_input(middleware, config, &[]);
})
That's all for a first form. The provider registers two routes, GET /captcha/{profile?} for the
image and GET /captcha/api/{profile?} for keyed challenges, the MiniJinja functions and the
Captcha validation rule.
Protect a form
Show the image and an input in the form's view:
<img src="{{ captcha_src() }}" alt="captcha">
<input type="text" name="captcha" autocomplete="off">
{% if error('captcha') %}<p>{{ error('captcha') }}</p>{% endif %}
Validate the answer in the form's input struct:
use laravel_rust_captcha::Captcha;
#[laravel::input]
#[validate(anyone)]
pub struct StoreTopic {
#[validate(required, max(200))]
title: String,
#[validate(required, Captcha::session())]
captcha: String,
}
The rule checks the image the visitor last loaded. A correct answer passes once. By default a challenge allows one attempt within 60 seconds, as mews/captcha does: after a wrong answer, the visitor needs a new image. See Configuration to change that.
Before production
Challenges live in a cache store that every process of your app shares. The default memory store
works in development but is refused in production unless the app runs as one process. Read
Deployment.