Module: InvisibleCaptcha::ControllerExt

Defined in:
lib/invisible_captcha/controller_ext.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#default_on_spamObject



35
36
37
# File 'lib/invisible_captcha/controller_ext.rb', line 35

def default_on_spam
  head(200)
end

#detect_spam(options = {}) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/invisible_captcha/controller_ext.rb', line 11

def detect_spam(options = {})
  if invisible_captcha_timestamp?(options)
    on_timestamp_spam_action(options)
  elsif invisible_captcha?(options)
    on_spam_action(options)
  end
end

#invisible_captcha?(options = {}) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/invisible_captcha/controller_ext.rb', line 58

def invisible_captcha?(options = {})
  honeypot = options[:honeypot]
  scope    = options[:scope] || controller_name.singularize

  if honeypot
    # If honeypot is presented, search for:
    # - honeypot: params[:subtitle]
    # - honeypot with scope: params[:topic][:subtitle]
    if params[honeypot].present? || (params[scope] && params[scope][honeypot].present?)
      return true
    end
  else
    InvisibleCaptcha.honeypots.each do |field|
      return true if params[field].present?
    end
  end
  false
end

#invisible_captcha_timestamp?(options = {}) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/invisible_captcha/controller_ext.rb', line 39

def invisible_captcha_timestamp?(options = {})
  timestamp = session[:invisible_captcha_timestamp]

  # Consider as spam if timestamp not in session, cause that means the form was not fetched at all
  unless timestamp
    logger.warn("Potential spam detected for IP #{request.env['REMOTE_ADDR']}. Invisible Captcha timestamp not found in session.")
    return true
  end

  time_to_submit = Time.zone.now - DateTime.iso8601(timestamp)

  # Consider as spam if form submitted too quickly
  if time_to_submit < (options[:timestamp_threshold] || InvisibleCaptcha.timestamp_threshold)
    logger.warn("Potential spam detected for IP #{request.env['REMOTE_ADDR']}. Invisible Captcha timestamp threshold not reached (took #{time_to_submit.to_i}s).")
    return true
  end
  false
end

#on_spam_action(options = {}) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/invisible_captcha/controller_ext.rb', line 27

def on_spam_action(options = {})
  if action = options[:on_spam]
    send(action)
  else
    default_on_spam
  end
end

#on_timestamp_spam_action(options = {}) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/invisible_captcha/controller_ext.rb', line 19

def on_timestamp_spam_action(options = {})
  if action = options[:on_timestamp_spam]
    send(action)
  else
    redirect_to :back, flash: { error: InvisibleCaptcha.timestamp_error_message }
  end
end