Module: RuCaptcha::ControllerHelpers

Extended by:
ActiveSupport::Concern
Defined in:
lib/rucaptcha/controller_helpers.rb

Instance Method Summary collapse

Instance Method Details

#generate_rucaptchaObject

Generate a new Captcha



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rucaptcha/controller_helpers.rb', line 24

def generate_rucaptcha
  generate_rucaptcha_session_id

  res = RuCaptcha.generate
  session_val = {
    code: res[0],
    time: Time.now.to_i
  }
  RuCaptcha.cache.write(rucaptcha_sesion_key_key, session_val, expires_in: RuCaptcha.config.expires_in)
  res[1]
end

#rucaptcha_sesion_key_keyObject

session key of rucaptcha



14
15
16
17
18
19
20
21
# File 'lib/rucaptcha/controller_helpers.rb', line 14

def rucaptcha_sesion_key_key
  warning_when_session_invalid if rucaptcha_session_id.blank?

  # With https://github.com/rack/rack/commit/7fecaee81f59926b6e1913511c90650e76673b38
  # to protected session_id into secret
  session_id_digest = Digest::SHA256.hexdigest(rucaptcha_session_id.inspect)
  ["rucaptcha-session", session_id_digest].join(":")
end

#rucaptcha_session_idObject



9
10
11
# File 'lib/rucaptcha/controller_helpers.rb', line 9

def rucaptcha_session_id
  cookies[:_rucaptcha_session_id]
end

#verify_rucaptcha?(_resource = nil, opts = {}) ⇒ Boolean

Verify captcha code

params: resource - [optional] a ActiveModel object, if given will add validation error message to object. :keep_session - if true, RuCaptcha will not delete the captcha code session. :captcha - if given, the value of it will be used to verify the captcha,

if do not give or blank, the value of params[:_rucaptcha] will be used to verify the captcha

exmaples:

verify_rucaptcha?
verify_rucaptcha?(user, keep_session: true)
verify_rucaptcha?(nil, keep_session: true)
verify_rucaptcha?(nil, captcha: params[:user][:captcha])


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/rucaptcha/controller_helpers.rb', line 51

def verify_rucaptcha?(_resource = nil, opts = {})
  opts ||= {}

  store_info = RuCaptcha.cache.read(rucaptcha_sesion_key_key)
  # make sure move used key
  RuCaptcha.cache.delete(rucaptcha_sesion_key_key) unless opts[:keep_session]

  # Make sure session exist
  return add_rucaptcha_validation_error if store_info.blank?

  # Make sure not expire
  return add_rucaptcha_validation_error if (Time.now.to_i - store_info[:time]) > RuCaptcha.config.expires_in

  # Make sure parama have captcha
  captcha = (opts[:captcha] || params[:_rucaptcha] || "").downcase.strip
  return add_rucaptcha_validation_error if captcha.blank?

  return add_rucaptcha_validation_error if captcha != store_info[:code]

  true
end