summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/redactor_filter.rb
blob: c753a84a20d9a2d556cfc857d46f8f507d6ce2b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
module Banzai
  module Filter
    # HTML filter that removes references to records that the current user does
    # not have permission to view.
    #
    # Expected to be run in its own post-processing pipeline.
    #
    class RedactorFilter < HTML::Pipeline::Filter
      def call
        nodes = Querying.css(doc, 'a.gfm[data-reference-type]')
        visible = nodes_visible_to_user(nodes)

        nodes.each do |node|
          unless visible.include?(node)
            # The reference should be replaced by the original text,
            # which is not always the same as the rendered text.
            text = node.attr('data-original') || node.text
            node.replace(text)
          end
        end

        doc
      end

      private

      def nodes_visible_to_user(nodes)
        per_type = Hash.new { |h, k| h[k] = [] }
        visible = Set.new

        nodes.each do |node|
          per_type[node.attr('data-reference-type')] << node
        end

        per_type.each do |type, nodes|
          parser = Banzai::ReferenceParser[type].new(project, current_user)

          visible.merge(parser.nodes_visible_to_user(current_user, nodes))
        end

        visible
      end

      def current_user
        context[:current_user]
      end

      def project
        context[:project]
      end
    end
  end
end