Skip to content

Instantly share code, notes, and snippets.

@fcoury
Forked from peterc/gist:40234
Created May 1, 2009 04:44
Show Gist options
  • Save fcoury/104875 to your computer and use it in GitHub Desktop.
Save fcoury/104875 to your computer and use it in GitHub Desktop.
# NAME: recaptcha
# VERSION: 1.0
# AUTHOR: Peter Cooper [ http://www.rubyinside.com/ github:peterc twitter:peterc ]
# DESCRIPTION: Sinatra plugin to provide CAPTCHA support through recaptcha.net
# COMPATIBILITY: 0.3.2 /and/ latest rtomayko Hoboken builds!
# LICENSE: Use for what you want, just don't claim full credit unless you make significant changes
#
# INSTRUCTIONS:
# 0. Check out an extended client code example at the footer of this file
# 1. Ensure _this_ file is lib/recaptcha.rb within your app's directory structure
# 2. Set RECAPTCHA_PRIVATE and RECAPTCHA_PUBLIC with your Recaptcha.net-provided keys
# 3. Require from app with require 'lib/recaptcha'
# 4. Use show_captcha from a view to get a CAPTCHA for a form
# 5. In response method, use:
# captcha_valid?(params[:recaptcha_challenge_field], params[:recaptcha_response_field])
# to determine validity of response.
# 6. Act appropriately based on the results of step 5!
require 'net/http'
module Sinatra
module Plugins
module Recaptcha
RECAPTCHA_PRIVATE = "-- fill me in --"
RECAPTCHA_PUBLIC = "-- fill me in --"
RECAPTCHA_URL = "http://api-verify.recaptcha.net/verify"
def captcha_valid?(challenge, response, private_key = Sinatra::Plugins::Recaptcha::RECAPTCHA_PRIVATE)
begin
res = Net::HTTP.post_form(URI.parse(RECAPTCHA_URL), { :privatekey => private_key, :remoteip => request.env["REMOTE_ADDR"], :challenge => challenge, :response => response })
res.body.index("true") == 0
rescue
false
end
end
def show_captcha(public_key = Sinatra::Plugins::Recaptcha::RECAPTCHA_PUBLIC)
%{<script type="text/javascript"
src="http://api.recaptcha.net/challenge?k=#{public_key}">
</script>
<noscript>
<iframe src="http://api.recaptcha.net/noscript?k=#{public_key}"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>}
end
end
end
end
# Little hack to make it work with both Sinatra 0.3.2 and latest experimental builds
(Sinatra::Base rescue Sinatra::EventContext).send(:include, Sinatra::Plugins::Recaptcha)
# EXTENDED CLIENT CODE EXAMPLE
#
# get '/' do
# %{
# <form method="post" action="/submit">
# <input type="text" name="whatever" value="" />
# #{show_captcha}
# <input type="submit" />
# </form>
# }
# end
#
# post '/submit' do
# if captcha_valid?(params[:recaptcha_challenge_field], params[:recaptcha_response_field])
# "CAPTCHA passed"
# else
# redirect '/'
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment