Skip to content

Commit 64a1a67

Browse files
authored
Add documentation for using resource's policy class to authorize custom action (#345)
1 parent 20ac650 commit 64a1a67

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/3.0/authorization.md

+26
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,32 @@ end
422422

423423
Now, Avo will use `avo_index?` instead of `index?` to manage the **Index** view authorization.
424424

425+
## Use Resource's Policy to authorize custom actions
426+
427+
It may be necessary to authorize a specific field or custom action of a resource using a policy class rather than defining the authorization logic directly within the resource class. By doing so, we can delegate control to the policy class, ensuring a cleaner and more maintainable authorization structure.
428+
429+
:::code-group
430+
```ruby [app/resources/product.rb]{8}
431+
field :amount,
432+
as: :money,
433+
currencies: %w[USD],
434+
sortable: true,
435+
filterable: true,
436+
copyable: true,
437+
# define ability to change the amount in policy class instead of doing it here
438+
disabled: -> { !@resource.authorization.authorize_action(:amount?, raise_exception: false) }
439+
```
440+
```ruby [app/policies/product_policy.rb]{2-4}
441+
# Define ability to change the amount in Product Policy
442+
def amount?
443+
user.admin?
444+
end
445+
446+
```
447+
:::
448+
449+
450+
425451
## Raise errors when policies are missing
426452

427453
The default behavior of Avo is to allow missing policies for resources silently. So, if you have a `User` model and a `Avo::Resources::User` but don't have a `UserPolicy`, Avo will not raise errors regarding missing policies and authorize that resource.

0 commit comments

Comments
 (0)