How to expose `has_users` type aggregate in Accounts.Users?

I have created the sample ash project which created the Accounts.Users resource. This resources is guarded by the policies section. I am trying to expose a function / action called has_users in the resource. The implementation is straightforward.

    action :has_users, :boolean do
      run fn _input, _ -> Ash.exists() end
    end

But this does not work due to the filter policy. AFAIK Only current user can read their deets. I tried the below policy, but it does not seem to work. Need some help / guidance on how to handle this scenario.

    bypass action :has_users do
      description "Check if there are any users in the database"
      authorize_if always()
    end

The intention - If there are no users in the db, display a “create a new admin user” page, else display a sign-in page. This is for initial “admin” user setup.

    action :has_users, :boolean do
      run fn _input, _ -> Ash.exists() end
    end

The problem is subtle. That is calling a read action when doing Ash.exists, but none is specified, so it uses the primary read action. Your policy allows the user to call :has_users, but the Ash.exists that it calls is still having policies applied (as if it was a non-signed-in-user).

You likely want this:

    action :has_users, :boolean do
      run fn _input, _ -> Ash.exists(authorize?: false) end
    end

Thanks for the reply. This is exactly what I was looking for.

2 Likes

Does Ash inject current resource in Ash.exists() automatically when called in an action run?

No, my assumption was that that was pseudo code.

1 Like

Yeah it indeed was a psuedo-code and we need to pass in the module name.

Thanks for all the help !

1 Like