123456789_123456789_123456789_123456789_123456789_

Class: ActiveModel::SecurePassword::BCryptPassword

Relationships & Source Files
Inherits: Object
Defined in: activemodel/lib/active_model/secure_password/bcrypt_password.rb

Constant Summary

Class Method Summary

Instance Method Summary

Constructor Details

.newBCryptPassword

This method is for internal use only.
[ GitHub ]

  
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 11

def initialize
  # Load bcrypt gem only when has_secure_password is used.
  # This is to avoid Active Model (and by extension the entire framework)
  # being dependent on a binary library.
  require "bcrypt"
rescue LoadError
  warn "You don't have bcrypt installed in your application. Please add it to your Gemfile and run bundle install."
  raise
end

Instance Method Details

#algorithm_name

Returns the algorithm name.

[ GitHub ]

  
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 46

def algorithm_name
  :bcrypt
end

#cost (private)

[ GitHub ]

  
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 51

def cost
  ActiveModel::SecurePassword.min_cost ? ::BCrypt::Engine::MIN_COST : ::BCrypt::Engine.cost
end

#hash_password(unencrypted_password)

Hashes the unencrypted password using BCrypt.

[ GitHub ]

  
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 22

def hash_password(unencrypted_password)
  ::BCrypt::Password.create(unencrypted_password, cost: cost)
end

#password_salt(digest)

Generates the salt from the password digest.

[ GitHub ]

  
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 32

def password_salt(digest)
  ::BCrypt::Password.new(digest).salt
end

#validate(record, attribute)

Validates the password and adds error to the record in the given attribute. BCrypt has a maximum input size, so we need to validate it.

[ GitHub ]

  
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 38

def validate(record, attribute)
  password = record.public_send(attribute)
  if password.present?
    record.errors.add(attribute, :password_too_long) if password.bytesize > MAX_PASSWORD_LENGTH_ALLOWED
  end
end

#verify_password(password, digest)

Verifies if the password matches the digest.

[ GitHub ]

  
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 27

def verify_password(password, digest)
  ::BCrypt::Password.new(digest).is_password?(password)
end