Created
May 29, 2020 03:12
-
-
Save zachdaniel/a35c217c1572d4d56a34da91b4d75620 to your computer and use it in GitHub Desktop.
Example resource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AshExample.Representative do | |
use Ash.Resource, type: "representative", name: "representatives" | |
use AshPostgres, repo: AshExample.Repo | |
use AshJsonApi.JsonApiResource | |
use AshGraphql.GraphqlResource | |
use AshPolicyAccess | |
policies do | |
user_is_admin? = actor_attribute_equals(:admin, true) | |
user_is_manager? = actor_attribute_equals(:manager, true) | |
user_in_matching_group? = actor_attribute_matches_record(:group, :group) | |
admin_only_record? = attribute_equals(:admin_only, true) | |
record_is_active? = attribute_equals(:active, true) | |
policy action_type(:read) do | |
access_type(:auto_filter) | |
authorize_if(user_in_matching_group?) | |
authorize_if(user_is_admin?) | |
forbid_if(admin_only_record?) | |
forbid_unless(user_is_manager?) | |
authorize_if(record_is_active?) | |
end | |
policy action_type(:create) do | |
authorize_if(user_is_admin?) | |
# Nested policies don't pass the entire flow | |
# But they *need to pass as a group* for the | |
# flow to continue | |
policy changing(:admin_only) do | |
authorize_if(user_is_admin?) | |
end | |
policy setting(:owner) do | |
authorize_if(user_is_admin?) | |
forbid_unless(relationship_unset(:owner)) | |
authorize_if(setting_relationship_to_self(:owner)) | |
end | |
end | |
end | |
attributes do | |
attribute :first_name, :string | |
attribute :last_name, :string | |
attribute :admin_only, :boolean, allow_nil?: false, default: {:constant, false} | |
attribute :active, :boolean, allow_nil?: false, default: {:constant, true} | |
end | |
json_api do | |
fields [:first_name, :last_name, :owner, :tickets, :representative_tickets] | |
routes do | |
get :default | |
post :default | |
end | |
end | |
actions do | |
read :default | |
create :default | |
end | |
relationships do | |
belongs_to :owner, AshExample.Owner | |
has_many :tickets, AshExample.Ticket, destination_field: :representative_id | |
has_many :representative_tickets, AshExample.Ticket, destination_field: :representative_id | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment