From 60e933df73ad8cebf7cc8a3010accff5efded472 Mon Sep 17 00:00:00 2001 From: Michiel Prins Date: Mon, 29 Apr 2013 15:06:13 +0200 Subject: [PATCH] Add destroy_with_password method --- lib/devise/models/database_authenticatable.rb | 16 ++++++++++++ test/models/database_authenticatable_test.rb | 26 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/lib/devise/models/database_authenticatable.rb b/lib/devise/models/database_authenticatable.rb index 36e1bacc..6b05a8cf 100644 --- a/lib/devise/models/database_authenticatable.rb +++ b/lib/devise/models/database_authenticatable.rb @@ -95,6 +95,22 @@ module Devise result end + # Destroy record when :current_password matches, otherwise returns + # error on :current_password. It also automatically rejects + # :current_password if it is blank. + def destroy_with_password(current_password) + result = if valid_password?(current_password) + destroy + else + self.valid? + self.errors.add(:current_password, current_password.blank? ? :blank : :invalid) + false + end + + self.current_password = nil + result + end + def after_database_authentication end diff --git a/test/models/database_authenticatable_test.rb b/test/models/database_authenticatable_test.rb index 1439a51f..2ed3f4df 100644 --- a/test/models/database_authenticatable_test.rb +++ b/test/models/database_authenticatable_test.rb @@ -183,6 +183,32 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase assert user.valid_password?('12345678') end + test 'should destroy user if current password is valid' do + user = create_user + assert user.destroy_with_password('12345678') + assert_raise ActiveRecord::RecordNotFound do + user.reload + end + end + + test 'should not destroy user with invalid password' do + user = create_user + assert_not user.destroy_with_password('other') + assert_nothing_raised ActiveRecord::RecordNotFound do + user.reload + end + assert_match "is invalid", user.errors[:current_password].join + end + + test 'should not destroy user with blank password' do + user = create_user + assert_not user.destroy_with_password(nil) + assert_nothing_raised ActiveRecord::RecordNotFound do + user.reload + end + assert_match "can't be blank", user.errors[:current_password].join + end + test 'downcase_keys with validation' do user = User.create(:email => "HEllO@example.com", :password => "123456") user = User.create(:email => "HEllO@example.com", :password => "123456")