Integrating Google reCAPTCHA with Rails 5 App

Introduction

Why not Akismet? The pricing is not reasonable. If it had Amazon like low pay as you go pricing based on usage, I might consider it. In this article, we will see how to integrate Google reCAPTCHA feature to your Rails 5 app.

Steps

Step 1

Register your site. You will get a site key and a secret key. Site key looks like this:

6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy

This can be viewed in the html. The secret key is used for server side integration and it must be kept secret. For production, I added the public key and private key to the ~/.profile.

export RECAPTCHA_PUBLIC_KEY='6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
export RECAPTCHA_PRIVATE_KEY='6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'

Note that there should be no space anywhere except the export and the variable name. Otherwise you will get:

No public key specified error.

Step 2

Add the recaptcha gem to Gemfile.

gem "recaptcha", require: "recaptcha/rails"

Run bundle install.

Step 3

Add the recaptcha view helper:

<%= recaptcha_tags %>

to the form. In our case, we will add it to the feedback form. To see this in action go to RubyPlus Contact Page. If you load your form, you will see the CAPTCHA.

Ruby Plus

Step 4

In the controller, you can now verify if the user passed the robot test:

if verify_recaptcha
  # send feedback email 
end

Step 5

You have to style the failure message when reCAPTCHA fails. For Twitter Bootstrap, here is the helper:

def bootstrap_class_for(flash_type)
  map = {
         "success"         => "alert-success",
         "error"           => "alert-danger",
         "alert"           => "alert-warning",
         "notice"          => "alert-info",
         "recaptcha_error" => "alert-danger"
        }
  map.fetch(flash_type)
end

Other Uses for reCAPTCHA

You can add reCAPTCHA to your user registration page. You can also prevent automated scripts from downloading any files repeatedly. This will prevent wasting bandwidth and can save you money on Amazon S3.

Summary

In this article, you learned how to integrate Google reCAPTCHA with Rails 5 app using recaptcha gem to prevent abuse of your web app.

References

reCAPTCHA DOCS
recaptcha gem


Related Articles

Watch this Article as Screencast

You can watch this as a screencast Integrating Google reCAPTCHA with Rails 5 App