FIX: check if user is already allowed before adding to topic allowed users (#7242)

FIX: check if user is already allowed before adding to topic allowed users (#7242)

diff --git a/app/models/invite_redeemer.rb b/app/models/invite_redeemer.rb
index 23a6f01..d43ad9a 100644
--- a/app/models/invite_redeemer.rb
+++ b/app/models/invite_redeemer.rb
@@ -73,7 +73,6 @@ InviteRedeemer = Struct.new(:invite, :username, :name, :password, :user_custom_f
   def process_invitation
     approve_account_if_needed
     add_to_private_topics_if_invited
-    add_user_to_invited_topics
     add_user_to_groups
     send_welcome_message
     notify_invitee
@@ -103,16 +102,9 @@ InviteRedeemer = Struct.new(:invite, :username, :name, :password, :user_custom_f
   end
 
   def add_to_private_topics_if_invited
-    invite.topics.private_messages.each do |t|
-      t.topic_allowed_users.create(user_id: invited_user.id)
-    end
-  end
-
-  def add_user_to_invited_topics
-    Invite.where('invites.email = ? and invites.id != ?', invite.email, invite.id).includes(:topics).where(topics: { archetype: Archetype::private_message }).each do |i|
-      i.topics.each do |t|
-        t.topic_allowed_users.create(user_id: invited_user.id)
-      end
+    topic_ids = Topic.where(archetype: Archetype::private_message).includes(:invites).where(invites: { email: invite.email }).pluck(:id)
+    topic_ids.each do |id|
+      TopicAllowedUser.create(user_id: invited_user.id, topic_id: id) unless TopicAllowedUser.exists?(user_id: invited_user.id, topic_id: id)
     end
   end
 
diff --git a/app/models/topic.rb b/app/models/topic.rb
index b1f428e..931cd31 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -926,7 +926,7 @@ class Topic < ActiveRecord::Base
 
   def grant_permission_to_user(lower_email)
     user = User.find_by_email(lower_email)
-    topic_allowed_users.create!(user_id: user.id)
+    topic_allowed_users.create!(user_id: user.id) unless topic_allowed_users.exists?(user_id: user.id)
   end
 
   def max_post_number
@@ -1419,7 +1419,7 @@ class Topic < ActiveRecord::Base
 
     Topic.transaction do
       rate_limit_topic_invitation(invited_by)
-      topic_allowed_users.create!(user_id: target_user.id)
+      topic_allowed_users.create!(user_id: target_user.id) unless topic_allowed_users.exists?(user_id: target_user.id)
       add_small_action(invited_by, "invited_user", target_user.username)
 
       create_invite_notification!(

GitHub sha: 9b00ca30