Ash Policies - How To Check Permission From DB?

I’m working on authorization, and I’m looking to implement Ash Policies. My authorization system consists of three main resources:

  1. User
  2. Permission with primary attributes (name, resource)
  3. UserPermission

My setup involves users having many permissions through UserPermission.

I’ve written a function to check if a user has permission to perform an action on a resource. However, I’m encountering an error: undefined function can?/3 (there is no such import).

Here’s the policy in the Category resource:

  policies do
    policy action_type(:read) do
      authorize_if can?(:actor, :read, :resource)
    end
  end

How can I resolve this issue, or what’s the best approach to achieve this using Ash?

Have you read the policy and authorization guides in ash?

Yes. Actually a couple of times, but I haven’t fully grasped how it works wich custom checks.

If you are looking to write custom checks, you will likely want to start with a “SimpleCheck” first.

defmodule YourApp.Checks.Can do
  use Ash.Policy.SimpleCheck

  def match?(actor, %{query: query, changeset: changeset}, _opts) do
     # for read actions, the query will be populated
     # for create/update/destroy actions, the changeset will be populated
     subject = query || changeset

     resource = subject.resource
     action = subject.action.name
    {:ok,  your_function(actor, action, resource)}
  end
end

Then you can use it in a policy, like

authorize_if YourApp.Checks.Can
1 Like

Thanks Zach.