Skip to content

Instantly share code, notes, and snippets.

@mirhampt
Created October 5, 2010 00:40
Show Gist options
  • Save mirhampt/610737 to your computer and use it in GitHub Desktop.
Save mirhampt/610737 to your computer and use it in GitHub Desktop.
Verify a recaptcha using CoffeeScript and node.js. This is not bulletproof, but it is a start.
# Send a request to recaptcha to verify the user's input.
#
# The first argument must be an object containing four parts:
# privatekey: Your recaptcha private key.
# remoteip: The IP of the user who submitted the form.
# challenge: The challenge value from the recaptcha form.
# response: The user's response to the captcha.
#
# Example usage (express):
#
# recaptcha = require 'recaptcha'
#
# app.post '/comments', (req, res) ->
# data =
# privatekey: YOUR_PRIVATE_KEY
# remoteip: req.connection.remoteAddress
# challenge: req.body.recaptcha_challenge_field
# response: req.body.recaptcha_response_field
#
# recaptcha.verify_captcha data, (success, error_code) ->
# if success
# # Passed captcha.
# else
# # Did not pass captcha.
http = require 'http'
querystring = require 'querystring'
API_HOST = 'www.google.com'
API_END_POINT = '/recaptcha/api/verify'
exports.verify_captcha = (data, callback) ->
data = querystring.stringify data
recaptcha = http.createClient 80, API_HOST
request = recaptcha.request 'POST', API_END_POINT,
host: API_HOST
'Content-Length': data.length
'Content-Type': 'application/x-www-form-urlencoded'
request.on 'response', (response) ->
body = ''
response.on 'data', (chunk) ->
body += chunk
response.on 'end', () ->
[success, error_code] = body.split '\n'
callback(success == 'true', error_code)
request.write data.toString(), 'utf8'
request.end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment