Skip to content

Commit

Permalink
Update persistence token before validations
Browse files Browse the repository at this point in the history
  • Loading branch information
elektronaut committed Feb 2, 2024
1 parent 752f165 commit eeb5b26
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
14 changes: 11 additions & 3 deletions app/models/concerns/authenticable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -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
3 changes: 1 addition & 2 deletions spec/models/concerns/authenticable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down

0 comments on commit eeb5b26

Please sign in to comment.