Change content of a view depending on policies

My lib/example_app_web/live/product_live/index.ex file contains this code:

      <:action :let={{_id, product}}>
        <div class="sr-only">
          <.link navigate={~p"/products/#{product}"}>Show</.link>
        </div>

        <.link patch={~p"/products/#{product}/edit"}>Edit</.link>
      </:action>

      <:action :let={{id, product}}>
        <.link
          phx-click={JS.push("delete", value: %{id: product.id}) |> hide("##{id}")}
          data-confirm="Are you sure?"
        >
          Delete
        </.link>
      </:action>

The policies for the product allow edit, destroy and create only for special users:

  policies do
    policy action_type([:create, :update, :destroy]) do
      authorize_if actor_attribute_equals(:is_admin?, true)
    end

    policy action_type(:read) do
      authorize_if always()
    end
  end

How can I only display the edit and delete link in the view to users who have those rights?

Ash.can?/3 is what you’re looking for. There are a lot of options and nuances depending on the granularity and performance you need for your specific situation.

1 Like

Thanks! Is there anywhere an example of how to use it?

1 Like

In your case: Ash.can?({thing, :update}, user), for example.

1 Like