BigW Consortium Gitlab

help_controller.rb 2.41 KB
Newer Older
1
class HelpController < ApplicationController
2
  skip_before_action :authenticate_user!, :reject_blocked!
3

4
  layout 'help'
5

6
  def index
7
    @help_index = File.read(Rails.root.join('doc', 'README.md'))
8 9 10 11

    # Prefix Markdown links with `help/` unless they already have been
    # See http://rubular.com/r/nwwhzH6Z8X
    @help_index.gsub!(/(\]\()(?!help\/)([^\)\(]+)(\))/, '\1help/\2\3')
12
  end
Dmitriy Zaporozhets committed
13

14
  def show
Connor Shea committed
15
    @path = clean_path_info(path_params[:path])
16

17 18
    respond_to do |format|
      format.any(:markdown, :md, :html) do
19
        # Note: We are purposefully NOT using `Rails.root.join`
20
        path = File.join(Rails.root, 'doc', "#{@path}.md")
21 22 23 24 25 26 27 28 29 30 31 32

        if File.exist?(path)
          @markdown = File.read(path)

          render 'show.html.haml'
        else
          # Force template to Haml
          render 'errors/not_found.html.haml', layout: 'errors', status: 404
        end
      end

      # Allow access to images in the doc folder
33
      format.any(:png, :gif, :jpeg, :mp4) do
34
        # Note: We are purposefully NOT using `Rails.root.join`
35
        path = File.join(Rails.root, 'doc', "#{@path}.#{params[:format]}")
36 37 38 39 40 41 42 43 44 45

        if File.exist?(path)
          send_file(path, disposition: 'inline')
        else
          head :not_found
        end
      end

      # Any other format we don't recognize, just respond 404
      format.any { head :not_found }
46 47 48
    end
  end

49
  def shortcuts
50
  end
51 52

  def ui
53
    @user = User.new(id: 0, name: 'John Doe', username: '@johndoe')
54
  end
55

56 57
  private

58
  def path_params
59
    params.require(:path)
60 61 62 63

    params
  end

64 65
  PATH_SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact)

66 67
  # Taken from ActionDispatch::FileHandler
  # Cleans up the path, to prevent directory traversal outside the doc folder.
68
  def clean_path_info(path_info)
69
    parts = path_info.split(PATH_SEPS)
70 71 72

    clean = []

73
    # Walk over each part of the path
74
    parts.each do |part|
75
      # Turn `one//two` or `one/./two` into `one/two`.
76
      next if part.empty? || part == '.'
77 78 79 80 81 82 83 84

      if part == '..'
        # Turn `one/two/../` into `one`
        clean.pop
      else
        # Add simple folder names to the clean path.
        clean << part
      end
85 86
    end

87 88
    # If the path was an absolute path (i.e. `/` or `/one/two`),
    # add `/` to the front of the clean path.
89 90
    clean.unshift '/' if parts.empty? || parts.first.empty?

91
    # Join all the clean path parts by the path separator.
92 93
    ::File.join(*clean)
  end
94
end