From 9bd186a0e8aa5e40719134466c9d4676c4098ce5 Mon Sep 17 00:00:00 2001 From: Markus Doits Date: Tue, 5 Oct 2021 15:58:05 +0200 Subject: [PATCH] clear secure password cache if password is set to `nil` ```rb # before: user.password = 'something' user.password = nil user.password # => 'something' # now: user.password = 'something' user.password = nil user.password # => nil ``` --- activemodel/CHANGELOG.md | 18 ++++++++++++++++++ .../lib/active_model/secure_password.rb | 1 + activemodel/test/cases/secure_password_test.rb | 6 ++++++ 3 files changed, 25 insertions(+) diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md index a061132d581..9f7b555276b 100644 --- a/activemodel/CHANGELOG.md +++ b/activemodel/CHANGELOG.md @@ -1,3 +1,21 @@ +* Clear secure password cache if password is set to `nil` + + Before: + + user.password = 'something' + user.password = nil + + user.password # => 'something' + + Now: + + user.password = 'something' + user.password = nil + + user.password # => nil + + *Markus Doits* + ## Rails 7.0.0.alpha2 (September 15, 2021) ## * No changes. diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb index 6af2809b24d..742e4a63ebb 100644 --- a/activemodel/lib/active_model/secure_password.rb +++ b/activemodel/lib/active_model/secure_password.rb @@ -94,6 +94,7 @@ module ActiveModel define_method("#{attribute}=") do |unencrypted_password| if unencrypted_password.nil? + instance_variable_set("@#{attribute}", nil) self.public_send("#{attribute}_digest=", nil) elsif !unencrypted_password.empty? instance_variable_set("@#{attribute}", unencrypted_password) diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb index 0aca714bd21..0b8ad35256a 100644 --- a/activemodel/test/cases/secure_password_test.rb +++ b/activemodel/test/cases/secure_password_test.rb @@ -91,6 +91,12 @@ class SecurePasswordTest < ActiveModel::TestCase assert_equal ["doesn't match Password"], @user.errors[:password_confirmation] end + test "resetting password to nil clears the password cache" do + @user.password = "password" + @user.password = nil + assert_nil @user.password + end + test "update an existing user with validation and no change in password" do assert @existing_user.valid?(:update), "user should be valid" end