Module: RuCaptchaNumber::ControllerHelpers

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

Instance Method Summary collapse

Instance Method Details

#generate_rucaptchaObject

Generate a new Captcha



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rucaptcha_number/controller_helpers.rb', line 17

def generate_rucaptcha
  res = RuCaptchaNumber.generate()
  session_val = {
    code: res[0],
    time: Time.now.to_i
  }
  filename = rucaptcha_filename
  RuCaptchaNumber.cache.write(filename, session_val, expires_in: RuCaptchaNumber.config.expires_in)

  res[1]
end

#rucaptcha_filenameObject

filename key of rucaptcha



10
11
12
13
14
# File 'lib/rucaptcha_number/controller_helpers.rb', line 10

def rucaptcha_filename
  filename =  params[:filename]
  filename_digest = Digest::SHA256.hexdigest(filename.inspect)
  ['rucaptcha-session', filename_digest].join(':')
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, RuCaptchaNumber will not delete the captcha code session.

exmaples:

verify_rucaptcha?
verify_rucaptcha?(user, keep_session: true)
verify_rucaptcha?(nil, keep_session: true)

Returns:

  • (Boolean)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rucaptcha_number/controller_helpers.rb', line 41

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


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

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

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

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

  if captcha != store_info[:code]
    return add_rucaptcha_validation_error
  end

  true
end