Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What captcha for Sinatra?

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!

like image 705
Zag zag.. Avatar asked May 01 '26 02:05

Zag zag..


1 Answers

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
like image 156
Patrick Oscity Avatar answered May 03 '26 01:05

Patrick Oscity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!