Skip to content

Commit

Permalink
Add reason to Pundit::NotAuthorizedError
Browse files Browse the repository at this point in the history
  • Loading branch information
holyketzer committed Dec 7, 2019
1 parent d89a572 commit 973b63b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,37 @@ en:
Of course, this is just an example. Pundit is agnostic as to how you implement
your error messaging.
## Deep error messages customisation
If you have different authorization deny reasons you want to inform user with descriptive message then:
In your policy class raise `Pundit::NotAuthorizedError` with custom error message or I18n key in `reason` argument:

```ruby
class ProjectPolicy < ApplicationPolicy
def create?
if user.has_paid_subscription?
if user.project_limit_reached?
raise Pundit::NotAuthorizedError, reason: 'user.project_limit_reached'
else
true
end
else
raise Pundit::NotAuthorizedError, reason: 'user.paid_subscription_required'
end
end
end
```

Then you can get this error message in exception handler:
```ruby
rescue_from Pundit::NotAuthorizedError do |e|
message = e.reason ? I18n.t("errors.#{e.reason}") : e.message
flash[:error] = message, scope: "pundit", default: :default
redirect_to(request.referrer || root_path)
end
```

## Manually retrieving policies and scopes

Sometimes you want to retrieve a policy for a record outside the controller or
Expand Down
3 changes: 2 additions & 1 deletion lib/pundit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ module Generators; end

# Error that will be raised when authorization has failed
class NotAuthorizedError < Error
attr_reader :query, :record, :policy
attr_reader :query, :record, :policy, :reason

def initialize(options = {})
if options.is_a? String
Expand All @@ -31,6 +31,7 @@ def initialize(options = {})
@query = options[:query]
@record = options[:record]
@policy = options[:policy]
@reason = options[:reason]

message = options.fetch(:message) { "not allowed to #{query} this #{record.class}" }
end
Expand Down

0 comments on commit 973b63b

Please sign in to comment.