Skip to content

Instantly share code, notes, and snippets.

@patmaddox
Created March 16, 2009 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patmaddox/79975 to your computer and use it in GitHub Desktop.
Save patmaddox/79975 to your computer and use it in GitHub Desktop.
class CaptchaResponse
RECAPTCHA_API_SERVER = 'http://api.recaptcha.net'
RECAPTCHA_API_SECURE_SERVER = 'https://api-secure.recaptcha.net'
RECAPTCHA_VERIFY_SERVER = 'api-verify.recaptcha.net'
attr_writer :user
attr_reader :errors
class << self
private :new
attr_writer :mode
def build(ip, challenge, response)
case @mode
when :test_valid
FakeValidResponse.new
when :test_invalid
FakeInvalidResponse.new
else
new ip, challenge, response
end
end
end
def initialize(ip, challenge, response)
@ip = ip
@challenge = challenge
@response = response
@errors = ActiveRecord::Errors.new(self)
end
def valid?
return @valid if instance_variable_defined?(:@valid)
private_key = ENV['RECAPTCHA_PRIVATE_KEY']
raise ReCaptchaError, "No private key specified." unless private_key
begin
recaptcha = Net::HTTP.post_form URI.parse("http://#{RECAPTCHA_VERIFY_SERVER}/verify"), {
:privatekey => private_key,
:remoteip => @ip,
:challenge => @challenge,
:response => @response
}
answer, error = recaptcha.body.split.map { |s| s.chomp }
if answer == 'true'
return @valid = true
else
@errors.add_to_base "is incorrect, please try again"
return @valid = false
end
rescue Exception => e
raise ReCaptchaError, e
end
end
class FakeValidResponse
def valid?; true end
end
class FakeInvalidResponse
def valid?; false end
end
end
class User < ActiveRecord::Base
attr_accessor :captcha_response
validates_presence_of :captcha_response, :on => :create
validates_associated :captcha_response
end
class UsersController < ApplicationController
resource_controller
private
def build_object
params[:user] ||= { }
@object ||=
User.new(params[:user].merge(:captcha_response =>
CaptchaResponse.build(request.remote_ip, params[:recaptcha_challenge_field], params[:recaptcha_response_field])))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment