From 4172e1dd52f8728fa703838888c978caea8f4044 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Mon, 9 Jul 2018 16:54:57 +0800 Subject: [PATCH] FIX: Rename `User#usernames` that clashes with `Group#name`. (#6069) --- ...x_user_usernames_and_groups_names_clash.rb | 29 +++++++++++++++++++ ...er_usernames_and_group_names_clash_spec.rb | 15 ++++++++++ 2 files changed, 44 insertions(+) create mode 100644 app/jobs/scheduled/fix_user_usernames_and_groups_names_clash.rb create mode 100644 spec/jobs/fix_user_usernames_and_group_names_clash_spec.rb diff --git a/app/jobs/scheduled/fix_user_usernames_and_groups_names_clash.rb b/app/jobs/scheduled/fix_user_usernames_and_groups_names_clash.rb new file mode 100644 index 00000000000..3ed7469db07 --- /dev/null +++ b/app/jobs/scheduled/fix_user_usernames_and_groups_names_clash.rb @@ -0,0 +1,29 @@ +module Jobs + class FixUserUsernamesAndGroupNamesClash < Jobs::Scheduled + every 1.week + + def execute(args) + User.joins("LEFT JOIN groups ON lower(groups.name) = users.username_lower") + .where("groups.id IS NOT NULL") + .find_each do |user| + + suffix = 1 + old_username = user.username + + loop do + user.username = "#{old_username}#{suffix}" + suffix += 1 + break if user.valid? + end + + new_username = user.username + user.username = old_username + + UsernameChanger.new( + user, + new_username + ).change(asynchronous: false) + end + end + end +end diff --git a/spec/jobs/fix_user_usernames_and_group_names_clash_spec.rb b/spec/jobs/fix_user_usernames_and_group_names_clash_spec.rb new file mode 100644 index 00000000000..3b209acf4fd --- /dev/null +++ b/spec/jobs/fix_user_usernames_and_group_names_clash_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +RSpec.describe Jobs::FixUserUsernamesAndGroupNamesClash do + it 'update usernames of users that clashes with a group name' do + user = Fabricate(:user) + Fabricate(:user, username: 'test1') + group = Fabricate(:group, name: 'test') + user.update_columns(username: 'test', username_lower: 'test') + + Jobs::FixUserUsernamesAndGroupNamesClash.new.execute({}) + + expect(user.reload.username).to eq('test2') + expect(group.reload.name).to eq('test') + end +end