alove

alove

How to use Ash Policies when users have a different role for each organization?

So we have an application where users fundamentally belong to many organizations, and as such, they have different roles for each organization. Organizations can have child organizations as well, however is needed to organize and control their flow of data.

I want to use an ash policy to restrict the actions of users based on the role they have for the organization they are trying to perform the action on.

So I have the following table which associates a user to an organization and has their role for that organization on it

defmodule UsersOrganizations do

  use Ash.Resource,
    otp_app: :my_app,
    domain: User.Domain,
    data_layer: AshPostgres.DataLayer,
    authorizers: [Ash.Policy.Authorizer]

  attributes do
    uuid_primary_key(:id)

    attribute(:user_role, :atom,
      default: :default,
      allow_nil?: false,
      always_select?: true,
    )
  end

  relationships do
    belongs_to(:user, User, allow_nil?: false)

    belongs_to(:organization, Organization, allow_nil?: false)
  end
end

But I don’t know understand how to grab this relationship in a policy, such as this simplified situation below

defmodule MyResource do
    use Ash.Resource,
      otp_app: :my_app,
      domain: SomeResource.Domain,
      data_layer: AshPostgres.DataLayer,
      authorizers: [Ash.Policy.Authorizer]

    attributes do
     attribute :message_body, :string
    end

    relationships do
      belongs_to :sender, User
      belongs_to :organization, Organization
    end

    actions do 
      read :get_sender_information do
        #read sensitive user information, like a name and email.
     end
    end

    policies do
      policy action(:get_sender_information) do
        authorize_if #The reading user's role in the organization the message was sent in is :admin
      end
    end
 end

So my question is, what is the best approach to building out this sort of policy?

Loosely related question, is it possible to export Ash Policies as an Access Control List (ACL)?

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash

Nope, so for creating data it’s unfortunately basically the Wild West because the data doesn’t yet exist for us to query. You will need to write a custom check.

defmodule MyApp.Checks.HasRoleInOrganization do
  use Ash.Policy.SimpleCheck

  def match?(actor, %{subject: changeset}, context) do
    # run queries here to determine the result
    {:ok, false}
  end
end

Also Liked

alove

alove

For anyone who finds this page later, I used Zach’s approach above in combination with the following aggregates and calculations on my Organizations resource

  aggregates do
    list :admins, :users_join_assoc, :user_id, filter: [user_role: :admin]

    list :editors, :users_join_assoc, :user_id, filter: [user_role: :editor]

    list :guests, :users_join_assoc, :user_id, filter: [user_role: :guest]
  end

  calculations do
    calculate :actor_is_admin?, :boolean, expr(^actor(:id) in admins)

    calculate :actor_is_editor?, :boolean, expr(^actor(:id) in editors)

    calculate :actor_is_guest?, :boolean, expr(^actor(:id) in guests)
  end
chazwatkins

chazwatkins

I used a Filter check with different filter/3 clauses for each resource. Of course, I have an OrgMembership join resource that has the actor’s org role on it. It seems to work fine.

You can probably add an option to pass in the role so it can be used for any org role.

defmodule PetalProAsh.Orgs.Checks.IsOrgAdmin do
  @moduledoc false
  use Ash.Policy.FilterCheck

  alias MyApp.MyDomain.Foo
  alias PetalProAsh.Orgs.Org

  @impl true
  def describe(_options) do
    "actor is an org admin"
  end

  @impl true
  def filter(actor, %{resource: Org}, _options) when not is_nil(actor) do
    expr(exists(memberships, user_id == ^actor.id and role == :admin))
  end

  @impl true
  def filter(actor, %{resource: Foo}, _options) when not is_nil(actor) do
    expr(exists(org.memberships, user_id == ^actor.id and role == :admin))
  end

  @impl true
  def filter(_actor, _context, _options) do
    false
  end
end

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement