什么是Sinatra的验证码?

时间:2014-01-21 15:25:28

标签: sinatra captcha recaptcha

您在Sinatra应用程序中使用的验证码是什么?

我喜欢谷歌的http://www.google.com/recaptcha,但似乎不适用于Sinatra(但是有一个Rails的插件)。谷歌搜索后,https://github.com/jpoz/sinatra-recaptchahttps://github.com/bmizerany/sinatra-captcha等插件似乎总是有5年......

谢谢!

1 个答案:

答案 0 :(得分:6)

在没有任何插件的情况下使用reCaptcha并不难。请参阅here for how to display reCaptcha without pluginshere for how to verify the user's answer。 API非常简单。当用户解决验证码时,将提交两个参数:recaptcha_challenge_fieldrecaptcha_response_field。您可以使用它们从服务器调用验证API并检查解决方案是否正常。例如:

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