uploads_controller.rb 2.03 KB
Newer Older
1 2
# frozen_string_literal: true

3
class UploadsController < ApplicationController
4
  include UploadsActions
5

6 7 8 9 10 11 12 13 14 15 16 17 18 19
  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

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

26 27 28
  def uploader_class
    PersonalFileUploader
  end
29

30
  def find_model
31 32
    return nil unless params[:id]

33
    upload_model_class.find(params[:id])
34 35 36
  end

  def authorize_access!
37 38
    return nil unless model

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

        can?(current_user, permission, model)
51 52
      end

53 54 55 56
    render_unauthorized unless authorized
  end

  def authorize_create_access!
57
    return nil unless model
58

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

62 63 64 65
    render_unauthorized unless authorized
  end

  def render_unauthorized
66
    if current_user
67
      render_404
68 69
    else
      authenticate_user!
70 71
    end
  end
72

73
  def cache_privately?
74
    true unless User === model || Appearance === model
75 76
  end

77 78
  def upload_model_class
    MODEL_CLASSES[params[:model]] || raise(UnknownUploadModelError)
79
  end
80

81 82
  def upload_model_class_has_mounts?
    upload_model_class < CarrierWave::Mount::Extension
83 84
  end

85 86
  def upload_mount_satisfied?
    return true unless upload_model_class_has_mounts?
87

88
    upload_model_class.uploader_options.has_key?(upload_mount)
89
  end
90
end