Class: ReCaptcha::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/recaptcha.rb

Instance Method Summary collapse

Constructor Details

#initialize(pubkey, privkey, ssl = false) ⇒ Client

Returns a new instance of Client.



85
86
87
88
89
90
91
92
93
# File 'lib/recaptcha.rb', line 85

def initialize(pubkey, privkey, ssl=false)
  @pubkey = pubkey
  @privkey=privkey
  @host = ssl ? 'api-secure.recaptcha.net':'api.recaptcha.net'
  @vhost = 'api-verify.recaptcha.net'
  @proto = ssl ? 'https' : 'http'
  @ssl = ssl
  @last_error=nil
end

Instance Method Details

#get_challenge(error = '', options = {}) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/recaptcha.rb', line 95

def get_challenge(error='', options={})
  s=''
  if options[:options]
    s << "<script type=\"text/javascript\">\nvar RecaptchaOptions = { "
    options[:options].each do |k,v|
      val = (v.class == Fixnum) ? "#{v}" : "\"#{v}\""
      s << "#{k} : #{val}, "
    end
    s.sub!(/, $/, '};')
    s << "\n</script>\n"
  end
  errslug = (error.empty?||error==nil||error=="success") ? '' :  "&error=#{CGI.escape(error)}"
  s <<<<-EOF
  <script type="text/javascript" src="#{@proto}://#{@host}/challenge?k=#{CGI.escape(@pubkey)}#{errslug}"> </script>
  <noscript>
  <iframe src="#{@proto}://#{@host}/noscript?k=#{CGI.escape(@pubkey)}#{errslug}"
  height="300" width="500" frameborder="0"></iframe><br>
  <textarea name="recaptcha_challenge_field" rows="3" cols="40">
  </textarea>
  <input type="hidden" name="recaptcha_response_field" 
  value="manual_challenge">
  </noscript>
  EOF
end

#last_errorObject



120
121
122
# File 'lib/recaptcha.rb', line 120

def last_error
  @last_error
end

#validate(remoteip, challenge, response, errors) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/recaptcha.rb', line 123

def validate(remoteip, challenge, response, errors)
  msg = "Captcha failed."
  unless response and challenge
    errors.add_to_base(msg)
    return false
  end
  proxy_host, proxy_port = nil, nil
  proxy_host, proxy_port = ENV['proxy_host'].split(':')  if ENV.has_key?('proxy_host')
  http = Net::HTTP::Proxy(proxy_host, proxy_port).start(@vhost)
  path='/verify'
  data = "privatekey=#{CGI.escape(@privkey)}&remoteip=#{CGI.escape(remoteip)}&challenge=#{CGI.escape(challenge)}&response=#{CGI.escape(response)}"
  resp, data = http.post(path, data, {'Content-Type'=>'application/x-www-form-urlencoded'})
  response = data.split
  result = response[0].chomp
  @last_error=response[1].chomp
  errors.add_to_base(msg) if  result != 'true'
  result == 'true' 
end