Class: Incline::RecaptchaValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/incline/validators/recaptcha_validator.rb

Overview

Validates a reCAPTCHA attribute.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validates a reCAPTCHA attribute.

The value of the attribute should be a hash with two keys: :response, :remote_ip



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/incline/validators/recaptcha_validator.rb', line 11

def validate_each(record, attribute, value)
  # Do NOT raise an error if nil.
  return if value.blank?

  # Make sure the response only gets processed once.
  return if value == :verified

  # Automatically skip validation if paused.
  return if Incline::Recaptcha::paused?

  # If the user form includes the recaptcha field, then something will come in
  # and then we want to check it.
  remote_ip, _, response = value.partition('|')
  if remote_ip.blank? || response.blank?
    record.errors[:base] << (options[:message] || 'Requires reCAPTCHA challenge to be completed')
  else
    if Incline::Recaptcha::verify(response: response, remote_ip: remote_ip)
      record.send "#{attribute}=", :verified
    else
      record.errors[:base] << (options[:message] || 'Invalid response from reCAPTCHA challenge')
    end
  end

end