Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend NotAuthorizedError with policy, record and query #117

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/pundit.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
require "active_support/core_ext/object/blank" require "active_support/core_ext/object/blank"


module Pundit module Pundit
class NotAuthorizedError < StandardError; end class NotAuthorizedError < StandardError
attr_accessor :policy, :record, :query
end
class NotDefinedError < StandardError; end class NotDefinedError < StandardError; end


extend ActiveSupport::Concern extend ActiveSupport::Concern
Expand Down Expand Up @@ -56,7 +58,9 @@ def authorize(record, query=nil)
query ||= params[:action].to_s + "?" query ||= params[:action].to_s + "?"
@_policy_authorized = true @_policy_authorized = true
unless policy(record).public_send(query) unless policy(record).public_send(query)
raise NotAuthorizedError, "not allowed to #{query} this #{record}" e = NotAuthorizedError.new
e.policy, e.record, e.query = policy(record), record, query
raise e, "not allowed to #{query} this #{record}"
end end
true true
end end
Expand Down
9 changes: 9 additions & 0 deletions spec/pundit_spec.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@ def destroy?
it "raises an error when the permission check fails" do it "raises an error when the permission check fails" do
expect { controller.authorize(Post.new) }.to raise_error(Pundit::NotAuthorizedError) expect { controller.authorize(Post.new) }.to raise_error(Pundit::NotAuthorizedError)
end end

it "raises an error with a policy, record and query" do
expect { controller.authorize(post, :destroy?) }.to raise_error do |error|
expect(error.policy).to eq controller.policy(post)
expect(error.record).to eq post
expect(error.query).to eq :destroy?
expect(error.message).to eq "not allowed to #{error.query} this #{error.record}"
end
end
end end


describe "#pundit_user" do describe "#pundit_user" do
Expand Down