uploads_controller.rb 1.97 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
    return render_404 unless upload_model && upload_mount
13 14 15 16 17

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

  def authorize_access!
18
    authorized =
19
      case model
20
      when Note
21 22
        can?(current_user, :read_project, model.project)
      when User
23
        true
24 25 26 27
      else
        permission = "read_#{model.class.to_s.underscore}".to_sym

        can?(current_user, permission, model)
28 29
      end

30 31 32 33 34 35
    render_unauthorized unless authorized
  end

  def authorize_create_access!
    # for now we support only personal snippets comments
    authorized = can?(current_user, :comment_personal_snippet, model)
36

37 38 39 40
    render_unauthorized unless authorized
  end

  def render_unauthorized
41
    if current_user
42
      render_404
43 44
    else
      authenticate_user!
45 46
    end
  end
47 48 49

  def upload_model
    upload_models = {
Douwe Maan's avatar
Douwe Maan committed
50 51 52
      "user"    => User,
      "project" => Project,
      "note"    => Note,
53
      "group"   => Group,
54 55
      "appearance" => Appearance,
      "personal_snippet" => PersonalSnippet
56 57
    }

Douwe Maan's avatar
Douwe Maan committed
58
    upload_models[params[:model]]
59 60 61
  end

  def upload_mount
62 63
    return true unless params[:mounted_as]

64
    upload_mounts = %w(avatar attachment file logo header_logo)
65 66 67 68 69

    if upload_mounts.include?(params[:mounted_as])
      params[:mounted_as]
    end
  end
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

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

    if model.is_a?(PersonalSnippet)
      @uploader = PersonalFileUploader.new(model, params[:secret])

      @uploader.retrieve_from_store!(params[:filename])
    else
      @uploader = @model.send(upload_mount)

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

    @uploader
  end

  def uploader_class
    PersonalFileUploader
  end

  def model
    @model ||= find_model
  end
94
end