uploads_controller.rb 1.42 KB
Newer Older
1
class UploadsController < ApplicationController
2 3
  skip_before_action :authenticate_user!
  before_action :find_model, :authorize_access!
4

5
  def show
6
    uploader = @model.send(upload_mount)
7

8 9 10 11
    unless uploader.file_storage?
      return redirect_to uploader.url
    end

12
    unless uploader.file && uploader.file.exists?
13 14
      return not_found!
    end
15 16 17

    disposition = uploader.image? ? 'inline' : 'attachment'
    send_file uploader.file.path, disposition: disposition
18
  end
19

20 21
  private

22 23 24 25 26 27 28 29 30
  def find_model
    unless upload_model && upload_mount
      return not_found!
    end

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

  def authorize_access!
31
    authorized =
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
      case @model
      when Project
        can?(current_user, :read_project, @model)
      when Group
        can?(current_user, :read_group, @model)
      when Note
        can?(current_user, :read_project, @model.project)
      else
        # No authentication required for user avatars.
        true
      end

    return if authorized

    if current_user
      not_found!
    else
      authenticate_user!
50 51
    end
  end
52 53 54

  def upload_model
    upload_models = {
Douwe Maan's avatar
Douwe Maan committed
55 56 57 58
      "user"    => User,
      "project" => Project,
      "note"    => Note,
      "group"   => Group
59 60
    }

Douwe Maan's avatar
Douwe Maan committed
61
    upload_models[params[:model]]
62 63 64 65 66 67 68 69 70
  end

  def upload_mount
    upload_mounts = %w(avatar attachment file)

    if upload_mounts.include?(params[:mounted_as])
      params[:mounted_as]
    end
  end
71
end