1
0
Fork 0
mirror of https://github.com/varvet/pundit.git synced 2022-11-09 12:30:11 -05:00

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.
This commit is contained in:
Ulysse Carion 2014-02-25 18:54:22 -08:00
parent baf681a341
commit d766d9e792
2 changed files with 20 additions and 3 deletions

View file

@ -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

View file

@ -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