Skip to content

Commit

Permalink
improvement: allow policy conditions to be applied inside their block
Browse files Browse the repository at this point in the history
```elixir
policy do
  condition [...]
  authorize_if ...
end
```
  • Loading branch information
zachdaniel committed Jul 22, 2024
1 parent 3c2f512 commit 34d6f22
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
4 changes: 2 additions & 2 deletions lib/ash/policy/authorizer/authorizer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ defmodule Ash.Policy.Authorizer do
"""
]
],
args: [:condition],
args: [{:optional, :condition}],
target: Ash.Policy.Policy,
no_depend_modules: [:condition],
transform: {Ash.Policy.Policy, :transform, []},
Expand Down Expand Up @@ -274,7 +274,7 @@ defmodule Ash.Policy.Authorizer do
"A check or list of checks that must be true in order for this field policy to apply. If not specified, it always applies."
]
],
args: [:fields, {:optional, :condition, {Ash.Policy.Check.Static, result: true}}],
args: [:fields, {:optional, :condition}],
target: Ash.Policy.FieldPolicy,
transform: {Ash.Policy.FieldPolicy, :transform, []},
entities: [
Expand Down
9 changes: 8 additions & 1 deletion lib/ash/policy/field_policy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,18 @@ defmodule Ash.Policy.FieldPolicy do
if Enum.empty?(field_policy.policies) do
{:error, "Field policies must have at least one check."}
else
field_policy =
if field_policy.condition in [nil, []] do
%{field_policy | condition: [{Ash.Policy.Check.Static, result: true}]}
else
field_policy
end

{:ok,
%{
field_policy
| policies: Enum.map(field_policy.policies, &set_field_policy_opt/1),
condition: Enum.map(List.wrap(field_policy.condition || []), &set_field_policy_opt/1)
condition: Enum.map(List.wrap(field_policy.condition), &set_field_policy_opt/1)
}}
end
end
Expand Down
6 changes: 5 additions & 1 deletion lib/ash/policy/policy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ defmodule Ash.Policy.Policy do
if Enum.empty?(policy.policies) do
{:error, "Policies must have at least one check."}
else
{:ok, policy}
if policy.condition in [nil, []] do
{:ok, %{policy | condition: [{Ash.Policy.Check.Static, result: true}]}}
else
{:ok, policy}
end
end
end

Expand Down
3 changes: 2 additions & 1 deletion test/actions/aggregate_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ defmodule Ash.Test.Actions.AggregateTest do
end

policies do
policy always() do
policy do
condition(always())
authorize_if expr(public == true)
end
end
Expand Down

0 comments on commit 34d6f22

Please sign in to comment.