uploads_controller.rb 1.53 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
      return render_404
14
    end
15 16

    disposition = uploader.image? ? 'inline' : 'attachment'
17 18

    expires_in 0.seconds, must_revalidate: true, private: true
19
    send_file uploader.file.path, disposition: disposition
20
  end
21

22 23
  private

24 25
  def find_model
    unless upload_model && upload_mount
26
      return render_404
27 28 29 30 31 32
    end

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

  def authorize_access!
33
    authorized =
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
      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
49
      render_404
50 51
    else
      authenticate_user!
52 53
    end
  end
54 55 56

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

Douwe Maan's avatar
Douwe Maan committed
64
    upload_models[params[:model]]
65 66 67
  end

  def upload_mount
68
    upload_mounts = %w(avatar attachment file logo header_logo)
69 70 71 72 73

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