Sha256: 69f07d4b4b66990d0e393a852e4a2f733eb8310d8cb5f92744c9e453afde9f50

Contents?: true

Size: 1.61 KB

Versions: 6

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

require 'active_support/concern'
require_relative 'json_rendering'

module Uploader
  module Authorization
    extend ActiveSupport::Concern

    included do
      include JsonRendering
      include ActionController::Rescue

      rescue_from Uploader::AccessDenied, with: :dispatch_uploader_access_denied
    end

    protected

    # Authorize the action and subject. Available in the controller
    def authorized?(action, subject = nil)
      uploader_authorization.authorized?(action, subject)
    end

    # Authorize the action and subject. Available in the controller.
    # If the action is not allowd, it raises an Uploader::AccessDenied exception.
    def authorize!(action, subject = nil)
      return if authorized?(action, subject)

      raise Uploader::AccessDenied.new(current_uploader_user, action, subject)
    end

    # Retrieve or instantiate the authorization instance for this resource
    def uploader_authorization
      @uploader_authorization ||= uploader_authorization_adapter.new(current_uploader_user)
    end

    # Returns the class to be used as the authorization adapter
    def uploader_authorization_adapter
      adapter = Uploader.authorization_adapter

      if adapter.is_a? String
        ActiveSupport::Dependencies.constantize(adapter)
      else
        adapter
      end
    end

    def dispatch_uploader_access_denied(exception)
      render_json({ message: exception.message }, 403)
    end

    def current_uploader_user
      return if Uploader.current_user_proc.nil?

      @current_uploader_user ||= Uploader.current_user_proc.call(request)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rails-uploader-0.5.6 lib/uploader/authorization.rb
rails-uploader-0.5.5 lib/uploader/authorization.rb
rails-uploader-0.5.4 lib/uploader/authorization.rb
rails-uploader-0.5.3 lib/uploader/authorization.rb
rails-uploader-0.5.2 lib/uploader/authorization.rb
rails-uploader-0.5.1 lib/uploader/authorization.rb