Module: Recaptcha::Verify

Defined in:
lib/recaptcha/verify.rb

Constant Summary collapse

G_RESPONSE_LIMIT =
4000

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.skip?(env) ⇒ Boolean

Returns:

  • (Boolean)

60
61
62
63
# File 'lib/recaptcha/verify.rb', line 60

def self.skip?(env)
  env ||= ENV['RAILS_ENV'] || ENV['RACK_ENV'] || (Rails.env if defined? Rails.env)
  Recaptcha.configuration.skip_verify_env.include? env
end

Instance Method Details

#verify_recaptcha(options = {}) ⇒ Object

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


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
# File 'lib/recaptcha/verify.rb', line 10

def verify_recaptcha(options = {})
  options = {model: options} unless options.is_a? Hash
  return true if Recaptcha::Verify.skip?(options[:env])

  model = options[:model]
  attribute = options[:attribute] || :base
  recaptcha_response = options[:response] || params['g-recaptcha-response'].to_s

  begin
    verified = if recaptcha_response.empty? || recaptcha_response.length > G_RESPONSE_LIMIT
      false
    else
      recaptcha_verify_via_api_call(request, recaptcha_response, options)
    end

    if verified
      flash.delete(:recaptcha_error) if recaptcha_flash_supported? && !model
      true
    else
      recaptcha_error(
        model,
        attribute,
        options[:message],
        "recaptcha.errors.verification_failed",
        "reCAPTCHA verification failed, please try again."
      )
      false
    end
  rescue Timeout::Error
    if Recaptcha.configuration.handle_timeouts_gracefully
      recaptcha_error(
        model,
        attribute,
        options[:message],
        "recaptcha.errors.recaptcha_unreachable",
        "Oops, we failed to validate your reCAPTCHA response. Please try again."
      )
      false
    else
      raise RecaptchaError, "Recaptcha unreachable."
    end
  rescue StandardError => e
    raise RecaptchaError, e.message, e.backtrace
  end
end

#verify_recaptcha!(options = {}) ⇒ Object


56
57
58
# File 'lib/recaptcha/verify.rb', line 56

def verify_recaptcha!(options = {})
  verify_recaptcha(options) || raise(VerifyError)
end