Skip to content

A platform for community discussion. Free, open, simple.

FIX: Add guard to prevent a primary `UserEmail` from being reassigned.

Guo Xiang Tan8a3bbcb19aa0
diff --git a/app/models/user_email.rb b/app/models/user_email.rb
index 426d2fe8289..7ddbf73602e 100644
--- a/app/models/user_email.rb
+++ b/app/models/user_email.rb
@@ -12,6 +12,8 @@ class UserEmail < ActiveRecord::Base
validates :email, email: true, format: { with: EmailValidator.email_regex },
if: :validate_email?
+ validate :user_id_not_changed, if: :primary
+
validates :primary, uniqueness: { scope: [:user_id] }
private
@@ -27,6 +29,14 @@ class UserEmail < ActiveRecord::Base
return false if self.skip_validate_email
email_changed?
end
+
+ def user_id_not_changed
+ if self.will_save_change_to_user_id? && self.persisted?
+ self.errors.add(:user_id, I18n.t(
+ 'active_record.errors.model.user_email.attributes.user_id.reassigning_primary_email')
+ )
+ end
+ end
end
# == Schema Information
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index b0c2c5033df..44746b461a2 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -403,6 +403,10 @@ en:
unique_characters: "has too many repeated characters. Please use a more secure password."
ip_address:
signup_not_allowed: "Signup is not allowed from this account."
+ user_email:
+ attributes:
+ user_id:
+ reassigning_primary_email: "Reassigning a primary email to another user is not allowed."
color_scheme_color:
attributes:
hex:
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index d057e042c33..621dd964249 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -37,6 +37,18 @@ describe User do
expect(user.errors.messages).to include(:primary_email)
end
end
+
+ describe 'when primary_email is being reassigned to another user' do
+ it "should not be valid" do
+ user2 = Fabricate.build(:user, email: nil)
+ user.save!
+ user2.primary_email = user.primary_email
+
+ expect(user2).to_not be_valid
+ expect(user2.errors.messages).to include(:primary_email)
+ expect(user2.primary_email.errors.messages).to include(:user_id)
+ end
+ end
end
end