uploads_controller.rb 1.91 KB
Newer Older
1
class UploadsController < ApplicationController
2
  include UploadsActions
3

4 5 6 7 8 9 10 11 12 13 14 15 16 17
  UnknownUploadModelError = Class.new(StandardError)

  MODEL_CLASSES = {
    "user"             => User,
    "project"          => Project,
    "note"             => Note,
    "group"            => Group,
    "appearance"       => Appearance,
    "personal_snippet" => PersonalSnippet,
    nil                => PersonalSnippet
  }.freeze

  rescue_from UnknownUploadModelError, with: :render_404

18
  skip_before_action :authenticate_user!
19
  before_action :upload_mount_satisfied?
20 21 22
  before_action :find_model
  before_action :authorize_access!, only: [:show]
  before_action :authorize_create_access!, only: [:create]
23

24 25 26
  def uploader_class
    PersonalFileUploader
  end
27

28
  def find_model
29 30
    return nil unless params[:id]

31
    upload_model_class.find(params[:id])
32 33 34
  end

  def authorize_access!
35 36
    return nil unless model

37
    authorized =
38
      case model
39
      when Note
40 41
        can?(current_user, :read_project, model.project)
      when User
42
        true
43 44
      when Appearance
        true
45 46 47 48
      else
        permission = "read_#{model.class.to_s.underscore}".to_sym

        can?(current_user, permission, model)
49 50
      end

51 52 53 54
    render_unauthorized unless authorized
  end

  def authorize_create_access!
55
    return nil unless model
56

57 58
    # for now we support only personal snippets comments
    authorized = can?(current_user, :comment_personal_snippet, model)
59

60 61 62 63
    render_unauthorized unless authorized
  end

  def render_unauthorized
64
    if current_user
65
      render_404
66 67
    else
      authenticate_user!
68 69
    end
  end
70

71 72
  def upload_model_class
    MODEL_CLASSES[params[:model]] || raise(UnknownUploadModelError)
73
  end
74

75 76
  def upload_model_class_has_mounts?
    upload_model_class < CarrierWave::Mount::Extension
77 78
  end

79 80
  def upload_mount_satisfied?
    return true unless upload_model_class_has_mounts?
81

82
    upload_model_class.uploader_options.has_key?(upload_mount)
83
  end
84
end