Module: Ambethia::ReCaptcha::Controller

Defined in:
lib/recaptcha/recaptcha.rb

Overview

Helpers

Instance Method Summary collapse

Instance Method Details

#verify_recaptcha(options = {}) ⇒ Object

Your private API can be specified in the options hash or preferably the environment variable RECAPTCHA_PUBLIC_KEY.

Raises:



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/recaptcha/recaptcha.rb', line 52

def verify_recaptcha(options = {})
  return true if SKIP_VERIFY_ENV.include? ENV['RAILS_ENV']
  private_key = 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]
    }
    answer, error = recaptcha.body.split.map { |s| s.chomp }
    unless answer == 'true'
      session[:recaptcha_error] = error
      if model = options[:model]
        model.valid?
        model.errors.add_to_base "Captcha response is incorrect, please try again."
      end
      return false
    else
      session[:recaptcha_error] = nil
      return true
    end
  rescue Exception => e
    raise ReCaptchaError, e
  end
end