Skip to content

Commit

Permalink
Add a timout to the validator
Browse files Browse the repository at this point in the history
Signed-off-by: Jason L Perry <jasper@ambethia.com>
  • Loading branch information
chrisfinne authored and Jason L Perry committed Sep 15, 2009
1 parent e56d9fc commit ad8bbbb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.rdoc
Expand Up @@ -33,7 +33,7 @@ Some of the options available:
<tt>:noscript</tt>:: Include <noscript> content (default +true+)
<tt>:display</tt>:: Takes a hash containing the +theme+ and +tabindex+ options per the API. (default +nil+)
<tt>:public_key</tt>:: Your public API key, takes precedence over the ENV variable (default +nil+).
<tt>:error</tt>:: Override the error in +session[:recaptcha_error]+ (default +nil+).
<tt>:error</tt>:: Override the error in +flash[:recaptcha_error]+ (default +nil+).

== +verify_recaptcha+

Expand Down
28 changes: 17 additions & 11 deletions lib/recaptcha/verify.rb
Expand Up @@ -9,28 +9,34 @@ def verify_recaptcha(options = {})
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" => request.remote_ip,
"challenge" => params[:recaptcha_challenge_field],
"response" => params[:recaptcha_response_field]
}
recaptcha = nil
Timeout::timeout(options[:timeout] || 3) do
recaptcha = Net::HTTP.post_form URI.parse("http://#{RECAPTCHA_VERIFY_SERVER}/verify"), {
"privatekey" => private_key,
"remoteip" => request.remote_ip,
"challenge" => params[:recaptcha_challenge_field],
"response" => params[:recaptcha_response_field]
}
end
answer, error = recaptcha.body.split.map { |s| s.chomp }
unless answer == 'true'
session[:recaptcha_error] = error
if model
model.valid?
if Rails::VERSION::MAJOR == 2 and Rails::VERSION::MINOR >= 2
model.errors.add :base, I18n.translate("#{model.class.name.underscore}.captcha", :scope => %w(errors models), :default => (options[:message] || "Captcha response is incorrect, please try again."))
else
model.errors.add :base, options[:message] || "Captcha response is incorrect, please try again."
end
model.errors.add :base, options[:message] || "Captcha response is incorrect, please try again."
end
return false
else
session[:recaptcha_error] = nil
return true
end
rescue Timeout::Error
session[:recaptcha_error] = "recaptcha-not-reachable"
if model
model.valid?
model.errors.add :base, options[:message] || "Oops, we failed to validate your Captcha. Please try again."
end
return false
rescue Exception => e
raise RecaptchaError, e.message, e.backtrace
end
Expand Down

0 comments on commit ad8bbbb

Please sign in to comment.