Working example of new recaptcha with Rails?

You should try this example from RailsCarma's Blog.

Follow these steps: 1) Get the credentials 2) Add recaptcha tags 3) To handle verification, create a recaptcha class 4) In Registrations controller add verify_recaptcha method

Setup Step 1:-

Add the following to your gem file:

gem “recaptcha”, :require => “recaptcha/rails”

Step 2:-

Login to developers.google.com and sign into your gmail account and search for ‘recaptcha’. Click on “Signup for an API Key” link. Check the secret and site keys. As the name itself suggests, the secret key should be kept at a safer location whereas the site key is the public key used for authenticating to Google. Register your site name with your google account to retrieve public and private key that will be used later on the application.

After the registration is done, you will get the public key and private key. From the client side, the public key is sent to recaptcha service to request a new captcha. The private key is applied on the server side to verify if the right value is entered.

Then register for a reCAPTCHA API key and add that to your environment config files:

#put this in development.rb and in production.rb
ENV_RECAPTCHA_PUBLIC_KEY= ‘your-public-key’
ENV_RECAPTCHA_PRIVATE_KEY= ‘your-private-key’

Step 3:-

Create a file named recaptcha.rb in config/initializers to configure recaptcha parameters.
Recaptcha.configure do |config|
config.public_key = ‘ ENV_RECAPTCHA_PUBLIC_KEY’
config.private_key = ‘ENV_RECAPTCHA_PRIVATE_KEY’
config.proxy = ‘http://www.google.com/recaptcha/api/verify’
end

Step 4:- View

The Captcha Gem helps to render the actual captcha box. It’s as simple as putting the following into your view at the point where you want the captcha to appear:

<%= raw recaptcha_tags %>
If you are using SSL, use this instead:
<%= recaptcha_tags :ssl => true %>, The SSL option ensures we send a https request to the recaptcha service.

Step 5:- Controller

The Captcha Gem provides another helper method that posts to the reCaptcha API server to verify if the submission is correct. If it is then the method returns true, if not, it will add a custom error message that the recaptcha is wrong to the model instance. Here is the basic code as you might have it in the create action of your controller:-

In devise controllers, app/controllers/registrations_controller.rb, Insert the following code:

require ‘recaptcha.rb’
before_action :verify_recaptcha, only: [:create]
def verify_recaptcha
response = Recaptcha.verify(params)
session[:sign_up] = params[:user].except(:password, :password_confirmation, :remoteip)
if response.code == 200
if response[‘success’]
flash[:notice] = “Recaptcha verification successful.”
else
redirect_to new_user_registration_path(user: params[:user]),
alert: “Recaptcha verification error.”
end
else
redirect_to new_user_registration_path(user: params[:user]),
alert: “HTTP connection error.”
end
end

The session[:sign_up] is persisted as the signup form can be pre-filled if verification fails.


Using the recaptcha gem, I created an example that uses the check box method.

Code available here: https://github.com/sunnyrjuneja/recaptcha_example

The commits should be very easy to follow. Let me know if you have anymore questions.

Example application here: https://recaptcha-checkbox.herokuapp.com/

UPDATE:

Here's a way to do it without secrets.yml.

Change your initializer to look like this:

Recaptcha.configure do |config|
  config.public_key  = ENV['RECAPTCHA_PUBLIC_KEY']
  config.private_key = ENV['RECAPTCHA_PRIVATE_KEY']
end

In your development or production environment, add this to your .bashrc or .zshrc.

export RECAPTCHA_PUBLIC_KEY="YOURPUBLICKEY"
export RECAPTCHA_PRIVATE_KEY="YOURPRIVATEKEY"

If you're using Heroku to deploy do this on your command line:

heroku config:set RECAPTCHA_PUBLIC_KEY="YOURPUBLICKEY"
heroku config:set RECAPTCHA_PRIVATE_KEY="YOURPRIVATEKEY"

UPDATE 2:

The recaptcha gem now uses different method names for setting the keys.

Recaptcha.configure do |config| config.site_key = 'YOUR_SITE_KEY_HERE' config.secret_key = 'YOUR_SECRET_KEY_HERE' # Uncomment the following line if you are using a proxy server: # config.proxy = 'http://myproxy.com.au:8080' end


Please follow this:

Step 1. Create a Ruby on Rails application:-

a)Open a terminal, navigate to a directory where you have rights to create application and type: rails new recap

b)After you create the application, switch to its folder:

$cd recap

c)Type and run bundle install:

$bundle install

Step 2. Create models, views, and controllers:-

Step 3. Integrating Google Recaptcha With Ruby On Rails:-

a) Please login to Google Recaptcha website to register ur domain to get access.(https://www.google.com/recaptcha/intro/index.html)

b) Please login and register your site , with the details c)After registeration google provide the

Script tag place this snippet before the closing tag on your HTML template. div place this snippet at the end of the where you want the reCAPTCHA widget to appear.

d)Once the above steps are done, we can see the recaptcha in the site.

f)For the server side validation we can use the secret key and the response which is going to be sent as parameters to the form submit action in the controller.

g)To check whether Google has verified that user, send a GET request with these parameters:URL: https://www.google.com/recaptcha/api/siteverify

Step 4. Application Code change for server side validation.

Please see below links for more details,

1) recaptcha-in-rails

2) google-recaptcha-in-rails

In layout:

<script src='https://www.google.com/recaptcha/api.js'></script>

My view app/views/users/_form.html.erb:

<div class="g-recaptcha" data-sitekey="6LdgWwETAAAAAPwAddRqDtNbt9sdfsfsfsdJhggghhKKYTdadsHt54"></div>

In initializers:

SECRET_KEY = "my_secret_key_here"

In User Controller:

 def verify_google_recptcha(secret_key,response)
  status = `curl "https://www.google.com/recaptcha/api/siteverify?secret=#{secret_key}&response=#{response}"`
     logger.info "---------------status ==> #{status}"
     hash = JSON.parse(status)
     hash["success"] == true ? true : false
  end

  def create
    @user = User.new(user_params)
    status = verify_google_recptcha(SECRET_KEY,params["g-recaptcha-response"])
    respond_to do |format|
    if @user.save && status
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
    else
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end
logger.info "---------------status ==> #{status}" will print like below

In Error:

---------------status ==> {
"success": false,
 "error-codes": [
  "missing-input-response"
 ]
}

In success

 ---------------status ==> {
"success": true
}

In that you could take status["error-codes"][0] and you could show it in _form.html.erb

See my application in heroku