Created
March 16, 2009 17:56
-
-
Save patmaddox/79975 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
attr_accessor :captcha_response | |
validates_presence_of :captcha_response, :on => :create | |
validates_associated :captcha_response | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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