Skip to content

Instantly share code, notes, and snippets.

@taylor
Forked from mikedamage/captcha.rb
Created May 17, 2012 05:50
Show Gist options
  • Save taylor/2716769 to your computer and use it in GitHub Desktop.
Save taylor/2716769 to your computer and use it in GitHub Desktop.
Wolfram CAPTCHA Sinatra App
require 'rubygems'
require 'sinatra'
require 'nokogiri'
require 'digest'
require 'net/http'
require 'cgi'
configure do
set :config, YAML.load_file(File.join(File.dirname(__FILE__), 'config.yml'))
set :api_key, settings.config['api_key']
set :api_base, "http://api.wolframalpha.com/v2/query"
set :captcha_length, 6
end
get '/' do
"hello world"
end
get '/captcha/:secret' do
# Calculate our CAPTCHA and request it from Wolfram's API. Then parse the response.
captcha = CGI::escape(Digest::MD5.hexdigest(params[:secret])[0, settings.captcha_length])
key = CGI::escape(settings.api_key)
url = URI.parse(settings.api_base + "?input=captcha+#{captcha}&appid=#{key}")
resp = Net::HTTP.get_response(url)
xml = Nokogiri::XML(resp.body)
# need to remove the other attributes, because it contains the plaintext as an alt attribute
@img = xml.search('pod#Result > subpod[primary="true"] > img').first.attr('src')
content_type 'text/html'
"<img src='#{@img}' />"
end
# vim: set ft=ruby sw=2 ts=2 :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment