View Source ChannelHandler.Handler behaviour (channel_handler v0.6.3)

A module implementing an event handler.

You can use ChannelHandler.Handler to import phoenix functions like push or reply, and the plug macro for handler-level plugs.

Link to this section Summary

Callbacks

Hanndles a delegated event.

Functions

Registers a plug for the current module.

Defines a module plug.

Link to this section Callbacks

Link to this callback

handle_in(t, term, map, t)

View Source
@callback handle_in(String.t(), term(), map(), Phoenix.Socket.t()) ::
  Phoenix.Channel.reply()

Hanndles a delegated event.

This function is called when using delegate in a router.

defmodule MyRouter do
  use ChannelHandler.Router

  delegate "posts:", PostsHandler
end

defmodule PostsHandler do
  use ChannelHandler.Handler

  def handle_in("create", payload, context, socket) do
    # ...
  end
end

Link to this section Functions

Registers a plug for the current module.

defmodule MyHandler do
  use ChannelHandler.Handler

  plug &check_permissions/4, [:create]

  def create(_payload, context, socket) do
    # Authorized users only
  end

  def check_permissions(socket, payload, context, opts) do
    permissions = opts[:permissions] || []
    user_permissions = socket.assigns.current_user.permissions

    if Enum.any?(permissions, &Enum.member?(user_permissions, &1)) do
      {:cont, socket, payload, context}
    else
      {:reply, {:error, "Unauthorized"}, socket}
    end
  end
end

Plugs support guards, and can be used to filter events or actions.

plug &do_something/4 when action in [:create, :update]

Due to operator precedence in Elixir, if the second argument is a keyword list, we need to wrap the keyword in [...] when using when:

plug &authenticate/4, [usernames:  ["jose", "eric", "sonny"]] when action in [:create, :update]
plug &authenticate/4, [usernames: ["admin"]] when not action in [:create]

The first plug will run when the action is :create or :update. The second will always run except when the action is :create.

Those guards work like regular Elixir guards and the only variables accessible in the guard are the action as an atom and the event as a string.

Link to this macro

plug(plug, opts)

View Source (macro)

Defines a module plug.

For more information about plugs, check plug/1.