diff --git a/app/models/user.rb b/app/models/user.rb index e822a5d4eb..647d9c8940 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -536,25 +536,24 @@ def self.fetch_orphan_account def update_pseud_name return unless saved_change_to_login? && login_before_last_save.present? - - old_pseud = pseuds.where(name: login_before_last_save).first - if login.downcase == login_before_last_save.downcase - old_pseud.name = login - old_pseud.save! - else + + pseud_to_update = pseuds.where(name: login_before_last_save).first + # If the new login is (case insensitive) different from the old login + if login != login_before_last_save.downcase new_pseud = pseuds.where(name: login).first - # do nothing if they already have the matching pseud + # If the user does not have an existing pseud for the new login if new_pseud.blank? - if old_pseud.present? - # change the old pseud to match - old_pseud.name = login - old_pseud.save!(validate: false) - else + # If the pseud for the old login doesn't exist + if pseud_to_update.blank? # shouldn't be able to get here, but just in case Pseud.create!(name: login, user_id: id) end + else + pseud_to_update = new_pseud end end + pseud_to_update.name = login + pseud_to_update.save!(validate: justification_enabled?) end def reindex_user_creations_after_rename diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index d55c1bf1f3..2affbb55c5 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -359,6 +359,23 @@ expect(log_item.note).to eq("Change made by #{admin.login}") end end + + context "username was changed to match an existing pseud's name except with alternate capitalization and diacritics" do + let(:new_pseud) { build(:pseud, name: "New_Usernamé") } + + before do + existing_user.pseuds << new_pseud + existing_user.update!(login: "new_username") + existing_user.reload + end + + it "pseud's capitalization and diacritics were changed to match the new username's" do + expect(existing_user.pseuds.size).to eq(2) + expect(existing_user.pseuds.second.name).to eq(existing_user.login) + expect(existing_user.pseuds.second.name).to eq("new_username") + expect(existing_user.login).to eq("new_username") + end + end end describe ".search_multiple_by_email" do