Sha256: a9b9763f04488c6d04139f4b1847fcb1aed53e4864857ef47230d13eb56fb29d

Contents?: true

Size: 1.24 KB

Versions: 3

Compression:

Stored size: 1.24 KB

Contents

module Pundit
  module ResourceController
    extend ActiveSupport::Concern

    included do
      include ActionController::Rescue
      include AbstractController::Callbacks

      after_action :enforce_policy_use

      JSONAPI.configure do |config|
        error = Pundit::NotAuthorizedError
        unless config.exception_class_whitelist.include? error
          config.exception_class_whitelist << error
        end
      end

      rescue_from Pundit::NotAuthorizedError, with: :reject_forbidden_request
    end

    protected

    def enforce_policy_use
      return if @policy_used || response.status.in?(400...600)
      raise Pundit::AuthorizationNotPerformedError,
        "#{params[:controller]}##{params[:action]}"
    end

    def reject_forbidden_request(error)
      type = error.record.class.name.underscore.humanize(capitalize: false)
      error = JSONAPI::Error.new(
        code: JSONAPI::FORBIDDEN,
        status: :forbidden,
        title: "#{params[:action].capitalize} Forbidden",
        detail: "You don't have permission to #{params[:action]} this #{type}.",
      )

      render json: { errors: [error] }, status: 403
    end

    def context
      { current_user: current_user, policy_used: -> { @policy_used = true } }
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pundit-resources-1.1.1 lib/pundit/resource_controller.rb
pundit-resources-1.1.0 lib/pundit/resource_controller.rb
pundit-resources-1.0.1 lib/pundit/resource_controller.rb