Class: Rack::Captchachacha

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/captchachacha.rb,
lib/rack/captchachacha/helpers.rb,
lib/rack/captchachacha/version.rb

Defined Under Namespace

Modules: Helpers

Constant Summary collapse

VERIFY_URL =
"http://captchator.com/captcha/check_answer"
CHALLENGE_FIELD =
'captcha_session'
RESPONSE_FIELD =
'captcha'
DEFAULT_MESSAGE =
"Incorrect response, please try again."
RESULT_HEADER =
'X-Captcha-Valid'
RESULT_MESSAGE =
'X-Captcha-Msg'
VERSION =
"0.4.2"

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Captchachacha

Returns a new instance of Captchachacha.

Parameters:

  • app

    Rack application

  • options (optional, Hash) (defaults to: {})

    Hash of options

Options Hash (options):

  • paths (String, Array<String>)

    Where user goes to login or access the captcha.



19
20
21
22
23
24
# File 'lib/rack/captchachacha.rb', line 19

def initialize( app, options={} )
  @app = app
  
  # this is here because it's in the Rack::Recaptcha API, I've no idea what it does really.
  @paths = options[:paths] && [options[:paths]].flatten.compact
end

Instance Method Details

#_call(env) ⇒ Object

Parameters:

  • env

    Rack environment



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rack/captchachacha.rb', line 31

def _call(env)
  request = Request.new(env)
  if request.params[CHALLENGE_FIELD] && request.params[RESPONSE_FIELD]
 
    result, msg = verify(
                    request.params[CHALLENGE_FIELD].to_i, 
                    request.params[RESPONSE_FIELD] )
                    
    # captchator doesn't give an error message, but in the spirit of keeping a similar API
    # to reCAPTCHA, and because it's an easy place to stick a default error message, I'll
    # pretend that `verify` returns two results.
    # If it's a fail then the usual course of action would be to redirect back to the
    # captcha form, but on success to continue, so the error message will be ignored unless
    # of failure.
    msg ||= DEFAULT_MESSAGE
    
    env.merge!(RESULT_HEADER => result == true, RESULT_MESSAGE => msg )
  end
  
  @app.call(env)
end

#call(env) ⇒ Object



26
27
28
# File 'lib/rack/captchachacha.rb', line 26

def call(env)
  dup._call env
end

#verify(session_id, answer) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/rack/captchachacha.rb', line 54

def verify( session_id, answer )
  return false if session_id == 0 || session_id.nil?
  return false if answer.nil?

  require 'curb'
  Curl::Easy.perform("#{VERIFY_URL}/#{session_id}/#{answer}").body_str == "1"
end