Recaptcha.Verifier (recaptcha_v3 v0.1.0)
View SourcePlug middleware for automatic reCAPTCHA v3 verification.
This module provides a Plug that automatically verifies reCAPTCHA tokens in incoming requests. It integrates seamlessly with Phoenix applications and other Plug-based web frameworks to provide server-side reCAPTCHA verification without manual intervention.
Usage
Add the plug to your router, controller, or pipeline:
Router Pipeline
pipeline :protected do
plug :accepts, ["html"]
plug :fetch_session
plug :protect_from_forgery
plug Recaptcha.Verifier
end
Controller
defmodule MyAppWeb.ContactController do
use MyAppWeb, :controller
plug Recaptcha.Verifier
def create(%{assigns: %{recaptcha_response: recaptcha}} = conn, params) do
# Token has been verified, access the response
%{score: score} = recaptcha
# Process the request...
end
end
Configuration
The plug can be configured with options:
plug Recaptcha.Verifier, client: custom_client
Available options:
:client
- Custom API client (defaults toRecaptcha.API.client()
)
Request Processing
The plug follows this flow:
- Token Extraction: Looks for
g-recaptcha-response
parameter - Verification: Calls Google's reCAPTCHA API with the token
- Success Handling: Attaches response to
conn.assigns.recaptcha_response
- Error Handling: Raises appropriate exceptions for failures
- Pass Through: Requests without tokens are passed through unchanged
Error Handling
The plug raises structured exceptions for different failure scenarios:
Recaptcha.VerificationError
- When reCAPTCHA verification failsRecaptcha.APIError
- When the API request encounters an error
These exceptions should be handled by your application's error handling middleware or try/catch blocks.