FIX: Ensure scope exists in serializers.

FIX: Ensure scope exists in serializers.
From e4eeaa312324c4d7d56378278451fc011eb8a471 Mon Sep 17 00:00:00 2001
From: Dan Ungureanu <dan@ungureanu.me>
Date: Wed, 5 Dec 2018 10:54:31 +0200
Subject: [PATCH] FIX: Ensure scope exists in serializers.


diff --git a/plugin.rb b/plugin.rb
index 6f67817..00fb61d 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -197,7 +197,7 @@ after_initialize do
   end
 
   add_to_serializer(:topic_view, :include_topic_key?) do
-    scope.user
+    scope&.user.present?
   end
 
   add_to_serializer(:basic_topic, :topic_key, false) do
@@ -205,7 +205,7 @@ after_initialize do
   end
 
   add_to_serializer(:basic_topic, :include_topic_key?) do
-    scope.user
+    scope&.user.present?
   end
 
   add_to_serializer(:listable_topic, :topic_key, false) do
@@ -213,7 +213,7 @@ after_initialize do
   end
 
   add_to_serializer(:listable_topic, :include_topic_key?) do
-    scope.user
+    scope&.user.present?
   end
 
   add_to_serializer(:topic_list_item, :topic_key, false) do
@@ -221,7 +221,7 @@ after_initialize do
   end
 
   add_to_serializer(:topic_list_item, :include_topic_key?) do
-    scope.user
+    scope&.user.present?
   end
 
   DiscourseEncrypt::Engine.routes.draw do
diff --git a/spec/serializers/basic_topic_serializer_spec.rb b/spec/serializers/basic_topic_serializer_spec.rb
new file mode 100644
index 0000000..4a1cec2
--- /dev/null
+++ b/spec/serializers/basic_topic_serializer_spec.rb
@@ -0,0 +1,26 @@
+require 'rails_helper'
+
+describe BasicTopicSerializer do
+
+  let(:store) { PluginStore.new('discourse-encrypt') }
+
+  let(:user) { Fabricate(:user) }
+
+  let(:topic) { Fabricate(:private_message_topic, topic_allowed_users: [ Fabricate.build(:topic_allowed_user, user: user) ]) }
+  let(:unencrypted_topic) { Fabricate(:private_message_topic, topic_allowed_users: [ Fabricate.build(:topic_allowed_user, user: user) ]) }
+
+  before do
+    topic.custom_fields['encrypted_title'] = '-- the encrypted title --'
+    topic.save!
+
+    store.set("key_#{topic.id}_#{user.id}", '-- the key of user --')
+  end
+
+  it 'does not contain user-specific encrypted fields when scope is missing' do
+    serialized = described_class.new(topic, root: false).as_json
+
+    expect(serialized[:encrypted_title]).to eq('-- the encrypted title --')
+    expect(serialized[:topic_key]).to eq(nil)
+  end
+
+end

GitHub

2 Likes