Module: ActiveModel::OneTimePassword::ClassMethods

Defined in:
lib/active_model/one_time_password.rb

Instance Method Summary collapse

Instance Method Details

#has_one_time_password(options = {}) ⇒ Object



6
7
8
9
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
# File 'lib/active_model/one_time_password.rb', line 6

def has_one_time_password(options = {})
  cattr_accessor :otp_column_name, :otp_counter_column_name,
                 :otp_backup_codes_column_name
  class_attribute :otp_digits, :otp_counter_based,
                  :otp_backup_codes_count, :otp_one_time_backup_codes

  self.otp_column_name = (options[:column_name] || "otp_secret_key").to_s
  self.otp_digits = options[:length] || 6

  self.otp_counter_based = (options[:counter_based] || false)
  self.otp_counter_column_name = (options[:counter_column_name] || "otp_counter").to_s

  self.otp_backup_codes_column_name = (
    options[:backup_codes_column_name] || 'otp_backup_codes'
  ).to_s
  self.otp_backup_codes_count = options[:backup_codes_count] || 12
  self.otp_one_time_backup_codes = (
    options[:one_time_backup_codes] || false
  )

  include InstanceMethodsOnActivation

  before_create(**options.slice(:if, :unless)) do
    self.otp_regenerate_secret if !otp_column
    self.otp_regenerate_counter if otp_counter_based && !otp_counter
    otp_regenerate_backup_codes if backup_codes_enabled?
  end

  if respond_to?(:attributes_protected_by_default)
    def self.attributes_protected_by_default #:nodoc:
      super + [otp_column_name, otp_counter_column_name]
    end
  end
end

#otp_random_secret(length = 20) ⇒ Object

Defaults to 160 bit long secret (meaning a 32 character long base32 secret)



43
44
45
# File 'lib/active_model/one_time_password.rb', line 43

def otp_random_secret(length = 20)
  ROTP::Base32.random(length)
end