Relationship-Based Policies

I’m building an app with a many-to-many between Users and Teams via a TeamMember join resource and need guidance writing two related authorization policies: 1. TeamMember Resource Policy In team_member.ex I’ve defined:
read :list_team_members do
prepare build(load: :user)
end
read :list_team_members do
prepare build(load: :user)
end
I need to allow reading a TeamMember record only if the actor is also a member of the same team. These are the relationships defined in this resource:
relationships do
belongs_to :user, Noted.Accounts.User do
public? true
allow_nil? false
end

belongs_to :team, Noted.Workspace.Team do
public? true
allow_nil? false
end
end
relationships do
belongs_to :user, Noted.Accounts.User do
public? true
allow_nil? false
end

belongs_to :team, Noted.Workspace.Team do
public? true
allow_nil? false
end
end
2. User Resource Policy Since the above action loads the :user relationship, I also need a similar rule in user.ex. How to allow reading another user only when the actor and the target user share the same team? This is the relationship defined in my User resource:
relationships do
many_to_many :teams, Noted.Workspace.Team do
through Noted.Workspace.TeamMember
join_relationship :team_membership
end
end
relationships do
many_to_many :teams, Noted.Workspace.Team do
through Noted.Workspace.TeamMember
join_relationship :team_membership
end
end
Solution:
You can use relates_to_actor_via
Jump to solution
2 Replies
Solution
allenwyma
allenwyma6d ago
You can use relates_to_actor_via
Joan Gavelán
Joan GavelánOP5d ago
After trying many different ways to do it, I finally got it to work like this
authorize_if relates_to_actor_via([:teams, :users])
authorize_if relates_to_actor_via([:teams, :users])
Works for both policies Thanks

Did you find this page helpful?