uploads_controller.rb 1.41 KB
Newer Older
1
class UploadsController < ApplicationController
2 3
  skip_before_filter :authenticate_user!
  before_filter :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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
  def find_model
    unless upload_model && upload_mount
      return not_found!
    end

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

  def authorize_access!
    authorized = 
      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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

  def upload_model
    upload_models = {
      user: User,
      project: Project,
      note: Note,
      group: Group
    }

    upload_models[params[:model].to_sym]
  end

  def upload_mount
    upload_mounts = %w(avatar attachment file)

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