Class: ActiveModel::SecurePassword::BCryptPassword
- Defined in:
- activemodel/lib/active_model/secure_password/bcrypt_password.rb
Constant Summary collapse
- MAX_PASSWORD_LENGTH_ALLOWED =
BCrypt hash function can handle maximum 72 bytes, and if we pass password of length more than 72 bytes it ignores extra characters. Hence need to put a restriction on password length.
72
Instance Method Summary collapse
-
#algorithm_name ⇒ Object
Returns the algorithm name.
-
#hash_password(unencrypted_password) ⇒ Object
Hashes the unencrypted password using BCrypt.
-
#initialize ⇒ BCryptPassword
constructor
:nodoc:.
-
#password_salt(digest) ⇒ Object
Generates the salt from the password digest.
-
#validate(record, attribute) ⇒ Object
Validates the password and adds error to the record in the given attribute.
-
#verify_password(password, digest) ⇒ Object
Verifies if the password matches the digest.
Constructor Details
#initialize ⇒ BCryptPassword
:nodoc:
11 12 13 14 15 16 17 18 19 |
# 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 ⇒ Object
Returns the algorithm name.
46 47 48 |
# File 'activemodel/lib/active_model/secure_password/bcrypt_password.rb', line 46 def algorithm_name :bcrypt end |
#hash_password(unencrypted_password) ⇒ Object
Hashes the unencrypted password using BCrypt.
22 23 24 |
# 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) ⇒ Object
Generates the salt from the password digest.
32 33 34 |
# 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) ⇒ Object
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.
38 39 40 41 42 43 |
# 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) ⇒ Object
Verifies if the password matches the digest.
27 28 29 |
# 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 |