Tuesday, October 21, 2008

6 Simple steps to add reCaptcha (Human detector / pod stopper) to your rails application or Radiant

During development of my company's website www.espace.com.eg and after the launch of our all new technology Neverblock our blogs received loads of comments and ofcourse..loads of spam!

I found a marvelous rock-solid solution using reCaptcha plugin (thanks to guys at ambethia and to the modification that my friend & colleague humanzz has done.). Using the recaptcha plugin is so trivial and simple, it is explained in humanzz's & ambethia's pages, but the trick is in installing it in radiant applications.

Just follow the steps and you'll do great, just like the integration in the blogs of www.espace.com.eg.

Step 1: Register in the reCaptcha site, provide your website URL and get the public and private reCaptcha keys.

Step 2: Open your radiant project and add these three lines in the config.after_initialize block to be as follows:

config.after_initialize do
Ambethia::ReCaptcha.enabled = true
Ambethia::ReCaptcha.public_key = 'abcdefghij.....'
Ambethia::ReCaptcha.private_key = '12345.........'
end

and put the keys you got respectively.

Step 3: Download the reCaptcha plugin modified from humanzz's account at gitHub and copy-paste it in the /vendor/plugins folder in your radiant applicationand name the folder "recaptcha or whatver".

Step 4: In your /extensions/comments/app/comments_controller.rb file (or whatever applicable to your case in radiant project) add the check for the validity of the reCaptcha to verify that the poster is a human not a pod

def create
----- bla bla bla
----- bla bla bla
----- bla bla bla

if verify_recaptcha(comment)
comment.save!
else
----- Some more bla bla bla but raising error!
end


Step 5: Now you need to display the recaptcha box, and as you know (one who use radiant often!) that we can't put ruby code in the radiant admin pages, we use tags instead; so we will create our own reCaptcha tag.
Open the tag file (comment_tags.rb in this extension or case) and create a small class in the CommentTags module

module CommentTags
class Recaptcha_Generator
include Ambethia::ReCaptcha::Helper
end


Now you can create the tag by adding this to the same file:

tag "recaptcha" do |recaptcha|
if Ambethia::ReCaptcha.enabled
Recaptcha_Generator.new.recaptcha_tags()
end
end



Step 6: In your radiant admin in the comment form now add this line to submit with the comment parameters,

<r:recaptcha/>


you'll find the recaptcha box appearing now before your eyes!

Bonus Step:
If an error appeared stating you have problems with session error,open the recaptcha.rb file in the plugin in the lib folder and modify

error = options[:error] ||= session[:recaptcha_error]


to be:

error = "You are not human!" #options[:error] ||= session[:recaptcha_error]


Any questions don't hesitate to ask!