Intergrating Gaurdian Plugs into AshGraphql

I want implement JWT validation checking using Guardian. Is there an example I could checkout . For context this is for AshGraphQL and I want the check done only when certain actions are called not all. eg I have elixir

update :update_customer_registration do
accept [
:contact_name,
:organization_name,
:organization_abbreviation,
:location_city,
:location_state,
:customer_note
]

change fn changeset, struct ->
changeset
|> Ash.Changeset.after_action(fn changeset, customer ->
# send email to support

{:ok, customer}
end)
end
end
end
.....
policies do
policy action_type([:update_customer_registration]) do
forbid_if expr(confirmed_at == nil)
end
end

update :update_customer_registration do
accept [
:contact_name,
:organization_name,
:organization_abbreviation,
:location_city,
:location_state,
:customer_note
]

change fn changeset, struct ->
changeset
|> Ash.Changeset.after_action(fn changeset, customer ->
# send email to support

{:ok, customer}
end)
end
end
end
.....
policies do
policy action_type([:update_customer_registration]) do
forbid_if expr(confirmed_at == nil)
end
end
above is the action I want to protect by putting it behind a valid session. how do I use a Guardian plug that validates valid token to protect this action.
2 Replies
moxley
moxley2y ago
@edwinofdawn I have a solution for you. 1. Define a plug that will pass the session resource (Customer) to Ash:
def call(conn, _opts) do
resource = GuardianImpl.Plug.current_resource(conn)
Ash.PlugHelpers.set_actor(conn, session_resource)
end
def call(conn, _opts) do
resource = GuardianImpl.Plug.current_resource(conn)
Ash.PlugHelpers.set_actor(conn, session_resource)
end
2. In your resource module, add the policy:
use Ash.Resource,
data_layer: AshPostgres.DataLayer,
extensions: [AshGraphql.Resource],
authorizers: [Ash.Policy.Authorizer]

...

policies do
policy always() do
authorize_if actor_attribute_equals(:__struct__, __MODULE__)
end
end
use Ash.Resource,
data_layer: AshPostgres.DataLayer,
extensions: [AshGraphql.Resource],
authorizers: [Ash.Policy.Authorizer]

...

policies do
policy always() do
authorize_if actor_attribute_equals(:__struct__, __MODULE__)
end
end
ZachDaniel
ZachDaniel2y ago
policy action([:update_customer_registration]) do
forbid_if expr(confirmed_at == nil)
end
policy action([:update_customer_registration]) do
forbid_if expr(confirmed_at == nil)
end
To run only on specific acations you'd do it like that

Did you find this page helpful?