summaryrefslogtreecommitdiff
path: root/lib/gitlab/routing.rb
blob: fd9fb8ab7e22218f669bb1448c15743ecb7e75c6 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# frozen_string_literal: true

module Gitlab
  module Routing
    extend ActiveSupport::Concern

    class LegacyRedirector
      # @params path_type [symbol] type of path to do "-" redirection
      # https://gitlab.com/gitlab-org/gitlab/-/issues/16854
      def initialize(path_type)
        @path_type = path_type
      end

      def call(_params, request)
        ensure_valid_uri!(request)

        # Only replace the last occurrence of `path`.
        #
        # `request.fullpath` includes the querystring
        new_path = request.path.sub(%r{/#{@path_type}(/*)(?!.*#{@path_type})}, "/-/#{@path_type}\\1")
        new_path = "#{new_path}?#{request.query_string}" if request.query_string.present?

        new_path
      end

      private

      def ensure_valid_uri!(request)
        URI.parse(request.path)
      rescue URI::InvalidURIError => e
        # If url is invalid, raise custom error,
        # which can be ignored by monitoring tools.
        raise ActionController::RoutingError, e.message
      end
    end

    mattr_accessor :_includers
    self._includers = []

    included do
      Gitlab::Routing.includes_helpers(self)

      include Gitlab::Routing.url_helpers
    end

    def self.includes_helpers(klass)
      self._includers << klass
    end

    def self.add_helpers(mod)
      url_helpers.include mod
      url_helpers.extend mod

      GitlabRoutingHelper.include mod
      GitlabRoutingHelper.extend mod

      app_url_helpers = Gitlab::Application.routes.named_routes.url_helpers_module
      app_url_helpers.include mod
      app_url_helpers.extend mod

      _includers.each do |klass|
        klass.include mod
      end
    end

    # Returns the URL helpers Module.
    #
    # This method caches the output as Rails' "url_helpers" method creates an
    # anonymous module every time it's called.
    #
    # Returns a Module.
    def self.url_helpers
      @url_helpers ||= Gitlab::Application.routes.url_helpers
    end

    def self.redirect_legacy_paths(router, *paths)
      paths.each do |path|
        router.match "/#{path}(/*rest)",
                     via: [:get, :post, :patch, :delete],
                     to: router.redirect(LegacyRedirector.new(path)),
                     as: "legacy_#{path}_redirect"
      end
    end
  end
end