Coder Social home page Coder Social logo

recaptcha's Introduction

reCAPTCHA

Gem Version

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.

Table of Contents

  1. Obtaining a key
  2. Rails Installation
  3. Sinatra / Rack / Ruby Installation
  4. reCAPTCHA V2 API & Usage
  1. reCAPTCHA V3 API & Usage
  1. I18n Support
  2. Testing
  3. Alternative API Key Setup

Obtaining a key

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.

Rails Installation

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.

Sinatra / Rack / Ruby installation

See sinatra demo for details.

  • add gem 'recaptcha' to Gemfile
  • set env variables
  • include Recaptcha::Adapters::ViewMethods where you need recaptcha_tags
  • include Recaptcha::Adapters::ControllerMethods where you need verify_recaptcha

reCAPTCHA v2 API and Usage

recaptcha_tags

Use 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). (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_recaptcha

This 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_tags

Use 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). (default: nil)
:id Specify an html id attribute (default: nil)
:script Same as setting both :inline_script and :external_script. If you only need one or the other, use :inline_script and :external_script instead.
: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)

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)
: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 false to defer loading of external api.js until HTML documen has been parsed. (default: true)

With a single form on a page

  1. The invisible_recaptcha_tags generates a submit button for you.
<%= form_for @foo do |f| %>
  # ... other tags
  <%= invisible_recaptcha_tags text: 'Submit form' %>
<% end %>

Then, add verify_recaptcha to your controller as seen above.

With multiple forms on a page

  1. You will need a custom callback function, which is called after verification with Google's reCAPTCHA service. This callback function must submit the form. Optionally, invisible_recaptcha_tags currently implements a JS function called invisibleRecaptchaSubmit that is called when no callback is passed. Should you wish to override invisibleRecaptchaSubmit, you will need to use invisible_recaptcha_tags script: false, see lib/recaptcha/client_helper.rb for details.
  2. The invisible_recaptcha_tags generates a submit button for you.
<%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f| %>
  # ... other tags
  <%= invisible_recaptcha_tags callback: 'submitInvisibleRecaptchaForm', text: 'Submit form' %>
<% end %>
// app/assets/javascripts/application.js
var submitInvisibleRecaptchaForm = function () {
  document.getElementById("invisible-recaptcha-form").submit();
};

Finally, add verify_recaptcha to your controller as seen above.

Programmatically invoke

  1. Specify ui option
<%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f| %>
  # ... other tags
  <button type="button" id="submit-btn">
    Submit
  </button>
  <%= invisible_recaptcha_tags ui: :invisible, callback: 'submitInvisibleRecaptchaForm' %>
<% end %>
// 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();
};

reCAPTCHA v3 API and Usage

The main differences from v2 are:

  1. you must specify an action in both frontend and backend
  2. you can choose the minimum score required for you to consider the verification a success (consider the user a human and not a robot)
  3. reCAPTCHA v3 is invisible (except for the reCAPTCHA badge) and will never interrupt your users; you have to choose which scores are considered an acceptable risk, and choose what to do (require two-factor authentication, show a v3 challenge, etc.) if the score falls below the threshold you choose

For more information, refer to the v3 documentation.

Examples

With v3, you can let all users log in without any intervention at all if their score is above some threshold, and only show a v2 checkbox recaptcha challenge (fall back to v2) if it is below the threshold:

This example sets v2 keys through environment variables. For more information on how to set up keys, please refer to the documentation here.

# .env
RECAPTCHA_SITE_KEY=6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy
RECAPTCHA_SECRET_KEY=6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx
<% if @show_checkbox_recaptcha %>
    <%= recaptcha_tags %>
  <% else %>
    <%= recaptcha_v3(action: 'login', site_key: ENV['RECAPTCHA_SITE_KEY_V3']) %>
  <% end %>
# 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

(You can also find this example in the demo app.)

Another example:

<%= form_for @user do |f| %><%= recaptcha_v3(action: 'registration') %><% end %>
# 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

recaptcha_v3

Adds an inline script tag that calls grecaptcha.execute for the given site_key and action and calls the callback with the resulting response token. You need to verify this token with verify_recaptcha in your controller in order to get the score.

By default, this inserts a hidden <input type="hidden" class="g-recaptcha-response"> tag. The value of this input will automatically be set to the response token (by the default callback function). This lets you include recaptcha_v3 within a <form> tag and have it automatically submit the token as part of the form submission.

Note: reCAPTCHA actually already adds its own hidden tag, like <textarea id="g-recaptcha-response-data-100000" name="g-recaptcha-response-data" class="g-recaptcha-response">, immediately ater the reCAPTCHA badge in the bottom right of the page — but since it is not inside of any <form> element, and since it already passes the token to the callback, this hidden textarea isn't helpful to us.

If you need to submit the response token to the server in a different way than via a regular form submit, such as via Ajax or fetch, then you can either:

  1. just extract the token out of the hidden <input> or <textarea> (both of which will have a predictable name/id), like document.getElementById('g-recaptcha-response-data-my-action').value, or
  2. write and specify a custom callback function. You may also want to pass element: false if you don't have a use for the hidden input element.

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.execute(…) or grecaptcha.enterprise.execute(…) again. This helper provides a JavaScript method (for each action) named executeRecaptchaFor{action} to make this easier. That is the same method that is invoked immediately. It simply calls grecaptcha.execute or grecaptcha.enterprise.execute again and then calls the callback function with the response token.

You will also get a timeout-or-duplicate error if too much time has passed between getting the response token and verifying it. This can easily happen with large forms that take the user a couple minutes to complete. Unlike v2, where you can use the expired-callback to be notified when the response expires, v3 appears to provide no such callback. See also 1 and 2.

To deal with this, it is recommended to call the "execute" in your form's submit handler (or immediately before sending to the server to verify if not using a form) rather than using the response token that gets generated when the page first loads. The executeRecaptchaFor{action} function mentioned above can be used if you want it to invoke a callback, or the executeRecaptchaFor{action}Async variant if you want a Promise that you can await. See demo/rails/app/views/v3_captchas/index.html.erb for an example of this.

This helper is similar to the recaptcha_tags/invisible_recaptcha_tags helpers but only accepts the following options:

Option Description
:site_key Override site API key
:action The name of the reCAPTCHA action. Actions are not case-sensitive and may only contain alphanumeric characters, slashes, and underscores, and must not be user-specific.
:nonce Optional. Sets nonce attribute for script. Can be generated via SecureRandom.base64(32). (default: nil)
:callback Name of callback function to call with the token. When element is :input, this defaults to a function named setInputWithRecaptchaResponseTokenFor#{sanitize_action(action)} that sets the value of the hidden input to the token.
:id Specify a unique id attribute for the <input> element if using element: :input. (default: "g-recaptcha-response-data-" + action)
:name Specify a unique name attribute for the <input> element if using element: :input. (default: g-recaptcha-response-data[action])
:script Same as setting both :inline_script and :external_script. (default: true).
:inline_script If true, adds an inline script tag that calls grecaptcha.execute for the given site_key and action and calls the callback with the resulting response token. Pass false if you want to handle calling grecaptcha.execute yourself. (default: true)
:element The element to render, if any (default: :input)
:input: Renders a hidden <input type="hidden"> tag. The value of this will be set to the response token by the default setInputWithRecaptchaResponseTokenFor{action} callback.
false: Doesn't render any tag. You'll have to add a custom callback that does something with the token.
:turbo If true, calls the js function which executes reCAPTCHA after all the dependencies have been loaded. This cannot be used with the js param :onload. This makes reCAPTCHAv3 usable with turbo.
:turbolinks Alias of :turbo. Will be deprecated soon.
:ignore_no_element If true, adds null element checker for forms that can be removed from the page by javascript like modals with forms. (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)
: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 true to load the external api.js resource asynchronously. (default: false)
:script_defer Set to true to defer loading of external api.js until HTML documen has been parsed. (default: false)

If using element: :input, any unrecognized options will be added as attributes on the generated <input> element.

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.

result = verify_recaptcha(action: 'action/name')
Option Description
:action The name of the reCAPTCHA action that we are verifying. Set to false or nil to skip verifying that the action matches.
:minimum_score 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)

Multiple actions on the same page

According to https://developers.google.com/recaptcha/docs/v3#placement,

Note: You can execute reCAPTCHA as many times as you'd like with different actions on the same page.

You will need to verify each action individually with a separate call to verify_recaptcha.

result_a = verify_recaptcha(action: 'a')
result_b = verify_recaptcha(action: 'b')

Because the response tokens for multiple actions may be submitted together in the same request, 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.

recaptcha_reply

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.

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.

I18n support

reCAPTCHA supports the I18n gem (it comes with English translations) To override or add new languages, add to config/locales/*.yml

# config/locales/en.yml
en:
  recaptcha:
    errors:
      verification_failed: 'reCAPTCHA was incorrect, please try again.'
      recaptcha_unreachable: 'reCAPTCHA verification server error, please try again.'

Testing

By default, reCAPTCHA is skipped in "test" and "cucumber" env. To enable it during test:

Recaptcha.configuration.skip_verify_env.delete("test")

Alternative API key setup

Recaptcha.configure

# 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).

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:

recaptcha_tags site_key: '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'

# and

verify_recaptcha secret_key: '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'

hCaptcha support

hCaptcha 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 because API handles standard g-recaptcha for compatibility.
# config/initializers/recaptcha.rb
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
end

hCaptcha uses a scoring system (higher number more likely to be a bot) which is inverse of the reCaptcha scoring system (lower number more likely to be a bot). As such, a maximum_score attribute is provided for use with hCaptcha.

result = verify_recaptcha(maximum_score: 0.7)
Option Description
:maximum_score Provide a threshold to meet or fall below. Threshold should be a float between 0 and 1 which will be tested as score <= maximum_score. (Default: nil)

Misc

recaptcha's People

Contributors

basabin54 avatar carpodaster avatar chaman avatar dlackty avatar ericproulx avatar fivepapertigers avatar gkopylov avatar grosser avatar hjhart avatar introkun avatar jalkoby avatar jcmfernandes avatar jcoyne avatar jesse avatar joaomarceloods avatar nemurimasu avatar paulbaum avatar paveltyk avatar philipqnguyen avatar rickychilcott avatar romanbsd avatar schmidt avatar shrmnk avatar talyssonoc avatar tamvm avatar theirix avatar tuned-up avatar tylerrick avatar victor-fdez avatar vin0uz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

recaptcha's Issues

Plans on moving to gemcutter?

I'm working on a project where we use ambethia-recaptcha gem and we want to remove all gems from github 'cause the are stoping gem building and eventually gem hosting. Are there any plans to move the gem to gemcutter or rubyforge?

Please, get me posted when you make the move or any other decision.

BTW, thanks for the gem ;)

Ruby 1.9.1 issue

.verify_recaptcha raises exception in Ruby 1.9.1:

Ambethia::ReCaptcha::ReCaptchaError (can't dup Symbol)

Patch: antage@84b128863a7dc9bfe792e286768534dd5338ec82

reCaptcha with Authlogic registration problem

I'm using reCaptcha with Authlogic exactly this way, but I'm experiencing a problem.

If you try to register only missing or typing wrong recaptcha it will fail and render the page again raising the recaptcha error.
But if you just click the register button again it will success register the user and tell me that is the second time I logged in in the website.
Do you know what could be hapening in my code?

def create
@user = User.create(params[:user])

respond_to do |format|
    if verify_recaptcha(@user) && @user.save
      flash[:notice] = 'Success.'
      format.html { redirect_to(@user) }
      format.xml  { render :xml => @user, :status => :created, :location => @user }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
    end
end

end

Thanks.

Verification failure

My recaptcha verification fails in production, the same code works just fine in development. I made sure the public and private keys are correct and the correct keys load in the production enviornment. My production server hostname is "server" and I generated the keys are recaptcha with that name. Where do I even begin to troubleshoot this?

In config.yml

test:
recap_pub_key: 6LcbaboSAAAAADbBxT9yLOJ7CoLWLsuAfZr-aL-H
recap_priv_key: 6LcbaboSAAAAACJMtxxfExG5dm_GcDHuZl9WVjZG
google_js_api: ABQIAAAAi_F8JNAI9__oCG-KzCfTYhTJQa0g3IQ9GZqIMmInSLzwtGDKaBQ6kTvHNGROiENaALqema6YZJEh2Q
development:
recap_pub_key: 6LcbaboSAAAAADbBxT9yLOJ7CoLWLsuAfZr-aL-H
recap_priv_key: 6LcbaboSAAAAACJMtxxfExG5dm_GcDHuZl9WVjZG
google_js_api: ABQIAAAAi_F8JNAI9__oCG-KzCfTYhTJQa0g3IQ9GZqIMmInSLzwtGDKaBQ6kTvHNGROiENaALqema6YZJEh2Q
production:
recap_pub_key: 6LcbaboSAAAAADbBxT9yLOJ7CoLWLsuAfZr-aL-H
recap_priv_key: 6LcbaboSAAAAACJMtxxfExG5dm_GcDHuZl9WVjZG
google_js_api: ABQIAAAAi_F8JNAI9__oCG-KzCfTYhTJQa0g3IQ9GZqIMmInSLzwtGDKaBQ6kTvHNGROiENaALqema6YZJEh2Q

in environment.rb
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]
ENV['RECAPTCHA_PUBLIC_KEY'] = APP_CONFIG['recap_pub_key']
ENV['RECAPTCHA_PRIVATE_KEY'] = APP_CONFIG['recap_priv_key']
ENV['GOOGLE_JS_API'] = APP_CONFIG['google_js_api']

In users_controller.rb

def create
@user = User.new(params[:user])
@user.role = Role.find_by_name('user')
v = verify_recaptcha(:model => @user, :message => "Text entered did not match the image!")
if v
if @user.save_without_session_maintenance
@user.send_later :deliver_activation_instructions!
flash[:notice] = t('users.create.confirmation')

redirect_back_or_default root_url

            redirect_to root_url
        else
            render :action => :new
        end
    else

@user.errors.add()

flash[:error] = "Text entered did not match the image"

        render :action => :new
    end
end
# in production.log

Recaptcha result - false

<User id: nil, email: "[email protected]", zip: "88888", processing_vote: false, cached_slug: nil, username: "user1", sex: 0, age: 29, lat: nil,

lng: nil, role_id: 2, posts_count: 0, active: nil, created_at: nil, updated_at: nil, crypted_password: "2754e9333463856a1aaa4a91e5616323866e8833fafc
54e3029...", password_salt: "pdQQJpXxzqHJyNXjYO_M", persistence_token: "7bd973e319a175a7048680850a552667f668ee859b9af137a16...", single_access_token:
"muJOtrpdTXPJ6cQWtZs3", perishable_token: nil, login_count: 0, failed_login_count: 0, last_request_at: nil, current_login_at: nil, last_login_at: ni
l, current_login_ip: nil, last_login_ip: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, processing:
true>
Errors for this registration

<ActiveRecord::Errors:0xb2d1044 @base=#<User id: nil, email: "[email protected]", zip: "94131", processing_post: false, cached_slug: nil, userna

me: "user1", sex: 0, age: 29, lat: nil, lng: nil, role_id: 2, posts_count: 0, active: nil, created_at: nil, updated_at: nil, crypted_password: "2754e
9333463856a1aaa4a91e5616323866e8833fafc54e3029...", password_salt: "pdQQJpXxzqHJyNXjYO_M", persistence_token: "7bd973e319a175a7048680850a552667f668ee
859b9af137a16...", single_access_token: "muJOtrpdTXPJ6cQWtZs3", perishable_token: nil, login_count: 0, failed_login_count: 0, last_request_at: nil, c
urrent_login_at: nil, last_login_at: nil, current_login_ip: nil, last_login_ip: nil, image_file_name: nil, image_content_type: nil, image_file_size:
nil, image_updated_at: nil, processing: true>, @errors=#<OrderedHash {"base"=>[#<ActiveRecord::Error:0xb0b7c54 @base=#<User id: nil, email: "[email protected]", zip: "88888", processing_vote: false, cached_slug: nil, username: "user1", sex: 0, age: 29, lat: nil, lng: nil, role_id: 2, posts_cou
nt: 0, active: nil, created_at: nil, updated_at: nil, crypted_password: "2754e9333463856a1aaa4a91e5616323866e8833fafc54e3029...", password_salt: "pdQ
QJpXxzqHJyNXjYO_M", persistence_token: "7bd973e319a175a7048680850a552667f668ee859b9af137a16...", single_access_token: "muJOtrpdTXPJ6cQWtZs3", perisha
ble_token: nil, login_count: 0, failed_login_count: 0, last_request_at: nil, current_login_at: nil, last_login_at: nil, current_login_ip: nil, last_l
ogin_ip: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, processing: true>, @Attribute=:base, @messa
ge="Text entered did not match the image!", @type="Text entered did not match the image!", @options={}>]}>>

Errors in verify.rb (Using Sinatra)

In my sinatra application recapcha gem return some errors:

  1. undefined method `remote_ip' for #Sinatra::Request:0x7fdc7e4f8820
    file: verify.rb
    location: verify_recaptcha
    line: 30
    I solve this by change in verify.rb request.remote_ip to request.ip

  2. undefined local variable or method `flash' for #MyServer:0x7f9ac350e0c8
    file: verify.rb
    location: verify_recaptcha
    line: 55
    This error i solved by adding flash = [] before "unless answer == 'true'"
    But if i write correct capcha all works fine, if i wrote wrong answer i got errors like Symbol as array index in line 38 of verify.rb or error about converting symbon to integer. I commented all in unless-else-end exept "return true" and "return false". When i do that - check of capcha retun error or pass from my app.

My test application: https://github.com/ssic7i/samples-here/blob/master/test_http.rb
My view for test application: https://github.com/ssic7i/samples-here/blob/master/check.erb

Tests not running on a clean checkout or unpacked gem

While trying to run the tests, I get the following error with ruby 1.8.7

(in /Users/schmidt/Projekte/github/recaptcha)
./test/verify_recaptcha_test.rb:2:in `require': no such file to load -- rails/version (LoadError)
  from ./test/verify_recaptcha_test.rb:2
  from /Users/schmidt/.rvm/gems/ruby-1.8.7-p248/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:5:in `load'
  from /Users/schmidt/.rvm/gems/ruby-1.8.7-p248/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:5
  from /Users/schmidt/.rvm/gems/ruby-1.8.7-p248/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:5:in `each'
  from /Users/schmidt/.rvm/gems/ruby-1.8.7-p248/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:5
rake aborted!
Command failed with status (1): [/Users/schmidt/.rvm/rubies/ruby-1.8.7-p248...]

I have rails 2.3.5 installed.

What do I need to do, to get the tests running? Should the be either simplified or publicly documented?

Thread safety issue

The code used at https://github.com/ambethia/recaptcha/blob/master/lib/recaptcha.rb#L30 is not thread safe.

The with_configuration method is modifying the globaly available Recaptcha::@configuration variable; which will cause issues.

I would advise either of this two:

  • removing this functionality and only rely on inline overrides
  • or making Recaptcha.confguration and Recaptcha.with_configuration thread based; using an other immutable variable for the process defaults.

Bring gem up to date

I took interest in your gem today when I decided I needed to add a captcha to an application I'm working on. Overall, the gem seemed simple and intuitive. I ran into some minimally discussed problems concerning Net::HTTP and it took me some time to track down the issue.

It looks like your master branch works fine, but it seems it has been some time since the hosted gem has been updated. I also noticed that your Recaptcha::VERSION module is way out of date.

This is not a complaint by any stretch. I completely understand being busy and not being able to get to side projects. I just didn't want to jump in offering pull requests without starting a discussion. Would it help you to bring your versioning back into some semantic line? Are there other outlying issues that have prevented you from going ahead with publishing a new gem?

If I can help, please let me know :)

Running app on SSL requires modifying views

Switching an app using this gem to run on SSL requires modifying all the views (and, in Typo's case, all the themes you may want to use because the themes all use recaptcha directly).

It would be much better if the default value for :ssl could be set from the configuration rather than in the view.

Why does this gem need to be told whether to use SSL or not? Would it work to use '//www.google.com/recaptcha/api' as the nonssl API URL so the browser will use HTTPS when needed? If not, could it check the URL scheme of the page?

Not compatible with Rails 2.3.5

Method recaptcha_tags throws an error at client_helper.rb line 39 because
html_safe is not available in Rails 2.3.5.
The current version of rails_xss seems to require Rails 2.3.8.

Changing client_helper.rb line 39 to:
return (html.respond_to?(:html_safe) && html.html_safe) || html
fixes the issue.

Add Error message localization

In lib/recaptcha/verify.rb you're adding error messages to the ActiveRecord's error base. Please make these messages localizable!

e.g. line 42 - verify.rb:
model.errors.add :base, options[:message] || "Oops, we failed to validate your word verification response. Please try again."
should look become
model.errors.add :base, options[:message] || t("recaptcha_not_reachable_message")

Validation errors before validation

There is a condition where recaptcha_tags will display errors on the captcha text box before a validation has occurred.

When using recaptcha on a popup window, typing in an empty or invalid re-captcha, the recaptcha_error session is set with the error. Close the window without typing in a correct captcha, and you will see the captcha text field (red) as if it had failed validations, on all subsequent page loads.

This assumes you are passing the model to verify_recaptcha, and using error_messages_for to display form validations.

John

verify_recaptcha() always return false

"config/environment.rb"

ENV['RECAPTCHA_PUBLIC_KEY'] = '6LdCbtQSAAAAAL28'
ENV['RECAPTCHA_PRIVATE_KEY'] = '6LdCbtQSAAAAAP'

view:
<%= form_tag params.merge(:action=>"create") do %>


<%= text_field_tag 'telephone',nil, :id => "tel"%>

Введите код с картинки

<%= recaptcha_tags :display => {:theme => 'white'}%>



<%= submit_tag "Бронировать" %>

<% end %>
controller:
@booking = Booking.build(booking)
if verify_recaptcha()
@booking.save
respond_with(@booking)
else
redirect_to :action => "new", :parking_id => params[:booking_step]['parking_id']
end
gemfile:
gem "recaptcha", :require => "recaptcha/rails"

problem:
verify_recaptcha() always returns false. Help me find a bug in the code.
thanks for the earlier.

recaptcha-not-reachable

I install recaptcha a few day ago and add to my application. Until today, recaptcha was work fine but now it appear the message "recaptcha-not-reachable" everytime, i don't why. whats can be wrong?

defined? flash ? flash[:recaptcha_error] : "" doesn't do what you think

You have this line in http://github.com/ambethia/recaptcha/blob/master/lib/recaptcha/client_helper.rb#L9

defined? is a very special beast

 ☃ /tmp$ ruby -ve 'p(defined? flash ? flash[:recaptcha_error] : "")'
 ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0]
 nil
 ☃ /tmp$ ruby19 -ve 'p(defined? flash ? flash[:recaptcha_error] : "")'
 ruby 1.9.2dev (2009-09-25 trunk 25091) [x86_64-darwin10.0.0]
 "expression"

or

  ☃ /tmp$ ruby -ve 'p(defined? flash &&= 3)'
   ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0]
   "assignment"
  ☃ /tmp$ ruby19 -ve 'p(defined? flash &&= 3)'
  ruby 1.9.2dev (2009-09-25 trunk 25091) [x86_64-darwin10.0.0]
  "assignment"

You should use defined?(flash) ? flash[:recaptcha_error] : ""

Use with authlogic-oid

Has anyone managed to get this working alongside authlogic-oid? It looks like there is some interference between the two in the way they are programmed (or the way authlogic assumes the create action progresses when using open id).

If anyone has managed to get it working how would I alter the following User create action so that it would work with recaptcha (I have tried various ways of inserting the verify_recaptcha method without stuffing the registration process for open id users but no luck so far).

def create
  @user = User.new(params[:user])
  @user.save do |result|
    if result
      create_flash_notice("Successfully registered",:success)
      redirect_to dashboard_url
    else
      create_flash_notice("Unable to register",:error)
      render :action => 'new'
    end
  end
end

development mode

Would be nice if you added an option to "disable" the check in development environment (so that verify_recaptcha would just return true).

invalid-request-cookie

Continue to get this invalid-request-cookie error when attempting to submit form

Wonder if this is an issue with the reCaptcha plugin, the reCaptcha service, or an issue with rails

Release new updated gem

The 0.3.1 is actually broken for Rails 3.x but unpacking the gem with latest commits does work.

Can you please release the updated gem on rubygems?

Rails 4 integration

I'm using the reCaptcha gem in my Rails 4 app, and the tag for recaptcha isn't displaying, after reloading the page it renders correctly but I suspect that this is caused for the way Turbolinks works in Rails 4 apps..
Have thought about in update the gem to be compatible with Rails4 apps?
How can I do to avoid this?
Thanks!

rake test fails

$ rake test
(in /home/tagoh/rpms/BUILDROOT/rubygem-recaptcha-0.3.1-1.fc14.x86_64/usr/lib/ruby/gems/1.8/gems/recaptcha-0.3.1)
You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install
/usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require': no such file to load -- i18n (LoadError) from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/i18n.rb:2
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/inflector/transliterate.rb:3
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/core_ext/string/inflections.rb:3
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/core_ext/array/conversions.rb:4
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/duration.rb:2
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/core_ext/time/calculations.rb:1
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/core_ext/string/conversions.rb:3
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/core_ext/string.rb:1
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:inrequire'
from ./test/verify_recaptcha_test.rb:3
from /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:4:in load' from /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:4 from /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:4:ineach'
from /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb:4
rake aborted!
Command failed with status (1): [/usr/bin/ruby -I"lib:test" "/usr/lib/ruby/...]

(See full trace by running task with --trace)

recaptcha_tags - unable to use :display option with :ajax=>true

Recently I tried to add reCapcha to a form submited by remote_form_for method. In order to display reCaptcha properly after submit, I had to pass :ajax=>true option in recaptcha_tags method.

I also tried to customize look and feel of reCaptcha using :display option with something like this:

recaptcha_tags :display=>{:theme=>'white'}, :ajax=>true

but id doesn't seem to work. However, if I use it without :ajax=>true, it works good and display options are working. I could abandon using ajax form to use normal form instead, but that's not a solution for me. Any Ideas?

recaptcha in modal/overlay

im having a problem getting the recaptcha script to generate in my modal/overlay partial.

the script im using is
<%= recaptcha_tags :display=>{:theme=>'white', :noscript => false}%>

is what happens when i load in my overlay partial. end result is i cannot see the recaptcha

is what happens when i use the above script in a regular view. and it displays properly.

is there a work around for this?

here is the gist.

https://gist.github.com/ad2ff6371de4d6443f60

rails edge issue

ActionView::TemplateError (uninitialized constant Ambethia::ReCaptcha::Helper::Builder) when using recaptcha_tags

it narrows down to this line in recaptcha.rb

xhtml = Builder::XmlMarkup.new :target => out=(''), :indent => 2 # Because I can.

Issue with playing as audio

Hi,

We have a registration page in our system which we are protecting using recaptcha. The visual challenge works fine; hence I think my settings are correct. However, when I click the audio challenge, I do not hear any sound. Even clicking 'Play sound again' does not work - the view source do not show link to google recaptcha, just a '#'. Can anyone please point out what can possibly go wrong..?

Any help/suggestion is highly appreciated.

Always wrong recaptcha

I'm trying to set up Recaptcha in my rails 3.1 app. After I install gem and set up my public and private keys in a config/initializers/recaptcha.rb

   Recaptcha.configure do |config|
        config.public_key  = '6Ldo....'
         config.private_key = '6Ldo.....'
    end

I use it like this:

       <%= f.buttons do %>
        <%= recaptcha_tags %> 
            <%= f.commit_button %>
       <% end %>

controller where I need to check the recaptcha I use verify_recaptcha. And no matter what, 'verify_recaptcha' returns false and so the form posting doesn't succeed.

installing as gem for rails

i took some time to figure out how to use this as a gem (not plugin) with rails.

may be the following solution for rails 2.3.5 should be included in the docs:

install the gem normally with "gem install recaptcha". then create a file in initializers/recaptcha.rb containing:

require "recaptcha/rails"
ENV['RECAPTCHA_PUBLIC_KEY'] = 'xxx'

ENV['RECAPTCHA_PRIVATE_KEY'] = 'yyy'

500 accounts created per day - all with "correct" recaptchas

Anyone experienced anything like this? Has the OCR gotten good enough to beat it?

Over a 3 hour sample, 114 correct recaptchas submitted, 43 failures. 95% spammers at least. Unique IPs, very well done except all the usernames are "word" "two-digits" "word", which helps to see which are real.

None of the bots have done anything more than try to post a link to a casino or other website (which are all nofollowed anyways)

I'm logging the captcha responses and they look sane - doesn't seem to be any easy way to load a recaptcha from the recpatcha_challenge_field token for debugging.

I've tested it as myself and it's def. not accepting invalid inputs.

Any other experiences like this, or suggestions? Thanks!

net/http

Hi

Using ruby 1.8.7, rails 2.3.4 and recaptcha 0.2.2 as a gem, require 'net/http' is mandatory in environment.rb else the verify_captcha method raises a Recaptcha::RecaptchaError exception "uninitialized constant Net::HTTP"

Please require 'net/http' in the init.rb :)

Best

Goolgle has changed server Api's

Recaptcha has stopped working since couple days, Google has apparently changed the server urls http://code.google.com/p/web2py/issues/detail?id=255. Quick fix for now is to override the module Recaptcha with updated urls

module Recaptcha
RECAPTCHA_API_SERVER = 'http://api.recaptcha.net'
RECAPTCHA_API_SECURE_SERVER = 'https://www.google.com/recaptcha/api/'
RECAPTCHA_VERIFY_SERVER = 'https://www.google.com/recaptcha/api/verify'
end

The url's in the gem have to be updated accordingly.

Cheers
Abu

support proxy config

this project does not support passing proxy configuration for captcha validate

Order of validation in README would not work

Hello,

the README says:

respond_to do |format|
  if verify_recaptcha(:model => @post,
      :message => "Oh! It's error with reCAPTCHA!") && @post.save
    # ...
  else
    # ...
  end
end

Wich would NOT work.

The method verify_recaptcha would add an error to the @post, but the call to @post.save will call @post.valid?, which will clear the errors container of @post. So at the end, only the errors from @post.valid? will survive and the error added by verify_recaptche will disappear.

To solve this, one should validate the model first and then add the recaptcha errors:

respond_to do |format|
  post_valid, recaptcha_verified = @post.save,
      verify_recaptcha(:model => @post)
  if post_valid && recaptcha_verified
    # ...
  else
    # ...
  end
end

Helper generates invalid markup

The helper currently generates invalid xhtml. Can be fixed with a couple of tweaks:

diff --git a/vendor/gems/recaptcha-0.2.3/lib/recaptcha/client_helper.rb b/vendor/gems/recaptcha-0.2.
index 213ba3e..4ee93df 100644
--- a/vendor/gems/recaptcha-0.2.3/lib/recaptcha/client_helper.rb
+++ b/vendor/gems/recaptcha-0.2.3/lib/recaptcha/client_helper.rb
@@ -22,7 +22,7 @@ module Recaptcha
         html << %{</script>\n}
       else
         html << %{<script type="text/javascript" src="#{uri}/challenge?k=#{key}}
-        html << %{#{error ? "&error=#{CGI::escape(error)}" : ""}"></script>\n}
+        html << %{#{error ? "&amp;error=#{CGI::escape(error)}" : ""}"></script>\n}
         unless options[:noscript] == false
           html << %{<noscript>\n  }
           html << %{<iframe src="#{uri}/noscript?k=#{key}" }
@@ -32,7 +32,7 @@ module Recaptcha
           html << %{<textarea name="recaptcha_challenge_field" }
           html << %{rows="#{options[:textarea_rows] ||= 3}" }
           html << %{cols="#{options[:textarea_cols] ||= 40}"></textarea>\n  }
-          html << %{<input type="hidden" name="recaptcha_response_field" value="manual_challenge">}
+          html << %{<input type="hidden" name="recaptcha_response_field" value="manual_challenge" />}
           html << %{</noscript>\n}
         end
       end

Display option does not work with :ajax set to true

The offending line is line 20 of lib/recaptcha/client_helper.rb:

It should be:

    html << %{  Recaptcha.create('#{key}', document.getElementById('dynamic_recaptcha')#{options[:display] ? ',RecaptchaOptions' : ''});}

Instead of: html << %{ Recaptcha.create('#{key}', document.getElementById('dynamic_recaptcha')#{options[:display] ? '' : ',RecaptchaOptions'});}

The outcomes for options[:display] are reversed: if there is an options[:display] then add the RecaptchaOptions, otherwise don't bother.

Let me know if I can help further. Cheers for the gem: it's great!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.