views:

693

answers:

2

I'm using the rails recaptcha plugin found here: http://github.com/ambethia/recaptcha/tree/master

I have signed up for an account on recaptcha.com, obtained a public & private key, and the site is configured with a global key (for now).

In config/environment.rb I setup the environment variables:

ENV['RECAPTCHA_PUBLIC_KEY'] = 'xxxxxxxxxxxxxxxx'
ENV['RECAPTCHA_PRIVATE_KEY'] = 'XXXXXXXXXXXXXXxx'

In my view I render the captcha like this:

<%= recaptcha_tags %>

And in my controller processing this form I have this:

unless verify_recaptcha #   <--  always returns false
    flash[:error] = "Your captcha entry was invalid"
    render :action=>'new'
    return
end

My problem is that verify_recaptcha always returns false.

I must be missing something simple, but I don't see it. And before I get a smart-alec reply, YES I'm typing the correct words into the captcha box :)

+2  A: 

I went in and looked at the recaptcha plugin. The pertinent part reads something like this:

recaptcha = Net::HTTP.post_form URI.parse("http://#{server}/verify"), {
            "privatekey" => private_key,
            "remoteip"   => request.remote_ip,
            "challenge"  => challenge,
            "response"   => response
          }

This takes the challenge and response and returns a response. When I tried it with a challenge and response I generated, I got "true\nsuccess". The following lines of code return false if:

answer, error = recaptcha.body.split.map { |s| s.chomp }
unless answer == "true"

Since I got back "true\nsuccess", answer will be "true", and the code should therefore pass.

Can you try sending the response directly using Net::HTTP and seeing what response you get?

Yehuda Katz
Thanks for the tip, turns out I had fat fingered my private key!
Ben Scheirman
+2  A: 

Just as a note, make sure you didn't accidentally switch around the public and private keys; they are different.

I can't tell if you're already handling the possibility that it is correct, in which case you would want to have something like this:

if verify_recaptcha
  @thing.save!
  redirect_to success_path
else
  flash[:error] = "There was an error with the recaptcha code below. Please re-enter the code and click submit." 
  render :action => 'new'
end

And remember to use:

<%= recaptcha_tags :ssl => true %>

If you are using SSL.

Jorge Israel Peña
Thanks for the tips, got those areas covered.
Ben Scheirman
Your answer prompted me to verify my keys, and turns out I had missed a trailing character from the private key. Thanks!
Ben Scheirman