2020-06-22 15:26:47 +12:00
|
|
|
defmodule Ash.Test.Authorizer do
|
2024-04-08 00:01:46 +12:00
|
|
|
@moduledoc false
|
2020-06-22 15:26:47 +12:00
|
|
|
@behaviour Ash.Authorizer
|
|
|
|
|
2021-01-29 08:47:59 +13:00
|
|
|
use Agent
|
2020-06-22 15:26:47 +12:00
|
|
|
|
2021-01-29 08:47:59 +13:00
|
|
|
def start_link(opts) do
|
|
|
|
Agent.start_link(
|
|
|
|
fn ->
|
|
|
|
%{
|
2024-01-19 18:05:42 +13:00
|
|
|
strict_check_result: maybe_forbidden(opts[:strict_check] || :authorized),
|
|
|
|
check_result: maybe_forbidden(opts[:check] || :authorized),
|
2021-01-29 08:47:59 +13:00
|
|
|
strict_check_context: opts[:strict_check_context]
|
|
|
|
}
|
|
|
|
end,
|
|
|
|
name: __MODULE__
|
|
|
|
)
|
2020-06-22 15:26:47 +12:00
|
|
|
end
|
|
|
|
|
2021-01-29 08:47:59 +13:00
|
|
|
defp maybe_forbidden(:forbidden), do: {:error, Ash.Error.Forbidden.exception([])}
|
|
|
|
defp maybe_forbidden(other), do: other
|
|
|
|
|
2024-08-14 03:16:00 +12:00
|
|
|
def initial_state(actor, _b, _c, _d) do
|
|
|
|
%{actor: actor}
|
|
|
|
end
|
|
|
|
|
2021-01-29 08:47:59 +13:00
|
|
|
def strict_check_context(_), do: get(:strict_check_context, [])
|
|
|
|
|
2024-08-14 03:16:00 +12:00
|
|
|
def strict_check(state, _) do
|
|
|
|
case get(:strict_check_result, :authorized) do
|
|
|
|
:authorized_if_actor ->
|
|
|
|
if state.actor do
|
|
|
|
:authorized |> continue(state) |> wrap_authorized(state)
|
|
|
|
else
|
|
|
|
:forbidden |> continue(state) |> wrap_authorized(state)
|
|
|
|
end
|
|
|
|
|
|
|
|
other ->
|
|
|
|
other |> continue(state) |> wrap_authorized(state)
|
|
|
|
end
|
|
|
|
end
|
2021-01-29 08:47:59 +13:00
|
|
|
|
2020-06-22 15:26:47 +12:00
|
|
|
def check_context(_), do: []
|
|
|
|
|
2021-01-29 08:47:59 +13:00
|
|
|
def check(state, _), do: get(:check_result, :authorized) |> continue(state)
|
|
|
|
|
|
|
|
defp continue(:continue, state), do: {:continue, state}
|
|
|
|
defp continue(other, _), do: other
|
|
|
|
|
2023-03-11 07:28:16 +13:00
|
|
|
defp wrap_authorized(:authorized, state), do: {:authorized, state}
|
|
|
|
defp wrap_authorized(other, _), do: other
|
|
|
|
|
2021-01-29 08:47:59 +13:00
|
|
|
defp get(key, default) do
|
|
|
|
Agent.get(__MODULE__, &Map.get(&1, key)) || default
|
|
|
|
catch
|
|
|
|
:exit, _ ->
|
|
|
|
default
|
2020-06-22 15:26:47 +12:00
|
|
|
end
|
|
|
|
end
|