From 619128cb9be73153dac0b66d84120c08e3d0504a Mon Sep 17 00:00:00 2001 From: Stan Hu Date: Fri, 2 Oct 2015 12:28:58 -0700 Subject: [PATCH 1/2] Only clear the reset password token if the model has already been persisted If a new user is created with a reset password token, the previous behavior would automatically clear the token even when it was desired for setting the password for the first time. --- lib/devise/models/recoverable.rb | 2 +- test/models/recoverable_test.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/devise/models/recoverable.rb b/lib/devise/models/recoverable.rb index f90279c3..51b7f0b1 100644 --- a/lib/devise/models/recoverable.rb +++ b/lib/devise/models/recoverable.rb @@ -32,7 +32,7 @@ module Devise included do before_save do - if email_changed? || encrypted_password_changed? + if persisted? && (email_changed? || encrypted_password_changed?) clear_reset_password_token end end diff --git a/test/models/recoverable_test.rb b/test/models/recoverable_test.rb index 8198698b..fc9ef949 100644 --- a/test/models/recoverable_test.rb +++ b/test/models/recoverable_test.rb @@ -42,6 +42,17 @@ class RecoverableTest < ActiveSupport::TestCase assert_nil user.reset_password_token end + test 'should not clear reset password token for new user' do + user = new_user + assert_nil user.reset_password_token + + user.send_reset_password_instructions + assert_present user.reset_password_token + + user.save + assert_present user.reset_password_token + end + test 'should clear reset password token if changing password' do user = create_user assert_nil user.reset_password_token From 56fed052f8a93fdbd9a53753ffb88ca7cad0e33e Mon Sep 17 00:00:00 2001 From: Stan Hu Date: Tue, 24 Nov 2015 23:23:34 -0800 Subject: [PATCH 2/2] Wrap logic for resetting token into instance method and add comments --- lib/devise/models/recoverable.rb | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/devise/models/recoverable.rb b/lib/devise/models/recoverable.rb index 51b7f0b1..8525b81d 100644 --- a/lib/devise/models/recoverable.rb +++ b/lib/devise/models/recoverable.rb @@ -31,10 +31,16 @@ module Devise end included do + def expire_reset_token? + # Expire the reset token only if the e-mail or password were changed + # since the last time the record was saved to the database. An admin + # may want to retain the token to give the newly-created user a chance + # to set the password for the first time. + persisted? && (email_changed? || encrypted_password_changed?) + end + before_save do - if persisted? && (email_changed? || encrypted_password_changed?) - clear_reset_password_token - end + clear_reset_password_token if expire_reset_token? end end