summaryrefslogtreecommitdiff
path: root/lib/gitlab/markdown/cross_project_reference.rb
blob: 261fc0feb0e06411ebdff8cea713c4bd1f9e577f (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
module Gitlab
  module Markdown
    # Common methods for ReferenceFilters that support an optional cross-project
    # reference.
    module CrossProjectReference
      NAMING_PATTERN  = Gitlab::Regex::NAMESPACE_PATH_REGEX_STR
      PROJECT_PATTERN = "(?<project>#{NAMING_PATTERN}/#{NAMING_PATTERN})"

      # Given a cross-project reference string, get the Project record
      #
      # Defaults to value of `context[:project]` if:
      # * No reference is given OR
      # * Reference given doesn't exist
      #
      # ref - String reference.
      #
      # Returns a Project, or nil if the reference can't be accessed
      def project_from_ref(ref)
        return context[:project] unless ref

        other = Project.find_with_namespace(ref)
        return nil unless other && user_can_reference_project?(other)

        other
      end

      def user_can_reference_project?(project, user = context[:current_user])
        Ability.abilities.allowed?(user, :read_project, project)
      end
    end
  end
end