Skip to content

Commit

Permalink
Better error message if authorize passed a Class
Browse files Browse the repository at this point in the history
In some cases you may want to authorize actions against a class not an
instance of that class. If authorization fails when a class is passed to
authorize the error message is unhelpful. For example

    not allowed to index? Class

This PR checks if an instance or class was passed and provides more
informative error message in the case of a class. The error
message for an instance being passed remains the same.

For a concrete example of class being passed see jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3251c6589d31bc931ee3a98c5c47e16eedd82b97/lib/jsonapi/authorization/default_pundit_authorizer.rb#L28-L31
  • Loading branch information
mrloop committed Mar 12, 2020
1 parent bb09157 commit 2bda793
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/pundit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ def initialize(options = {})
@policy = options[:policy]
@reason = options[:reason]

message = options.fetch(:message) { "not allowed to #{query} this #{record.class}" }
name = if record.is_a?(Class)
record.name
else
"this #{record.class.name}"
end

message = options.fetch(:message) { "not allowed to #{query} #{name}" }
end

super(message)
Expand Down
9 changes: 9 additions & 0 deletions spec/pundit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,15 @@
it "raises an error with a invalid policy constructor" do
expect { controller.authorize(wiki, :destroy?) }.to raise_error(Pundit::InvalidConstructorError)
end

it "raises an error with class name when passed Class" do
expect { controller.authorize(Post, :index?) }.to raise_error(Pundit::NotAuthorizedError, "not allowed to index? Post")
end

it "raises an error with class name when passed record" do
expect { controller.authorize(post, :destroy?) }.to raise_error(Pundit::NotAuthorizedError, "not allowed to destroy? this Post")
end

end

describe "#skip_authorization" do
Expand Down
4 changes: 4 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ def show?
true
end

def index?
false
end

def permitted_attributes
if post.user == user
%i[title votes]
Expand Down

0 comments on commit 2bda793

Please sign in to comment.