From d766d9e7922fbbec048e83afddfe6f5b4019f85a Mon Sep 17 00:00:00 2001 From: Ulysse Carion Date: Tue, 25 Feb 2014 18:54:22 -0800 Subject: [PATCH] Add #query, #record, and #policy properties to Pundit::NotAuthorizedError. Exceptions raised by #authorize now provide the query (e.g. 'create?') and record (e.g. an instance of 'Post') that caused the exception to be raised, as well as the relevant policy (e.g. an instance of 'PostPolicy'). NotAuthorizedError is modified to continue to inherit from StandardError, but now also has attr_accessor values for :query, :record, and :policy. --- lib/pundit.rb | 15 ++++++++++++--- spec/pundit_spec.rb | 8 ++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/pundit.rb b/lib/pundit.rb index cf0d8ba..4d6ab5f 100644 --- a/lib/pundit.rb +++ b/lib/pundit.rb @@ -5,7 +5,10 @@ require "active_support/core_ext/string/inflections" require "active_support/core_ext/object/blank" module Pundit - class NotAuthorizedError < StandardError; end + class NotAuthorizedError < StandardError + attr_accessor :query, :record, :policy + end + class NotDefinedError < StandardError; end extend ActiveSupport::Concern @@ -55,9 +58,15 @@ module Pundit def authorize(record, query=nil) query ||= params[:action].to_s + "?" @_policy_authorized = true - unless policy(record).public_send(query) - raise NotAuthorizedError, "not allowed to #{query} this #{record}" + + policy = policy(record) + unless policy.public_send(query) + error = NotAuthorizedError.new("not allowed to #{query} this #{record}") + error.query, error.record, error.policy = query, record, policy + + raise error end + true end diff --git a/spec/pundit_spec.rb b/spec/pundit_spec.rb index 93c3cf9..459b128 100644 --- a/spec/pundit_spec.rb +++ b/spec/pundit_spec.rb @@ -224,6 +224,14 @@ describe Pundit do it "raises an error when the permission check fails" do expect { controller.authorize(Post.new) }.to raise_error(Pundit::NotAuthorizedError) end + + it "raises an error with a query and action" do + expect { controller.authorize(post, :destroy?) }.to raise_error do |error| + expect(error.query).to eq :destroy? + expect(error.record).to eq post + expect(error.policy).to eq controller.policy(post) + end + end end describe "#pundit_user" do