Class: ActiveModel::SecurePassword::InstanceMethodsOnActivation

Inherits:
Module
  • Object
show all
Defined in:
lib/active_model/secure_password.rb

Instance Method Summary collapse

Constructor Details

#initialize(attribute, reset_token:) ⇒ InstanceMethodsOnActivation

Returns a new instance of InstanceMethodsOnActivation.



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/active_model/secure_password.rb', line 183

def initialize(attribute, reset_token:)
  attr_reader attribute

  define_method("#{attribute}=") do |unencrypted_password|
    if unencrypted_password.nil?
      instance_variable_set("@#{attribute}", nil)
      self.public_send("#{attribute}_digest=", nil)
    elsif !unencrypted_password.empty?
      instance_variable_set("@#{attribute}", unencrypted_password)
      cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
      self.public_send("#{attribute}_digest=", BCrypt::Password.create(unencrypted_password, cost: cost))
    end
  end

  attr_accessor :"#{attribute}_confirmation", :"#{attribute}_challenge"

  # Returns +self+ if the password is correct, otherwise +false+.
  #
  #   class User < ActiveRecord::Base
  #     has_secure_password validations: false
  #   end
  #
  #   user = User.new(name: 'david', password: 'mUc3m00RsqyRe')
  #   user.save
  #   user.authenticate_password('notright')      # => false
  #   user.authenticate_password('mUc3m00RsqyRe') # => user
  define_method("authenticate_#{attribute}") do |unencrypted_password|
    attribute_digest = public_send("#{attribute}_digest")
    attribute_digest.present? && BCrypt::Password.new(attribute_digest).is_password?(unencrypted_password) && self
  end

  # Returns the salt, a small chunk of random data added to the password before it's hashed.
  define_method("#{attribute}_salt") do
    attribute_digest = public_send("#{attribute}_digest")
    attribute_digest.present? ? BCrypt::Password.new(attribute_digest).salt : nil
  end

  alias_method :authenticate, :authenticate_password if attribute == :password

  if reset_token
    # Returns the class-level configured reset token for the password.
    define_method("#{attribute}_reset_token") do
      generate_token_for(:"#{attribute}_reset")
    end
  end
end