Skip to content

Instantly share code, notes, and snippets.

@s01ipsist
Created August 20, 2019 10:24
Show Gist options
  • Save s01ipsist/7f8bbe0df1131224b361d56901c08f91 to your computer and use it in GitHub Desktop.
Save s01ipsist/7f8bbe0df1131224b361d56901c08f91 to your computer and use it in GitHub Desktop.
GoogleRecaptcha Ruby
# https://developers.google.com/recaptcha/docs/verify
# app/controllers/application_controller.rb
def recaptcha_valid?
recaptcha_response = params['g-recaptcha-response']
return false unless recaptcha_response
GoogleRecaptcha.new.verify_recaptcha(response: recaptcha_response, remoteip: request.remote_ip)
rescue
false
end
# lib/google_recaptcha.rb
class GoogleRecaptcha
BASE_URL = "https://www.google.com/".freeze
VERIFY_URL = "recaptcha/api/siteverify".freeze
def initialize
@client = Faraday.new(BASE_URL)
end
def verify_recaptcha(params)
response = perform_verify_request(params)
success?(response)
end
def success?(response)
JSON.parse(response.body)["success"]
end
private
attr_reader :client
def perform_verify_request(params)
client.post(VERIFY_URL) do |req|
req.params = params.merge(secret: ENV['RECAPTCHA_SECRET_KEY'])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment