aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib
diff options
context:
space:
mode:
authorGodfrey Chan <godfreykfc@gmail.com>2014-01-24 20:35:48 -0800
committerGodfrey Chan <godfreykfc@gmail.com>2014-01-24 20:35:48 -0800
commit94ce51445eb70fb168640c0404b7fc1985365f67 (patch)
treedd7244b4b9131ba47a39f663e5396aad262f4e2f /activemodel/lib
parent7776fd6afb4463f8e7c39e653bdc2ee9226b22f4 (diff)
parent98705d88cd8ec705b80a032f8c166072b4e6fffd (diff)
downloadrails-94ce51445eb70fb168640c0404b7fc1985365f67.tar.gz
rails-94ce51445eb70fb168640c0404b7fc1985365f67.tar.bz2
rails-94ce51445eb70fb168640c0404b7fc1985365f67.zip
Merge pull request #13772 from chancancode/fix_has_secure_password_for_good
Refactored validations rules for has_secure_password
Diffstat (limited to 'activemodel/lib')
-rw-r--r--activemodel/lib/active_model/secure_password.rb22
1 files changed, 11 insertions, 11 deletions
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
index d824a66784..01739d8ae4 100644
--- a/activemodel/lib/active_model/secure_password.rb
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -57,11 +57,15 @@ module ActiveModel
include InstanceMethodsOnActivation
if options.fetch(:validations, true)
- validates_confirmation_of :password, if: :password_confirmation_required?
- validates_presence_of :password, on: :create
- validates_presence_of :password_confirmation, if: :password_confirmation_required?
+ # This ensures the model has a password by checking whether the password_digest
+ # is present, so that this works with both new and existing records. However,
+ # when there is an error, the message is added to the password attribute instead
+ # so that the error message will make sense to the end-user.
+ validate do |record|
+ record.errors.add(:password, :blank) unless record.password_digest.present?
+ end
- before_create { raise "Password digest missing on new record" if password_digest.blank? }
+ validates_confirmation_of :password, if: ->{ password.present? }
end
if respond_to?(:attributes_protected_by_default)
@@ -100,7 +104,9 @@ module ActiveModel
# user.password = 'mUc3m00RsqyRe'
# user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."
def password=(unencrypted_password)
- unless unencrypted_password.blank?
+ if unencrypted_password.nil?
+ self.password_digest = nil
+ elsif unencrypted_password.present?
@password = unencrypted_password
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)
@@ -110,12 +116,6 @@ module ActiveModel
def password_confirmation=(unencrypted_password)
@password_confirmation = unencrypted_password
end
-
- private
-
- def password_confirmation_required?
- password_confirmation && password.present?
- end
end
end
end