From eeb5b268ee10db3f0251bb2f5bcd1ba26287604b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Inge=20J=C3=B8rgensen?= Date: Fri, 2 Feb 2024 14:30:04 +0100 Subject: [PATCH] Update persistence token before validations --- app/models/concerns/authenticable.rb | 14 +++++++++++--- spec/models/concerns/authenticable_spec.rb | 3 +-- 2 files changed, 12 insertions(+), 5 deletions(-) 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) }