uploads_controller.rb 2.28 KB
Newer Older
1
class UploadsController < ApplicationController
2
  include UploadsActions
3

4 5 6 7
  skip_before_action :authenticate_user!
  before_action :find_model
  before_action :authorize_access!, only: [:show]
  before_action :authorize_create_access!, only: [:create]
8

9 10
  private

11
  def find_model
12 13
    return nil unless params[:id]

14
    return render_404 unless upload_model && upload_mount
15 16 17 18 19

    @model = upload_model.find(params[:id])
  end

  def authorize_access!
20 21
    return nil unless model

22
    authorized =
23
      case model
24
      when Note
25 26
        can?(current_user, :read_project, model.project)
      when User
27
        true
28 29
      when Appearance
        true
30 31 32 33
      else
        permission = "read_#{model.class.to_s.underscore}".to_sym

        can?(current_user, permission, model)
34 35
      end

36 37 38 39
    render_unauthorized unless authorized
  end

  def authorize_create_access!
40
    return nil unless model
41

42 43
    # for now we support only personal snippets comments
    authorized = can?(current_user, :comment_personal_snippet, model)
44

45 46 47 48
    render_unauthorized unless authorized
  end

  def render_unauthorized
49
    if current_user
50
      render_404
51 52
    else
      authenticate_user!
53 54
    end
  end
55 56 57

  def upload_model
    upload_models = {
Douwe Maan's avatar
Douwe Maan committed
58 59 60
      "user"    => User,
      "project" => Project,
      "note"    => Note,
61
      "group"   => Group,
62 63
      "appearance" => Appearance,
      "personal_snippet" => PersonalSnippet
64 65
    }

Douwe Maan's avatar
Douwe Maan committed
66
    upload_models[params[:model]]
67 68 69
  end

  def upload_mount
70 71
    return true unless params[:mounted_as]

72
    upload_mounts = %w(avatar attachment file logo header_logo)
73 74 75 76 77

    if upload_mounts.include?(params[:mounted_as])
      params[:mounted_as]
    end
  end
78 79 80 81

  def uploader
    return @uploader if defined?(@uploader)

82 83 84 85 86 87
    case model
    when nil
      @uploader = PersonalFileUploader.new(nil, params[:secret])

      @uploader.retrieve_from_store!(params[:filename])
    when PersonalSnippet
88 89 90 91
      @uploader = PersonalFileUploader.new(model, params[:secret])

      @uploader.retrieve_from_store!(params[:filename])
    else
92
      @uploader = @model.public_send(upload_mount) # rubocop:disable GitlabSecurity/PublicSend
93 94 95 96 97 98 99 100 101 102 103 104 105 106

      redirect_to @uploader.url unless @uploader.file_storage?
    end

    @uploader
  end

  def uploader_class
    PersonalFileUploader
  end

  def model
    @model ||= find_model
  end
107
end