Reapply "FIX: Skip key consistency check when creating the topic."

Reapply “FIX: Skip key consistency check when creating the topic.”

This commit reapplies bcc0fe9d15f61ae7b60b2821dcf772ef5db6e9c5 and fixes the failing spec.

diff --git a/plugin.rb b/plugin.rb
index 0b44607..5a4a4d4 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -215,7 +215,7 @@ after_initialize do
 
   # Delete TopicAllowedUser records for users who do not have the key.
   on(:post_created) do |post, opts, user|
-    if post.topic&.is_encrypted? && !DiscourseEncrypt::Store.get("key_#{post.topic_id}_#{user.id}").present?
+    if post.post_number > 1 && post.topic&.is_encrypted? && !DiscourseEncrypt::Store.get("key_#{post.topic_id}_#{user.id}").present?
       TopicAllowedUser.find_by(user_id: user.id, topic_id: post.topic_id).delete
     end
   end
diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb
index 5a888bb..70d9de7 100644
--- a/spec/models/topic_spec.rb
+++ b/spec/models/topic_spec.rb
@@ -4,7 +4,8 @@ require 'rails_helper'
 
 describe Topic do
   let(:topic) { Fabricate(:topic) }
-  let(:encrypt_topic) { Fabricate(:encrypt_topic) }
+  let(:encrypt_post) { Fabricate(:encrypt_post) }
+  let!(:encrypt_topic) { encrypt_post.topic }
 
   context '#is_encrypted?' do
     it 'works' do
@@ -16,8 +17,8 @@ describe Topic do
   context 'remove_allowed_user' do
     it 'deletes topic key for user' do
       expect { encrypt_topic.remove_allowed_user(Discourse.system_user, encrypt_topic.user) }
-        .to change { TopicAllowedUser.count }.by(1)
-        .and change { PluginStoreRow.count }.by(1)
+        .to change { TopicAllowedUser.count }.by(-1)
+        .and change { PluginStoreRow.count }.by(-1)
       expect(DiscourseEncrypt::Store.get("key_#{encrypt_topic.id}_#{encrypt_topic.user_id}")).to eq(nil)
     end
   end

GitHub sha: 00868e55