Module: ActiveRecord::ProtectedToken::ClassMethods

Defined in:
lib/has_protected_token.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#generate_token(length = 24) ⇒ Object

.generate_token

Class method to generate random tokens

Accepts an optional integer to specify the length of the returned token.



107
108
109
110
111
112
# File 'lib/has_protected_token.rb', line 107

def generate_token(length = 24)
  n = length.to_i
  SecureRandom.hex(n / 2) # hex returns n * 2
rescue NoMethodError
  raise ArgumentError, 'Token length must be an integer'
end

#has_protected_token(options = {}) ⇒ Object

TODO: something about the method length rubocop:disable Metrics/MethodLength



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/has_protected_token.rb', line 75

def has_protected_token(options = {})
  attribute = options[:column_name] || :token
  cost = options[:cost] || BCrypt::Engine::DEFAULT_COST

  define_method("regenerate_#{attribute}") do
    raw_token = self.class.generate_token

    update_column(attribute, hash_token(raw_token, cost))
    raw_token
  end

  define_method("#{attribute}=") do |raw_token|
    super(hash_token(raw_token, cost))
    raw_token
  end

  define_method("authenticate_#{attribute}") do |raw_token|
    begin
      BCrypt::Password.new(send(attribute)) == raw_token
    rescue BCrypt::Error
      false
    end
  end
end