VoileWeb.Auth.LiveHelpers (Voile v0.1.31)

Copy Markdown View Source

Helper functions for authorization in Phoenix LiveView.

Summary

Functions

Assign permissions to socket for use in templates. Useful when you need to check multiple permissions.

Authorize a user in a LiveView action. Returns {:ok, socket} or {:error, reason}.

Authorize a user and raise an error if unauthorized.

Check if the current user in the socket has a permission.

Functions

assign_permissions(socket, collection_id)

Assign permissions to socket for use in templates. Useful when you need to check multiple permissions.

Examples

def mount(_params, _session, socket) do
  socket = assign_permissions(socket, @collection.id)
  {:ok, socket}
end

# In template:
<%= if @permissions.can_edit do %>
  <.button>Edit</.button>
<% end %>

authorize(socket, permission, opts \\ [])

Authorize a user in a LiveView action. Returns {:ok, socket} or {:error, reason}.

Examples

def handle_event("delete", _params, socket) do
  case authorize(socket, "collections.delete", scope: {:collection, @collection.id}) do
    {:ok, socket} ->
      # ... perform deletion
      {:noreply, socket}

    {:error, reason} ->
      {:noreply, put_flash(socket, :error, reason)}
  end
end

authorize!(socket, permission, opts \\ [])

Authorize a user and raise an error if unauthorized.

This function is typically used in mount/3 callbacks. It will redirect the user with a flash message if they don't have permission, rather than raising an error.

Examples

def mount(%{"id" => id}, _session, socket) do
  authorize!(socket, "collections.read", scope: {:collection, id})
  # ... rest of mount
end

can?(assigns_or_socket, permission, opts \\ [])

Check if the current user in the socket has a permission.

Examples

<%= if can?(assigns, "collections.update", scope: {:collection, @collection.id}) do %>
  <.button>Edit</.button>
<% end %>