### Configure and Run v3 Recaptcha Examples Source: https://github.com/ambethia/recaptcha/blob/master/demo/rails/Readme.md For v3 examples, obtain a v3 key, set the site and secret keys as environment variables, start the server, and visit the v3 captchas page. ```bash export RECAPTCHA_SITE_KEY=your_v3_key export RECAPTCHA_SECRET_KEY=your_v3_key ``` ```bash rails s ``` -------------------------------- ### Run v2 Recaptcha Examples Source: https://github.com/ambethia/recaptcha/blob/master/demo/rails/Readme.md To run the v2 examples, start the Rails server and navigate to the captchas page. ```bash rails s ``` -------------------------------- ### Complete HTML Example with Multiple Widgets Source: https://github.com/ambethia/recaptcha/wiki/Add-multiple-widgets-to-the-same-page This is a full HTML example integrating the JavaScript callback, the HTML elements for the widgets, and the reCAPTCHA API script. It demonstrates how to set up multiple reCAPTCHA widgets on a single page. ```html reCAPTCHA demo: Explicit render for multiple widgets <%= form_for @foo do |f| %> # ...
# ... <% end %> <%= form_for @foo2 do |f| %> # ...
# ... <% end %> <%= form_for @foo3 do |f| %> # ...
# ... <% end %> ``` -------------------------------- ### Example Turnstile server response Source: https://github.com/ambethia/recaptcha/wiki/Cloudflare-Turnstile This is an example of the JSON response received from the server after a successful Turnstile verification. It includes details like action, hostname, and success status, but not a score. ```json { "action": "messages", "cdata": "", "challenge_ts": "2023-08-19T03:38:03.777Z", "error-codes": [], "hostname": "127.0.0.1", "metadata": { "interactive": false }, "success": true } ``` -------------------------------- ### Provide API Keys Per Call Source: https://github.com/ambethia/recaptcha/blob/master/README.md For setups with multiple reCAPTCHA integrations, pass site and secret keys directly as options during runtime. ```ruby recaptcha_tags site_key: '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy' # and verify_recaptcha secret_key: '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx' ``` -------------------------------- ### Configure and Run v3 Recaptcha with v2 Fallback Source: https://github.com/ambethia/recaptcha/blob/master/demo/rails/Readme.md To enable v3 with v2 fallback, unset the v3 keys, set the v3 site and secret keys, start the server, and access the v3 captchas page with the fallback parameter. ```bash unset RECAPTCHA_SITE_KEY unset RECAPTCHA_SECRET_KEY export RECAPTCHA_SITE_KEY_V3=your_v3_key export RECAPTCHA_SECRET_KEY_V3=your_v3_key ``` ```bash rails s ``` -------------------------------- ### reCAPTCHA Configuration Source: https://github.com/ambethia/recaptcha/blob/master/README.md Configuration options for the reCAPTCHA gem, including API key setup and environment skipping. ```APIDOC ## Alternative API key setup ### Recaptcha.configure Configure API keys and other settings in an initializer file. ```ruby # config/initializers/recaptcha.rb Recaptcha.configure do |config| config.site_key = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy' config.secret_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx' # Uncomment the following line if you are using a proxy server: # config.proxy = 'http://myproxy.com.au:8080' # Uncomment the following lines if you are using the Enterprise API: # config.enterprise = true # config.enterprise_api_key = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA' # config.enterprise_project_id = 'my-project' end ``` ### Recaptcha.with_configuration For temporary overwrites (not thread-safe). ```ruby Recaptcha.with_configuration(site_key: '12345') do # Do stuff with the overwritten site_key. end ``` ### Per call Pass in keys as options at runtime, for code base with multiple reCAPTCHA setups: ```ruby recaptcha_tags site_key: '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy' # and verify_recaptcha secret_key: '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx' ``` ## Testing By default, reCAPTCHA is skipped in "test" and "cucumber" env. To enable it during test: ```ruby Recaptcha.configuration.skip_verify_env.delete("test") ``` ``` -------------------------------- ### Load Page-Specific JS with Webpacker Source: https://github.com/ambethia/recaptcha/wiki/Add-form-with-Turbolinks,-Recaptcha,-and-errors-handling Import and register page-specific JavaScript modules for execution on Turbolinks page loads. This setup ensures that JavaScript logic is loaded only when needed for a particular page. ```javascript // javascript/packs/application.js import { posts_show } from '../per_page/posts_show'; import { users_new } from '../per_page/users_new'; const pages = { posts_show, users_new }; document.addEventListener("turbolinks:load", () => { // I am using gon to save the page name, but you can add page name to document body and then const page = document.body.className const page = gon.controller_full // check if method exist if true execute if ('function' === typeof pages[page]){ new pages[page] } }); // we need to add this method to windows otherwise our callback will not find it // not realy happy with this solution, but could not come up with anything better window.update_recaptcha_token = (el_id,token) => { let hiddenInput = document.getElementById(el_id) hiddenInput.value = token hiddenInput.innerHTML = '' } ``` -------------------------------- ### Get reCAPTCHA Reply and Failure Reason Source: https://github.com/ambethia/recaptcha/blob/master/README.md Retrieves the raw reply from reCAPTCHA, including the score, or the reason for verification failure. ```APIDOC ## `recaptcha_reply` and `recaptcha_failure_reason` After `verify_recaptcha` has been called, you can call `recaptcha_reply` to get the raw reply from recaptcha. This can allow you to get the exact score returned by recaptcha should you need it. ### Example Usage ```ruby if verify_recaptcha(action: 'login') redirect_to @user else score = recaptcha_reply['score'] Rails.logger.warn("User #{@user.id} was denied login because of a recaptcha score of #{score}") render 'new' end ``` `recaptcha_reply` will return `nil` if the the reply was not yet fetched. `recaptcha_failure_reason` will return information if verification failed. E.g. if params was wrong or api resulted some error-codes. ``` -------------------------------- ### Verify reCAPTCHA v2 Submission in Rails Controller Source: https://github.com/ambethia/recaptcha/blob/master/README.md In your Rails controller, use `verify_recaptcha` to validate the user's submission against the reCAPTCHA response. This example includes model binding for validation errors. ```ruby # 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 ``` -------------------------------- ### Invisible Recaptcha with Multiple Forms Source: https://github.com/ambethia/recaptcha/blob/master/README.md For pages with multiple forms, a custom JavaScript callback is required to submit the form after verification. This example shows how to define and use such a callback. The `invisible_recaptcha_tags` helper generates a submit button. Ensure `verify_recaptcha` is added to your controller. ```erb <%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f| %> # ... other tags <%= invisible_recaptcha_tags callback: 'submitInvisibleRecaptchaForm', text: 'Submit form' %> <% end %> ``` ```javascript // app/assets/javascripts/application.js var submitInvisibleRecaptchaForm = function () { document.getElementById("invisible-recaptcha-form").submit(); }; ``` -------------------------------- ### Configure Recaptcha with Site and Secret Keys Source: https://github.com/ambethia/recaptcha/blob/master/README.md Set your reCAPTCHA site and secret keys globally in an initializer file. Proxy and Enterprise API settings can also be configured here. ```ruby # config/initializers/recaptcha.rb Recaptcha.configure do |config| config.site_key = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy' config.secret_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx' # Uncomment the following line if you are using a proxy server: # config.proxy = 'http://myproxy.com.au:8080' # Uncomment the following lines if you are using the Enterprise API: # config.enterprise = true # config.enterprise_api_key = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA' # config.enterprise_project_id = 'my-project' end ``` -------------------------------- ### Backend verification with action Source: https://github.com/ambethia/recaptcha/wiki/Cloudflare-Turnstile Perform backend verification for Turnstile, including the response, IP, hostname, and the specific action that was performed. This allows for more granular tracking and verification. ```ruby verify_recaptcha response: params['cf-turnstile-response'], remoteip: request.ip, hostname: request.hostname, action: 'contact_us' ``` -------------------------------- ### Controller for Recaptcha and Turbolinks Source: https://github.com/ambethia/recaptcha/wiki/Add-form-with-Turbolinks,-Recaptcha,-and-errors-handling Handles user creation with Recaptcha v3 and v2 verification. Renders new form with errors on failure, preserving Turbolinks compatibility. ```ruby def create @user = User.new(user_params) recaptcha_v3_success = verify_recaptcha(action: 'signup', minimum_score: 0.5) recaptcha_v2_success = verify_recaptcha(secret_key: ENV['RECAPTCHA_SECRET_KEY_V3']) unless recaptcha_v3_success if (recaptcha_v3_success || recaptcha_v2_success) and @user.save ... head :ok # redirect with turbolinks else unless recaptcha_v3_success @show_checkbox_recaptcha = true # if there is no users erros it's recaptcha error # so we add this as error @user.errors[:base] << "Please fill the recaptcha" unless @user.errors.any? end #render :new, :layout => 'no_head_foot' render :new, status: 422#, layout: false # status is needed to update page on with error end end ``` -------------------------------- ### Backend verification with IP and Hostname Source: https://github.com/ambethia/recaptcha/wiki/Cloudflare-Turnstile Include the request's IP address and hostname in the backend verification call for Turnstile. This provides additional context for the verification process. ```ruby verify_recaptcha response: params['cf-turnstile-response'], remoteip: request.ip, hostname: request.hostname ``` -------------------------------- ### Configure reCAPTCHA API Keys via Environment Variables Source: https://github.com/ambethia/recaptcha/blob/master/README.md Set your reCAPTCHA site and secret keys using environment variables. For development, consider using the dotenv gem. ```shell export RECAPTCHA_SITE_KEY = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy' export RECAPTCHA_SECRET_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx' ``` -------------------------------- ### Configure reCAPTCHA Script Loading Behavior Source: https://github.com/ambethia/recaptcha/blob/master/README.md Control whether the reCAPTCHA script is loaded asynchronously or deferred. `script_async: false` loads synchronously, while `script_defer: true` defers parsing. ```ruby recaptcha_tags script_async: false, script_defer: true ``` -------------------------------- ### hCaptcha Support Source: https://github.com/ambethia/recaptcha/blob/master/README.md Instructions on how to configure the gem to use hCaptcha as an alternative to reCAPTCHA. ```APIDOC ## hCaptcha support [hCaptcha](https://hcaptcha.com) is an alternative service providing reCAPTCHA API. To use hCaptcha: 1. Set a site and a secret key as usual 2. Set two options in `verify_url` and `api_service_url` pointing to hCaptcha API endpoints. 3. Disable a response limit check by setting a `response_limit` to the large enough value (reCAPTCHA is limited by 4000 characters). 4. It is not required to change a parameter name as [official docs suggest](https://docs.hcaptcha.com/switch) because API handles standard `g-recaptcha` for compatibility. ```ruby # Example configuration for hCaptcha (specific parameters may vary based on gem version and hCaptcha API) # Recaptcha.configure do |config| # config.site_key = 'YOUR_HCAPTCHA_SITE_KEY' # config.secret_key = 'YOUR_HCAPTCHA_SECRET_KEY' # config.verify_url = 'https://api.hcaptcha.com/verify' # config.api_service_url = 'https://api.hcaptcha.com/' # config.response_limit = 10000 # Example large value # end ``` ``` -------------------------------- ### HTML and JavaScript for reCAPTCHA with Link Click Source: https://github.com/ambethia/recaptcha/wiki/Recaptcha-Without-Form-Submit-via-Link This snippet shows how to render reCAPTCHA tags and attach an event listener to a link. The listener captures the username and reCAPTCHA response, adding them as data parameters to the link for manual submission. ```html = f.input :username = link_to "check availability", is_username_available_path, id: "check_username", remote: true = recaptcha_tags ajax: true ``` ```javascript $("#check_username").on('click', function() { username = $("input[name='your_form[username]']").val(); recaptcha = $("#g-recaptcha-response").val(); $(this).data("params", "username=" + username + "&g-recaptcha-response=" + recaptcha); }); ``` -------------------------------- ### Configure reCAPTCHA Enterprise API Keys Source: https://github.com/ambethia/recaptcha/blob/master/README.md For reCAPTCHA Enterprise, set the enterprise flag and provide the API key and project ID. The site key will hold the enterprise key ID. ```shell export RECAPTCHA_ENTERPRISE = 'true' export RECAPTCHA_ENTERPRISE_API_KEY = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA' export RECAPTCHA_ENTERPRISE_PROJECT_ID = 'my-project' ``` -------------------------------- ### Set Recaptcha v2 Keys via Environment Variables Source: https://github.com/ambethia/recaptcha/blob/master/README.md Configure your Recaptcha v2 site and secret keys using environment variables. This is a common practice for managing sensitive credentials. ```bash # .env RECAPTCHA_SITE_KEY=6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy RECAPTCHA_SECRET_KEY=6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx ``` -------------------------------- ### Verify reCAPTCHA v3 with Action Source: https://github.com/ambethia/recaptcha/blob/master/README.md Use this method for reCAPTCHA v3 to verify a specific action. You can optionally provide a minimum score threshold. ```ruby result = verify_recaptcha(action: 'action/name') ``` -------------------------------- ### Enable reCAPTCHA in Test Environment Source: https://github.com/ambethia/recaptcha/blob/master/README.md By default, reCAPTCHA is skipped in test environments. Uncomment this line in your configuration to enable it during testing. ```ruby Recaptcha.configuration.skip_verify_env.delete("test") ``` -------------------------------- ### Render reCAPTCHA with Custom Options Source: https://github.com/ambethia/recaptcha/blob/master/README.md Customize the reCAPTCHA widget using options such as theme, AJAX rendering, and overriding the site key. Unrecognized options are passed as HTML attributes. ```ruby recaptcha_tags site_key: "your_site_key", theme: "dark", ajax: true ``` -------------------------------- ### JavaScript for page-specific initialization Source: https://github.com/ambethia/recaptcha/wiki/Add-form-with-Turbolinks,-Recaptcha,-and-errors-handling Loads page-specific JavaScript based on the controller name. Ensures correct scripts are executed after Turbolinks loads new content. ```coffeescript class Init constructor: -> ... # some code every page uses # find if page have own js page = gon.controller_full # 'users_new' # you don't have to use gon, you can read controller name from body 'document.body.className' @execute_page_js(page) execute_page_js: (page) -> # check if method exist if true execute if 'function' is typeof window[page] klass = window[page] new klass() # will load the right js for every page by controller-action name document.addEventListener "turbolinks:load", -> new Init() ``` -------------------------------- ### Load monkey-patch in initializers Source: https://github.com/ambethia/recaptcha/wiki/Cloudflare-Turnstile Ensure the monkey-patch for POST verification is loaded by requiring the custom file in your Rails initializers. ```ruby require Rails.root.join('lib/recaptcha.rb') ``` -------------------------------- ### Include reCAPTCHA View Methods in Ruby Source: https://github.com/ambethia/recaptcha/blob/master/README.md Include this module in your application where you need to use the `recaptcha_tags` helper to render reCAPTCHA widgets. ```ruby include Recaptcha::Adapters::ViewMethods ``` -------------------------------- ### Include reCAPTCHA Controller Methods in Ruby Source: https://github.com/ambethia/recaptcha/blob/master/README.md Include this module in your controller where you need to use the `verify_recaptcha` method to verify user submissions. ```ruby include Recaptcha::Adapters::ControllerMethods ``` -------------------------------- ### Define reCAPTCHA Callback and Render Widgets Source: https://github.com/ambethia/recaptcha/wiki/Add-multiple-widgets-to-the-same-page Define the `onloadCallback` function to render multiple reCAPTCHA widgets. This function is called when the reCAPTCHA API script is loaded. It uses `grecaptcha.render` to attach widgets to specific HTML elements, assigning IDs like `widgetId1` and `widgetId2` for potential future reference. A callback function `verifyCallback` is also defined for one of the widgets. ```html ``` -------------------------------- ### Verify Multiple reCAPTCHA Actions Source: https://github.com/ambethia/recaptcha/blob/master/README.md When multiple actions occur on the same page, verify each individually. Ensure the script tag is included only once by setting `external_script: false` for subsequent calls. ```ruby result_a = verify_recaptcha(action: 'a') result_b = verify_recaptcha(action: 'b') ``` -------------------------------- ### Temporarily Override Recaptcha Configuration Source: https://github.com/ambethia/recaptcha/blob/master/README.md Use `Recaptcha.with_configuration` for temporary, non-thread-safe overrides of settings like the site key. ```ruby Recaptcha.with_configuration(site_key: '12345') do # Do stuff with the overwritten site_key. end ``` -------------------------------- ### Backend verification with Turnstile response param Source: https://github.com/ambethia/recaptcha/wiki/Cloudflare-Turnstile When verifying on the backend, specify the response parameter using `params['cf-turnstile-response']` to correctly identify the Turnstile submission. ```ruby verify_recaptcha response: params['cf-turnstile-response'] ``` -------------------------------- ### User New Page Class with AJAX Handlers Source: https://github.com/ambethia/recaptcha/wiki/Add-form-with-Turbolinks,-Recaptcha,-and-errors-handling Defines a class for the 'users_new' page that handles form submissions via AJAX. It includes success callbacks to navigate to a new page and error callbacks to replace the current page content with the error response. ```javascript // javascript/per_page.users_new.js import { on_error_replace_page_with_recived_respons } from './methods/replace_page_from_response' export class users_new { constructor() { form = document.getElementByid('your_form_id') $(form).on('ajax:success', (event) => { Turbolinks.visit('some_page') }); $(form).on('ajax:error', (event) => { data = event.detail[0] on_error_replace_page_with_recived_respons(data) }); } } ``` -------------------------------- ### Set reCAPTCHA Nonce for Security Source: https://github.com/ambethia/recaptcha/blob/master/README.md Provide a nonce for the reCAPTCHA script for enhanced security, especially when using Content Security Policy. A nonce can be generated using `SecureRandom.base64(32)`. ```ruby recaptcha_tags nonce: SecureRandom.base64(32) ``` -------------------------------- ### Configure Recaptcha Gem Source: https://github.com/ambethia/recaptcha/blob/master/README.md Configure the Recaptcha gem with site key, secret key, and API endpoints. Supports hCaptcha by specifying custom URLs. ```ruby Recaptcha.configure do |config| config.site_key = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy' config.secret_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx' config.verify_url = 'https://hcaptcha.com/siteverify' config.api_server_url = 'https://hcaptcha.com/1/api.js' config.response_limit = 100000 config.response_minimum = 100 end ``` -------------------------------- ### Stimulus Controller for Recaptcha v2 Source: https://github.com/ambethia/recaptcha/wiki/Recaptcha-with-Turbo-and-Stimulus A Stimulus controller to initialize and render the Recaptcha v2 widget. It uses the `siteKey` value passed from the HTML data attributes. ```javascript // recaptcha_v2_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { static values = { siteKey: String } initialize() { grecaptcha.render("recaptchaV2", { sitekey: this.siteKeyValue } ) } } ``` -------------------------------- ### Load reCAPTCHA API with Explicit Render Source: https://github.com/ambethia/recaptcha/wiki/Add-multiple-widgets-to-the-same-page This script tag loads the reCAPTCHA API. The `onload=onloadCallback` parameter specifies the JavaScript function to call once the API is loaded, and `render=explicit` enables explicit rendering mode, which is necessary for rendering multiple widgets manually. ```html ``` -------------------------------- ### Combined Recaptcha Verification in Controller Source: https://github.com/ambethia/recaptcha/wiki/Recaptcha-with-Turbo-and-Stimulus Modify the controller to first attempt verification with Recaptcha v3, and if that fails, attempt verification with Recaptcha v2. Any validation errors are added to the user object. ```ruby def create @user = User.new user_params check = (verify_recaptcha action: 'signup', minimum_score: 0.7, secret_key: ENV['RECAPTCHA_SECRET_V3']) || (verify_recaptcha model: @user, secret_key: ENV['RECAPTCHA_SECRET']) if check && @user.save # Everything is good else @user.validate # add any other validation errors # @user.validate generates a new errors, so that recaptcha error message cannot be seen. @user.errors.add(:base, t('recaptcha.errors.verification_failed')) unless check render :new end end ``` -------------------------------- ### Add Turnstile action verification with data-attributes Source: https://github.com/ambethia/recaptcha/wiki/Cloudflare-Turnstile Supply actions for Turnstile verification as data-attributes on the recaptcha tag, prefixed with `data-`. This is supported even though actions are typically a v3 feature. ```ruby recaptcha_tags class: 'cf-turnstile', json: true, 'data-action': 'contact_us' ``` -------------------------------- ### Control reCAPTCHA Script Loading Source: https://github.com/ambethia/recaptcha/blob/master/README.md Manage the loading of the external `api.js` script. Set `external_script: false` to prevent the helper from including the script tag, which is useful when including it manually or multiple times. ```ruby recaptcha_tags external_script: false ``` -------------------------------- ### Recaptcha v3 for User Registration Form Source: https://github.com/ambethia/recaptcha/blob/master/README.md Integrate Recaptcha v3 into a user registration form. This snippet shows how to include the v3 tags within the form builder. ```erb <%= form_for @user do |f| %> … <%= recaptcha_v3(action: 'registration') %> … <% end %> ``` -------------------------------- ### Access reCAPTCHA Reply and Failure Reason Source: https://github.com/ambethia/recaptcha/blob/master/README.md After verification, `recaptcha_reply` retrieves the raw response, including the score. `recaptcha_failure_reason` provides details if verification fails. ```ruby if verify_recaptcha(action: 'login') redirect_to @user else score = recaptcha_reply['score'] Rails.logger.warn("User #{@user.id} was denied login because of a recaptcha score of #{score}") render 'new' end ``` -------------------------------- ### Configure reCAPTCHA I18n Source: https://github.com/ambethia/recaptcha/blob/master/README.md Customize reCAPTCHA error messages by adding translations to your `config/locales/*.yml` files. ```yaml # config/locales/en.yml en: recaptcha: errors: verification_failed: 'reCAPTCHA was incorrect, please try again.' recaptcha_unreachable: 'reCAPTCHA verification server error, please try again.' ``` -------------------------------- ### Verify reCAPTCHA (v3) Source: https://github.com/ambethia/recaptcha/blob/master/README.md Verifies a reCAPTCHA submission using reCAPTCHA v3. Allows specifying an action and a minimum score for validation. ```APIDOC ## `verify_recaptcha` (use with v3) This works the same as for v2, except that you may pass an `action` and `minimum_score` if you wish to validate that the action matches or that the score is above the given threshold, respectively. ### Method ```ruby verify_recaptcha(action: 'action/name') ``` ### Parameters #### Options - `:action` (string) - The name of the reCAPTCHA action that we are verifying. Set to `false` or `nil` to skip verifying that the action matches. - `:minimum_score` (float) - Provide a threshold to meet or exceed. Threshold should be a float between 0 and 1 which will be tested as `score >= minimum_score`. (Default: `nil`) ### Example Usage ```ruby result = verify_recaptcha(action: 'action/name') ``` ### Multiple Actions To verify multiple actions on the same page, call `verify_recaptcha` for each action individually. ```ruby result_a = verify_recaptcha(action: 'a') result_b = verify_recaptcha(action: 'b') ``` When multiple actions are submitted together, they are passed as a hash under `params['g-recaptcha-response-data']` with the action as the key. It is recommended to pass `external_script: false` on all but one of the calls to `recaptcha` since you only need to include the script tag once for a given `site_key`. ``` -------------------------------- ### Add reCAPTCHA Gem to Rails Project Source: https://github.com/ambethia/recaptcha/blob/master/README.md Add the reCAPTCHA gem to your application's Gemfile to include its functionality. ```ruby gem "recaptcha" ``` -------------------------------- ### HTML Elements for reCAPTCHA Widgets Source: https://github.com/ambethia/recaptcha/wiki/Add-multiple-widgets-to-the-same-page These HTML elements serve as containers for the reCAPTCHA widgets. Each `div` must have a unique `id` that matches the one specified in the `grecaptcha.render` calls within your JavaScript callback function. ```erb <%= form_for @foo do |f| %> # ...
# ... <% end %> <%= form_for @foo2 do |f| %> # ...
# ... <% end %> <%= form_for @foo3 do |f| %> # ...
# ... <% end %> ``` -------------------------------- ### Verify Recaptcha v3 in Controller Source: https://github.com/ambethia/recaptcha/wiki/Recaptcha-with-Turbo-and-Stimulus Verify the Recaptcha v3 score in your controller action. The `action` parameter must match the one used in the view. This check is performed before saving the user. ```ruby def create @user = User.new user_params @user.validate # this line will validate the user even if Recaptcha failed. This way we will present all potential validation errors right away check = verify_recaptcha action: 'signup', minimum_score: 0.7, secret_key: ENV['RECAPTCHA_SECRET_V3'] if check && @user.save # everything is great, you can now let the user in and redirect them somewhere else render :new # if something goes wrong, we'll re-render the form end end ``` -------------------------------- ### Verify Recaptcha in Rails Controller Source: https://github.com/ambethia/recaptcha/blob/master/README.md Backend verification logic for Recaptcha v3 and v2. This controller action checks the score and handles fallback to v2 if necessary. ```ruby # app/controllers/sessions_controller.rb def create success = verify_recaptcha(action: 'login', minimum_score: 0.5, secret_key: ENV['RECAPTCHA_SECRET_KEY_V3']) checkbox_success = verify_recaptcha unless success if success || checkbox_success # Perform action else if !success @show_checkbox_recaptcha = true end render 'new' end end ``` -------------------------------- ### Render reCAPTCHA v2 Checkbox Tags Source: https://github.com/ambethia/recaptcha/blob/master/README.md Use `recaptcha_tags` to render the reCAPTCHA widget for v2 Checkbox type. Various options like theme, AJAX rendering, and custom site keys can be specified. ```ruby recaptcha_tags ``` -------------------------------- ### Enable JSON and POST for Turnstile verification Source: https://github.com/ambethia/recaptcha/wiki/Cloudflare-Turnstile If PR#461 is merged, add the `json: true` option to `recaptcha_tags` to ensure data is sent via JSON and POST, which is required for Turnstile. ```ruby recaptcha_tags class: 'cf-turnstile', json: true ``` -------------------------------- ### Replace Recaptcha with v2 Stream Source: https://github.com/ambethia/recaptcha/wiki/Recaptcha-with-Turbo-and-Stimulus When Recaptcha v3 fails, replace the existing recaptcha frame with a new one for Recaptcha v2 using a turbo stream. This new frame is configured with Stimulus. ```html <%= turbo_stream.replace 'recaptcha' do %>
<% end %> ``` -------------------------------- ### Add Data Attributes to Recaptcha Tags Source: https://github.com/ambethia/recaptcha/wiki/Data-attributes Use optional parameters in the `recaptcha_tags` helper to include data attributes like callback, ID, and sitekey for reCAPTCHA customization. ```ruby <%= recaptcha_tags(callback: 'recaptcha_callback', id: 'boogie', sitekey: 'blahblahblahblah' ) %> ``` -------------------------------- ### Programmatically Invoke Invisible Recaptcha Source: https://github.com/ambethia/recaptcha/blob/master/README.md Use this snippet to programmatically trigger the invisible recaptcha verification. Ensure the 'submit-btn' ID is present and the callback function 'submitInvisibleRecaptchaForm' is defined. ```erb <%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f| %> # ... other tags <%= invisible_recaptcha_tags ui: :invisible, callback: 'submitInvisibleRecaptchaForm' %> <% end %> ``` ```javascript // app/assets/javascripts/application.js document.getElementById('submit-btn').addEventListener('click', function (e) { // do some validation if(isValid) { // call reCAPTCHA check grecaptcha.execute(); } }); var submitInvisibleRecaptchaForm = function () { document.getElementById("invisible-recaptcha-form").submit(); }; ``` -------------------------------- ### Verify Recaptcha with Score Threshold Source: https://github.com/ambethia/recaptcha/blob/master/README.md Use the `verify_recaptcha` method with a `maximum_score` option for hCaptcha. The score is a float between 0 and 1, where a lower score is less likely to be a bot. ```ruby result = verify_recaptcha(maximum_score: 0.7) ``` -------------------------------- ### reCAPTCHA Integration in ERB View Source: https://github.com/ambethia/recaptcha/wiki/Add-form-with-Turbolinks,-Recaptcha,-and-errors-handling Renders reCAPTCHA tags in an ERB view, conditionally displaying either v2 or v3 based on a `@show_checkbox_recaptcha` flag. The v3 integration includes a callback to update a hidden input with the reCAPTCHA token. ```erb # view > new.html.erb > users_new <% if @show_checkbox_recaptcha %> <%= recaptcha_tags site_key: ENV['RECAPTCHA_SITE_KEY_V2'] %> # we need to add SITE_KEY for v2, as the v3 uses 'Recaptcha.configure' <% else %> <%= recaptcha_v3(action: 'signup', turbolinks: true, callback: 'update_recaptcha_token') %> <% end %> ``` -------------------------------- ### Verify Recaptcha for User Registration in Rails Source: https://github.com/ambethia/recaptcha/blob/master/README.md Backend verification for Recaptcha v3 during user registration. This code checks the recaptcha validity and handles the user save operation. ```ruby # app/controllers/users_controller.rb def create @user = User.new(params[:user].permit(:name)) recaptcha_valid = verify_recaptcha(model: @user, action: 'registration') if recaptcha_valid if @user.save redirect_to @user else render 'new' end else # Score is below threshold, so user may be a bot. Show a challenge, require multi-factor # authentication, or do something else. render 'new' end end ``` -------------------------------- ### Invisible Recaptcha with Single Form Source: https://github.com/ambethia/recaptcha/blob/master/README.md Use this when your form has a single reCAPTCHA widget. The `invisible_recaptcha_tags` helper generates a submit button. Ensure `verify_recaptcha` is added to your controller. ```erb <%= form_for @foo do |f| %> # ... other tags <%= invisible_recaptcha_tags text: 'Submit form' %> <% end %> ``` -------------------------------- ### Specify reCAPTCHA Callback Functions Source: https://github.com/ambethia/recaptcha/blob/master/README.md Define callback functions for successful submissions (`callback`), expired responses (`expired_callback`), or errors (`error_callback`) to handle reCAPTCHA events dynamically. ```ruby recaptcha_tags callback: "mySuccessCallback", expired_callback: "myExpiredCallback", error_callback: "myErrorCallback" ``` -------------------------------- ### Recaptcha Tags Helper Source: https://github.com/ambethia/recaptcha/blob/master/README.md The `recaptcha_tags` method is used to render reCAPTCHA widgets for v2 Checkbox type. It accepts various options to customize the appearance and behavior of the widget, including theme, AJAX rendering, site key overrides, error handling, size, nonce, ID, and callback functions for success, expiration, and errors. It also supports options for the JavaScript resource, such as onload callbacks, rendering behavior, language, and script loading preferences. ```APIDOC ## recaptcha_tags ### Description Use this when your key's reCAPTCHA type is "v2 Checkbox". This helper method renders the necessary HTML and JavaScript for the reCAPTCHA widget. ### Method `recaptcha_tags(options = {})` ### Parameters #### Options - **`:theme`** (string) - Optional - Specify the theme to be used. Available options: `dark` and `light`. (default: `light`) - **`:ajax`** (boolean) - Optional - Render the dynamic AJAX captcha. (default: `false`) - **`:site_key`** (string) - Optional - Override site API key from configuration. - **`:error`** (string) - Optional - Override the error code returned from the reCAPTCHA API (default: `nil`). - **`:size`** (string) - Optional - Specify a size (default: `nil`). - **`:nonce`** (string) - 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`** (string) - Optional - Specify an html id attribute (default: `nil`). - **`:callback`** (string) - Optional - Name of success callback function, executed when the user submits a successful response. - **`:expired_callback`** (string) - Optional - Name of expiration callback function, executed when the reCAPTCHA response expires and the user needs to re-verify. - **`:error_callback`** (string) - Optional - Name of error callback function, executed when reCAPTCHA encounters an error (e.g. network connectivity). - **`:noscript`** (boolean) - Optional - Include `