Question

What captcha are you using in your Sinatra apps?

I like Google's http://www.google.com/recaptcha, but it seems not for Sinatra (there's a plugin for Rails however). And after googling, plugin such as https://github.com/jpoz/sinatra-recaptcha or https://github.com/bmizerany/sinatra-captcha seems to always have 5 years old...

Thanks!

Was it helpful?

Solution

Using reCaptcha without any plugin is not that hard. See here for how to display reCaptcha without plugins and here for how to verify the user's answer. The API is pretty straightforward. When the user solves the captcha, two parameters will be submitted: recaptcha_challenge_field and recaptcha_response_field. You can use these to call the verification API from the server and check if the solution is ok. For example:

require 'net/http'
require 'json'

post '/check_captcha' do
  res = Net::HTTP.post_form(
    URI.parse('http://www.google.com/recaptcha/api/verify'),
    {
      'privatekey' => 'Your private key',
      'remoteip'   => request.ip,
      'challenge'  => params[:recaptcha_challenge_field],
      'response'   => params[:recaptcha_response_field]
    }
  )

  success, error_key = res.body.lines.map(&:chomp)

  if success == 'true'
    # solved the captcha
  else
    # did not solve the captcha
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top