Module: Nlpcaptcha::Verify

Defined in:
lib/nlpcaptcha/verify.rb

Instance Method Summary collapse

Instance Method Details

#NLPValidate(options = {}) ⇒ Object

Your private API can be specified in the options hash or preferably using the Configuration.

Raises:



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/nlpcaptcha/verify.rb', line 6

def NLPValidate(options = {})
  if !options.is_a? Hash
    options = {:model => options}
  end

  env = options[:env] || ENV['RAILS_ENV']
  return true if Nlpcaptcha.configuration.skip_verify_env.include? env
  model = options[:model]
  attribute = options[:attribute] || :base
  validator_key = options[:validator_key] || Nlpcaptcha.configuration.validator_key
  raise NlpcaptchaError, "No Validator key specified." unless validator_key

  begin
    nlpcaptcha = nil
    if(Nlpcaptcha.configuration.proxy)
      proxy_server = URI.parse(Nlpcaptcha.configuration.proxy)
      http = Net::HTTP::Proxy(proxy_server.host, proxy_server.port, proxy_server.user, proxy_server.password)
    else
      http = Net::HTTP
    end

    Timeout::timeout(options[:timeout] || 3) do
      nlpcaptcha = http.post_form(URI.parse(Nlpcaptcha.configuration.validate_url), {
        "ValidateKey" => validator_key,
        "Identifier"  => params[:nlpIdentifier],
        "Answer"   => params[:nlpAnswer]
      })
    end
    answer, error = nlpcaptcha.body.split(":@NLP@:").map { |s| s.chomp }
    unless answer == 'success'
      flash[:nlpcaptcha_error] = error
      if model
        message = "Your Response Could not be Validated"
        message = I18n.translate(:'nlpcaptcha.errors.validation_failed', {:default => message}) if defined?(I18n)
        model.errors.add attribute, options[:message] || message
      end
      return false
    else
      flash[:nlpcaptcha_error] = nil
      return true
    end
  rescue Timeout::Error
    flash[:nlpcaptcha_error] = "nlpcaptcha-not-reachable"
    if model
      message = "An error occured while connecting to the captcha validation service. Please try again."
      message = I18n.translate(:'nlpcaptcha.errors.sever_unreachable', :default => message) if defined?(I18n)
      model.errors.add attribute, options[:message] || message
    end
    return false
  rescue Exception => e
    raise NlpcaptchaError, e.message, e.backtrace
  end
end