A simple Elixir package for implementing reCAPTCHA in Elixir applications.
- Template functionality is now in a separate module:
Recaptcha.Template
. Please note: in future templating may move to a Phoenix specific package. verify
API has changed, see the code for documentation of the new API.
Most other questions about 2.x should be answered by looking over the documentation and the code. Please raise an issue if you have any problems with migrating.
- Add recaptcha to your
mix.exs
dependencies
defp deps do
[
{:recaptcha, "~> 2.0"},
]
end
- List
:recaptcha
as an application dependency
def application do
[ applications: [:recaptcha] ]
end
- Run
mix do deps.get, compile
By default the public and private keys are loaded via the RECAPTCHA_PUBLIC_KEY
and RECAPTCHA_PRIVATE_KEY
environment variables.
config :recaptcha,
public_key: {:system, "RECAPTCHA_PUBLIC_KEY"},
secret: {:system, "RECAPTCHA_PRIVATE_KEY"}
Use raw
(if you're using Phoenix.HTML) and Recaptcha.Template.display/1
methods to render the captcha widget.
<form name="someform" method="post" action="/somewhere">
...
<%= raw Recaptcha.Template.display %>
...
</form>
display
method accepts additional options as a keyword list, the options are:
Option | Action | Default |
---|---|---|
noscript |
Renders default noscript code provided by google | false |
public_key |
Sets key to the data-sitekey reCaptcha div attribute |
Public key from the config file |
hl |
Sets the language of the reCaptcha | en |
Recaptcha provides the verify/2
method. Below is an example using a Phoenix controller action:
def create(conn, params) do
case Recaptcha.verify(params["g-recaptcha-response"]) do
{:ok, response} -> do_something
{:error, errors} -> handle_error
end
end
verify
method sends a POST
request to the reCAPTCHA API and returns 2 possible values:
{:ok, %Recaptcha.Response{challenge_ts: timestamp, hostname: host}}
-> The captcha is valid, see the documentation for more details.
{:error, errors}
-> errors
contains atomised versions of the errors returned by the API, See the error documentation for more details. Errors caused by timeouts in HTTPoison or Poison encoding are also returned as atoms. If the recaptcha request succeeds but the challenge is failed, a :challenge_failed
error is returned.
verify
method also accepts a keyword list as the third parameter with the following options:
Option | Action | Default |
---|---|---|
timeout |
Time to wait before timeout | 5000 (ms) |
secret |
Private key to send as a parameter of the API request | Private key from the config file |
remote_ip |
Optional. The user's IP address, used by reCaptcha | no default |
Check out CONTRIBUTING.md if you want to help.