From 5794d65a0743343bfaa367d10d7b0aaa82e20a25 Mon Sep 17 00:00:00 2001
From: Robert Speicher <rspeicher@gmail.com>
Date: Tue, 1 Sep 2015 18:16:56 -0400
Subject: [PATCH] Add post_process method to Gitlab::Markdown

---
 app/helpers/gitlab_markdown_helper.rb |  6 ++++--
 lib/gitlab/markdown.rb                | 22 ++++++++++++++++++++++
 spec/features/markdown_spec.rb        |  2 +-
 3 files changed, 27 insertions(+), 3 deletions(-)

diff --git a/app/helpers/gitlab_markdown_helper.rb b/app/helpers/gitlab_markdown_helper.rb
index 9890ec7c757..f2cab2840d4 100644
--- a/app/helpers/gitlab_markdown_helper.rb
+++ b/app/helpers/gitlab_markdown_helper.rb
@@ -52,7 +52,8 @@ module GitlabMarkdownHelper
       ref:          @ref
     )
 
-    Gitlab::Markdown.render(text, context)
+    html = Gitlab::Markdown.render(text, context)
+    Gitlab::Markdown.post_process(html, current_user)
   end
 
   # TODO (rspeicher): Remove all usages of this helper and just call `markdown`
@@ -65,7 +66,8 @@ module GitlabMarkdownHelper
       ref:          @ref
     )
 
-    Gitlab::Markdown.gfm(text, options)
+    html = Gitlab::Markdown.gfm(text, options)
+    Gitlab::Markdown.post_process(html, current_user)
   end
 
   def asciidoc(text)
diff --git a/lib/gitlab/markdown.rb b/lib/gitlab/markdown.rb
index 478851fc656..dbb8da3f0ad 100644
--- a/lib/gitlab/markdown.rb
+++ b/lib/gitlab/markdown.rb
@@ -31,6 +31,24 @@ module Gitlab
       renderer.render(markdown)
     end
 
+    # Perform post-processing on an HTML String
+    #
+    # This method is used to perform state-dependent changes to a String of
+    # HTML, such as removing references that the current user doesn't have
+    # permission to make (`RedactorFilter`).
+    #
+    # html     - String to process
+    # for_user - User state
+    #
+    # Returns an HTML-safe String
+    def self.post_process(html, for_user)
+      result = post_processor.call(html, current_user: for_user)
+
+      result[:output].
+        to_html.
+        html_safe
+    end
+
     # Provide autoload paths for filters to prevent a circular dependency error
     autoload :AutolinkFilter,               'gitlab/markdown/autolink_filter'
     autoload :CommitRangeReferenceFilter,   'gitlab/markdown/commit_range_reference_filter'
@@ -115,6 +133,10 @@ module Gitlab
       end
     end
 
+    def self.post_processor
+      @post_processor ||= HTML::Pipeline.new([Gitlab::Markdown::RedactorFilter])
+    end
+
     def self.redcarpet_options
       # https://github.com/vmg/redcarpet#and-its-like-really-simple-to-use
       @redcarpet_options ||= {
diff --git a/spec/features/markdown_spec.rb b/spec/features/markdown_spec.rb
index c557a1061af..fdd8cf07b12 100644
--- a/spec/features/markdown_spec.rb
+++ b/spec/features/markdown_spec.rb
@@ -220,7 +220,7 @@ describe 'GitLab Markdown', feature: true do
     end
   end
 
-  # `markdown` calls these two methods
+  # Fake a `current_user` helper
   def current_user
     @feat.user
   end
-- 
GitLab