uploads_controller.rb 2 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
      when Appearance
        true
26 27 28 29
      else
        permission = "read_#{model.class.to_s.underscore}".to_sym

        can?(current_user, permission, model)
30 31
      end

32 33 34 35 36 37
    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)
38

39 40 41 42
    render_unauthorized unless authorized
  end

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

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

Douwe Maan's avatar
Douwe Maan committed
60
    upload_models[params[:model]]
61 62 63
  end

  def upload_mount
64 65
    return true unless params[:mounted_as]

66
    upload_mounts = %w(avatar attachment file logo header_logo)
67 68 69 70 71

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

  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
96
end