diff --git a/app/models/concerns/authenticable.rb b/app/models/concerns/authenticable.rb index eb331447..99cd2850 100644 --- a/app/models/concerns/authenticable.rb +++ b/app/models/concerns/authenticable.rb @@ -24,13 +24,21 @@ module Authenticable } ) - before_save :update_persistence_token + after_initialize do |u| + u.persistence_token ||= u.class.random_persistence_token + end + + before_validation :update_persistence_token end module ClassMethods def find_and_authenticate_with_password(email, password) User.find_by(email:).try(:authenticate, password) end + + def random_persistence_token + SecureRandom.hex(32) + end end def deactivated? @@ -69,8 +77,8 @@ def verify_banned_until end def update_persistence_token - return unless !persistence_token || password_digest_changed? + return unless password_digest_changed? - self.persistence_token = SecureRandom.hex(32) + self.persistence_token = self.class.random_persistence_token end end diff --git a/spec/models/concerns/authenticable_spec.rb b/spec/models/concerns/authenticable_spec.rb index 6c161912..fe8c3e9c 100644 --- a/spec/models/concerns/authenticable_spec.rb +++ b/spec/models/concerns/authenticable_spec.rb @@ -141,8 +141,7 @@ context "when password is changed" do before do - user.password = user.password_confirmation = "new password" - user.save + user.update(password: "new password") end it { is_expected.not_to eq(previous_token) }