如何使用rails验证reCAPTCHA?

时间:2015-01-10 14:56:53

标签: ruby-on-rails ruby validation ruby-on-rails-4 recaptcha

我已经看过一些关于如何使用PHP重新使用recaptcha的指南,但没有使用Rails。这是我到目前为止的代码:

<script src='https://www.google.com/recaptcha/api.js'></script>

<%= form_for @user, :url => users_path, :html => { :multipart => true } do |f| %>
  <%= f.text_field :name %>
  <div class="g-recaptcha" data-sitekey="..."></div>
  <%= f.submit "Submit" %>
<% end %>

users_controller.rb

class UsersController < ApplicationController

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to users_success_path
    else
      flash[:notice] = "Failed"
      redirect_to new_user_path
    end
  end

如何验证响应是真还是假?谷歌关于这个主题的文档非常令人困惑。

4 个答案:

答案 0 :(得分:3)

我会看一下recaptcha宝石。看起来他们已经接近支持新的API了。

答案 1 :(得分:2)

这是一个非常简单的基本脚本。我不知道你是否期待这样的事情。你可以从中获得这个概念,并在此基础上进行构建以适应你的用例。

require 'uri'
require 'net/http'

uri = URI("http://www.google.com/recaptcha/api/verify")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true

verify_request = Net::HTTP::Post.new(uri.path)

verify_request["secret"]        = your_private_key
verify_request["remoteip"]  = request.remote_ip, #ip address of the user
verify_request["challenge"] = params[:recaptcha_challenge_field], #recaptcha challenge field value
verify_request["response"]  = params[:recaptcha_response_field] # recaptcha response field value

response = https.request(request)
puts response

#the response will be json and you could parse it check whether the captcha is correct or not.

答案 2 :(得分:1)

您应该能够使用HTTParty。

# Gemfile
gem 'httparty'

bundle

# app/models/recaptcha_verifier.rb
class RecaptchaVerifier
  def initialize(response, ip)
    @response = response
    @ip = ip
  end

  def self.verify(response, ip = nil)
    new(response, ip).verify
  end

  def verify
    recaptcha_response = HTTParty.get(recaptcha_url(@response, secret, @ip))
    response_success?(recaptcha_response)
  end

  private
  def recaptcha_url(response, secret, ip)
    "https://www.google.com/recaptcha/api/siteverify?secret=#{secret}&response=#{response}&remoteip=#{ip}"
  end

  def secret
    # load your secret here or hardcode it
  end

  def response_success?(response)
    response.fetch('success')
  end
end

您可以在控制器或模型中使用它,如下所示:

class SomeController
  def some_action
    if RecaptchaVerifier.verify(params[:user][:g-recaptcha-response])
      # proceed
    else
      # output some flash warning and render same action or redirect_to :back
    end
  end
end

答案 3 :(得分:0)

由于接受的答案有些过时,我将在此处添加代码:

def verify_recaptcha(request, params) #returns true if verification succeeded
    require 'net/http'
    uri = URI("https://www.google.com/recaptcha/api/siteverify")
    https = Net::HTTP.new(uri.host, uri.port)
    https.use_ssl = true
    verify_request = Net::HTTP::Post.new(uri.path)
    verify_request.set_form_data( 'secret'=> __your_secret_key_goes_here__,
                                  'response' => params['g-recaptcha-response'] )

    googleanswer = https.request(verify_request)
    resultingjson = JSON.parse( googleanswer.body )
    return resultingjson['success']
end

这使用的是Ruby 2.3.1和Rails 5.0.2。