Implementing reCAPTCHA in your rails app

In: reCAPTCHA|Ruby on Rails

26 Jan 2010

Adding reCaptcha to rails is quite easy

First create an account with reCAPTCHA and get your API keys.

Secondly get the ambethia-recaptcha gem from github http://github.com/ambethia/recaptcha You can either install it as a gem by adding

config.gem “ambethia-recaptcha”, :lib => “recaptcha/rails”, :source => “http://gems.github.com”

to your environment.rb file within the config block, then from your rails app root you run the following command

sudo rake gems:install

Or you can install it as a plugin and this does not require you to add the gem config line into your environment.rb file, simply go to your rails app root and run the command

script/plugin install git://github.com/ambethia/recaptcha.git

You need to also add the API keys and there are several ways of doing this but I go with the simplest, simple add the following line to the bottom of the environment.rb file (make sure its not in the config block)

ENV['RECAPTCHA_PUBLIC_KEY']  = ’6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy’
ENV['RECAPTCHA_PRIVATE_KEY'] = ’6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx’

replace the strings with your API keys else your captcha wont work.

Finally you can start using reCAPTCHA by adding the following help to your forms in the view

<%= recaptcha_tags %>

To verify the captcha simple add verify_recaptcha() to your controller like the below

Old Code

if @user.save
redirect_to :action => “login”
flash[:notice] = “Your account setup is almost complete please check your mail for activation link.”
end

New Code

if verify_recaptcha() and @user.save
redirect_to :action => “login”
flash[:notice] = “Your account setup is almost complete please check your mail for activation link.”
end

This will properly validate the captcha image but will not display any error to the user if the validation fails. You can add this extra params to the verify_recaptcha method

verify_recaptcha(:model => @user, :message => “Please re-enter the words from the image again!”)

HELPER CUSTOMIZATIONS

Ajax

<%= recaptcha_tags :ajax => true %>

For SSL

<%= recaptcha_tags :ssl => true %>

Themes

<%= recaptcha_tags :display => {:theme => “white”, :tabindex => 0} %>

You can get further directions on the Gem from http://github.com/ambethia/recaptcha

Thats all folks.

Comment Form

About this blog

Just tackling programming nightmares with flares. Sometimes the tactics are smooth sometimes their rough.

Photostream

About Me

1Alfred is a seasoned programmer with over 8 years of experience, CEO of nCodedev Labs, a Ruby evangelist and activist. Loves programming most of the time, spends my free times with his family or trying out something new. He believes in doing more than expected of you and working hard at anything you find your self working on. As he always says, you don't have to take the bull by its horns all the time, you can take it by the tail too and move on to the horns when you stronger.