针对 Ruby 应用程序的 ReCaptcha 插件
Author: Jason L Perry (http://ambethia.com)
Copyright: Copyright (c) 2007-2013 Jason L Perry
License: MIT
Info: https://github.com/ambethia/recaptcha
Bugs: https://github.com/ambethia/recaptcha/issues
This gem provides helper methods for the reCAPTCHA API. In your
views you can use the recaptcha_tags method to embed the needed javascript, and you can validate
in your controllers with verify_recaptcha or verify_recaptcha!, which raises an error on
failure.
Go to the reCAPTCHA admin console to obtain a reCAPTCHA API key.
The reCAPTCHA type(s) that you choose for your key will determine which methods to use below.
| reCAPTCHA type | Methods to use | Description |
|---|---|---|
| v3 | recaptcha_v3 |
Verify requests with a score |
| v2 Checkbox ("I'm not a robot" Checkbox) |
recaptcha_tags |
Validate requests with the "I'm not a robot" checkbox |
| v2 Invisible (Invisible reCAPTCHA badge) |
invisible_recaptcha_tags |
Validate requests in the background |
Note: You can only use methods that match your key's type. You cannot use v2 methods with a v3
key or use recaptcha_tags with a v2 Invisible key, for example. Otherwise you will get an
error like "Invalid key type" or "This site key is not enabled for the invisible captcha."
Note: Enter localhost or 127.0.0.1 as the domain if using in development with localhost:3000.
If you are having issues with Rails 7, Turbo, and Stimulus, make sure to check this Wiki page!
gem "recaptcha"
You can keep keys out of the code base with environment variables or with Rails secrets.
In development, you can use the dotenv gem. (Make sure to add it above gem 'recaptcha'.)
See Alternative API key setup for more ways to configure or override keys. See also the Configuration documentation.
export RECAPTCHA_SITE_KEY = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
export RECAPTCHA_SECRET_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
If you have an Enterprise API key:
export RECAPTCHA_ENTERPRISE = 'true'
export RECAPTCHA_ENTERPRISE_API_KEY = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA'
export RECAPTCHA_ENTERPRISE_PROJECT_ID = 'my-project'
note: you'll still have to provide RECAPTCHA_SITE_KEY, which will hold the value of your enterprise recaptcha key id. You will not need to provide a RECAPTCHA_SECRET_KEY, however.
RECAPTCHA_ENTERPRISE_API_KEY is the enterprise key of your Google Cloud Project, which you can generate here: https://console.cloud.google.com/apis/credentials.
Add recaptcha_tags to the forms you want to protect:
<%= form_for @foo do |f| %>
# …
<%= recaptcha_tags %>
# …
<% end %>
Then, add verify_recaptcha logic to each form action that you've protected:
# app/controllers/users_controller.rb
@user = User.new(params[:user].permit(:name))
if verify_recaptcha(model: @user) && @user.save
redirect_to @user
else
render 'new'
end
Please note that this setup uses reCAPTCHA_v2. For a recaptcha_v3 use, please refer to reCAPTCHA_v3 setup.
See sinatra demo for details.
gem 'recaptcha' to Gemfileinclude Recaptcha::Adapters::ViewMethods where you need recaptcha_tagsinclude Recaptcha::Adapters::ControllerMethods where you need verify_recaptcharecaptcha_tagsUse this when your key's reCAPTCHA type is "v2 Checkbox".
The following options are available:
| Option | Description |
|---|---|
:theme |
Specify the theme to be used per the API. Available options: dark and light. (default: light) |
:ajax |
Render the dynamic AJAX captcha per the API. (default: false) |
:site_key |
Override site API key from configuration |
:error |
Override the error code returned from the reCAPTCHA API (default: nil) |
:size |
Specify a size (default: nil) |
:nonce |
Optional. Sets nonce attribute for script. Can be generated via SecureRandom.base64(32). Use content_security_policy_nonce if you have config.content_security_policy_nonce_generator set in Rails. (default: nil) |
:id |
Specify an html id attribute (default: nil) |
:callback |
Optional. Name of success callback function, executed when the user submits a successful response |
:expired_callback |
Optional. Name of expiration callback function, executed when the reCAPTCHA response expires and the user needs to re-verify. |
:error_callback |
Optional. Name of error callback function, executed when reCAPTCHA encounters an error (e.g. network connectivity) |
:noscript |
Include <noscript> content (default: true) |
JavaScript resource (api.js) parameters:
| Option | Description |
|---|---|
:onload |
Optional. The name of your callback function to be executed once all the dependencies have loaded. (See explicit rendering) |
:render |
Optional. Whether to render the widget explicitly. Defaults to onload, which will render the widget in the first g-recaptcha tag it finds. (See explicit rendering) |
:hl |
Optional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. (See language codes) |
:script |
Alias for :external_script. If you do not need to add a script tag by helper you can set the option to false. It's necessary when you add a script tag manualy (default: true). |
:external_script |
Set to false to avoid including a script tag for the external api.js resource. Useful when including multiple recaptcha_tags on the same page. |
:script_async |
Set to false to load the external api.js resource synchronously. (default: true) |
:script_defer |
Set to true to defer loading of external api.js until HTML documen has been parsed. (default: true) |
Any unrecognized options will be added as attributes on the generated tag.
You can also override the html attributes for the sizes of the generated textarea and iframe
elements, if CSS isn't your thing. Inspect the source of recaptcha_tags
to see these options.
Note that you cannot submit/verify the same response token more than once or you will get a
timeout-or-duplicate error code. If you need reset the captcha and generate a new response token,
then you need to call grecaptcha.reset().
verify_recaptchaThis method returns true or false after processing the response token from the reCAPTCHA widget.
This is usually called from your controller, as seen above.
Passing in the ActiveRecord object via model: object is optional. If you pass a model—and the
captcha fails to verify—an error will be added to the object for you to use (available as
object.errors).
Why isn't this a model validation? Because that violates MVC. You can use it like this, or how ever you like.
Some of the options available:
| Option | Description |
|---|---|
:model |
Model to set errors. |
:attribute |
Model attribute to receive errors. (default: :base) |
:message |
Custom error message. |
:secret_key |
Override the secret API key from the configuration. |
:enterprise_api_key |
Override the Enterprise API key from the configuration. |
:enterprise_project_id |
Override the Enterprise project ID from the configuration. |
:timeout |
The number of seconds to wait for reCAPTCHA servers before give up. (default: 3) |
:response |
Custom response parameter. (default: params['g-recaptcha-response-data']) |
:hostname |
Expected hostname or a callable that validates the hostname, see domain validation and hostname docs. (default: nil, but can be changed by setting config.hostname) |
:env |
Current environment. The request to verify will be skipped if the environment is specified in configuration under skip_verify_env |
:json |
Boolean; defaults to false; if true, will submit the verification request by POST with the request data in JSON |
invisible_recaptcha_tagsUse this when your key's reCAPTCHA type is "v2 Invisible".
For more information, refer to: Invisible reCAPTCHA.
This is similar to recaptcha_tags, with the following additional options that are only available
on invisible_recaptcha_tags:
| Option | Description |
|---|---|
:ui |
The type of UI to render for this "invisible" widget. (default: :button):button: Renders a <button type="submit"> tag with options[:text] as the button text.:invisible: Renders a <div> tag.:input: Renders a <input type="submit"> tag with options[:text] as the button text. |
:text |
The text to show for the button. (default: "Submit") |
:inline_script |
If you do not need this helper to add an inline script tag, you can set the option to false (default: true). |
It also accepts most of the options that recaptcha_tags accepts, including the following:
| Option | Description |
|---|---|
:site_key |
Override site API key from configuration |
:nonce |
Optional. Sets nonce attribute for script tag. Can be generated via SecureRandom.base64(32). Use content_security_policy_nonce if you have config.content_security_policy_nonce_generator set in Rails. (default: nil) |
:id |
Specify an html id attribute (default: nil) |
暂无开放 Issues,或尚未同步最近议题。