FIX: encrypt works for a user who cannot edit posts (#24)

FIX: encrypt works for a user who cannot edit posts (#24)

The bug mentioned here: https://meta.discourse.org/t/min-trust-to-edit-post-setting-interfering-with-discourse-encrypt/163245

Using the guardian was the best and safest approach. However, there is a situation when user cannot edit posts. For example when min_trust_to_edit_post is set higher than the user trust level. Therefore we can simply check if the user is author of the post.

diff --git a/app/controllers/encrypt_controller.rb b/app/controllers/encrypt_controller.rb
index 1fe71e1..e78feb7 100644
--- a/app/controllers/encrypt_controller.rb
+++ b/app/controllers/encrypt_controller.rb
@@ -135,7 +135,8 @@ class DiscourseEncrypt::EncryptController < ApplicationController
     encrypted_raw = params.require(:encrypted_raw)
 
     post = Post.find_by(id: post_id)
-    guardian.ensure_can_edit!(post)
+
+    guardian.ensure_can_encrypt_post!(post)
 
     if post.updated_at < 5.seconds.ago
       return render_json_error(I18n.t('too_late_to_edit'), status: 409)
diff --git a/plugin.rb b/plugin.rb
index 661504a..2bb12ab 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -172,6 +172,10 @@ after_initialize do
     end
   end
 
+  add_to_class(:guardian, :can_encrypt_post?) do |post|
+    SiteSetting.encrypt_enabled? && post.topic.is_encrypted? && post.user == @user
+  end
+
   #
   # Hide cooked content.
   #
diff --git a/spec/requests/encrypt_controller_spec.rb b/spec/requests/encrypt_controller_spec.rb
index 7e3c165..559c4fe 100644
--- a/spec/requests/encrypt_controller_spec.rb
+++ b/spec/requests/encrypt_controller_spec.rb
@@ -109,4 +109,24 @@ describe DiscourseEncrypt::EncryptController do
       expect(response.status).to eq(200)
     end
   end
+
+  context '#update_post' do
+    let!(:post) { Fabricate(:encrypt_post) }
+
+    before do
+      SiteSetting.min_trust_to_edit_post = 2
+    end
+
+    it 'is not raising error when user cannot edit because min trust level' do
+      sign_in(post.user)
+      put '/encrypt/post', params: { post_id: post.id, encrypted_raw: 'some encrypted raw' }
+      expect(response.status).to eq(200)
+    end
+
+    it 'does not work if user is not author of post' do
+      sign_in(user)
+      put '/encrypt/post', params: { post_id: post.id, encrypted_raw: 'some encrypted raw' }
+      expect(response.status).to eq(403)
+    end
+  end
 end

GitHub sha: d99f740a

This commit appears in #24 which was merged by lis2.

The response code here seems odd if a user who cannot encrypt the post is trying to encrypt it. I guess Iā€™m confused with the description of the test vs the response code since the end point should not silently fail?

2 Likes