Skip to content

Commit

Permalink
Clear up reset password token whenever encrypted password changes
Browse files Browse the repository at this point in the history
  • Loading branch information
José Valim committed May 26, 2015
1 parent b149951 commit 31901bc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
21 changes: 6 additions & 15 deletions lib/devise/models/recoverable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,18 @@ def self.required_fields(klass)
[:reset_password_sent_at, :reset_password_token]
end

included do
before_update :clear_reset_password_token, if: :encrypted_password_changed?
end

# Update password saving the record and clearing token. Returns true if
# the passwords are valid and the record was saved, false otherwise.
def reset_password(new_password, new_password_confirmation)
self.password = new_password
self.password_confirmation = new_password_confirmation

if valid?
clear_reset_password_token
if respond_to?(:after_password_reset) && valid?
ActiveSupport::Deprecation.warn "after_password_reset is deprecated"
after_password_reset
end

Expand Down Expand Up @@ -90,19 +94,6 @@ def clear_reset_password_token
self.reset_password_sent_at = nil
end

# A callback initiated after password is successfully reset. This can
# be used to insert your own logic that is only run after the user
# successfully resets their password.
#
# Example:
#
# def after_password_reset
# self.update_attribute(:invite_code, nil)
# end
#
def after_password_reset
end

def set_reset_password_token
raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)

Expand Down
12 changes: 12 additions & 0 deletions test/models/recoverable_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ def setup
assert_nil user.reset_password_token
end

test 'should clear reset password token if changing password' do
user = create_user
assert_nil user.reset_password_token

user.send_reset_password_instructions
assert_present user.reset_password_token
user.password = "123456678"
user.password_confirmation = "123456678"
user.save!
assert_nil user.reset_password_token
end

test 'should not clear reset password token if record is invalid' do
user = create_user
user.send_reset_password_instructions
Expand Down

0 comments on commit 31901bc

Please sign in to comment.