Class: OmniAuth::Identity::SecurePassword::InstanceMethodsOnActivation

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

Overview

A module that defines instance methods for password handling.
Methods are defined dynamically based on the attribute name.

Instance Method Summary collapse

Constructor Details

#initialize(attribute) ⇒ InstanceMethodsOnActivation

Initializes the module with the password attribute name.

Parameters:

  • attribute (Symbol, String)

    the password attribute name



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/omniauth/identity/secure_password.rb', line 158

def initialize(attribute)
  attr_reader(attribute)

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

  define_method(:"#{attribute}_confirmation=") do |unencrypted_password|
    instance_variable_set(:"@#{attribute}_confirmation", unencrypted_password)
  end

  # 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")
    BCrypt::Password.new(attribute_digest).is_password?(unencrypted_password) && self
  end

  alias_method(:authenticate, :authenticate_password) if attribute == :password
end