Skip to content

Commit

Permalink
let authorize! return the policy record (#287)
Browse files Browse the repository at this point in the history
Co-authored-by: Vladimir Dementyev <[email protected]>
  • Loading branch information
sedubois and palkan authored Jan 29, 2025
1 parent 2fe7fc9 commit 62b3bc8
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## master


- Let authorize! return the policy record ([@sedubois][])

- Enable `allowance_to` as a helper method by default ([@stephannv][])

## 0.7.3 (2024-12-18)
Expand Down
2 changes: 2 additions & 0 deletions lib/action_policy/behaviour.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,13 @@ def self.included(base)
# Policy is inferred from record
# (unless explicitly specified through `with` option).
#
# @return the policy record
# Raises `ActionPolicy::Unauthorized` if check failed.
def authorize!(record = :__undef__, to:, **options)
policy = lookup_authorization_policy(record, **options)

Authorizer.call(policy, authorization_rule_for(policy, to))
policy.record
end

# Checks that an activity is allowed for the current context (e.g. user).
Expand Down
4 changes: 3 additions & 1 deletion lib/action_policy/rails/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,15 @@ module Controller
# If record is not provided, tries to infer the resource class
# from controller name (i.e. `controller_name.classify.safe_constantize`).
#
# @return the policy record
# Raises `ActionPolicy::Unauthorized` if check failed.
def authorize!(record = :__undef__, to: nil, **options)
to ||= :"#{action_name}?"

super
policy_record = super

self.authorize_count += 1
policy_record
end

# Tries to infer the resource class from controller name
Expand Down
3 changes: 1 addition & 2 deletions test/action_policy/rails/controllers_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ def current_user
private

def set_user
@user = User.new(params[:target])
authorize! @user
@user = authorize! User.new(params[:target])
end
end

Expand Down

0 comments on commit 62b3bc8

Please sign in to comment.