# Realtime events and channel auth from Phoenix

> Publish Hibira events from Elixir and sign private and presence channel subscriptions in a Phoenix controller. There is no package to add: the HTTP API is signed with HMAC-SHA256, which :crypto does.

Source: https://hibira.io/guides/phoenix

Publish Hibira events from Elixir and sign private and presence channel subscriptions in a Phoenix controller. There is no package to add: the HTTP API is signed with HMAC-SHA256, which :crypto does.

Package: Req

- Browsers and apps subscribe with pusher-js or any Pusher client; Phoenix publishes with one signed POST.
- The same HMAC signs channel subscriptions and Live Chat verified visitors.

## 1. Install

```elixir
# mix.exs
{:req, "~> 0.5"}
```

## 2. Publish events

```elixir
defmodule MyApp.Hibira do
  @host "https://ws.hibira.io"
  defp env(k), do: System.fetch_env!(k)
  defp hmac(data), do: :crypto.mac(:hmac, :sha256, env("HIBIRA_SECRET"), data) |> Base.encode16(case: :lower)

  def trigger(channels, event, data) do
    path = "/apps/#{env("HIBIRA_APP_ID")}/events"
    body = Jason.encode!(%{name: event, channels: channels, data: Jason.encode!(data)})
    query = [
      auth_key: env("HIBIRA_KEY"),
      auth_timestamp: System.os_time(:second),
      auth_version: "1.0",
      body_md5: :crypto.hash(:md5, body) |> Base.encode16(case: :lower)
    ]
    signed = query |> Enum.sort() |> Enum.map_join("&", fn {k, v} -> "#{k}=#{v}" end)
    Req.post!(@host <> path, body: body, headers: [{"content-type", "application/json"}],
      params: query ++ [auth_signature: hmac("POST\n#{path}\n#{signed}")])
  end

  # The body of POST /pusher/auth, from socket_id and channel_name.
  def auth(socket_id, channel), do: %{auth: "#{env("HIBIRA_KEY")}:#{hmac("#{socket_id}:#{channel}")}"}
end
```

## 3. Sign channel subscriptions

```elixir
# router.ex: post "/pusher/auth", PusherController, :auth
def auth(conn, %{"socket_id" => socket_id, "channel_name" => "private-user-" <> id = channel}) do
  if to_string(conn.assigns.current_user.id) == id,
    do: json(conn, MyApp.Hibira.auth(socket_id, channel)),
    else: send_resp(conn, 403, "")
end
```

## Before you start

- The app secret is shown only once, when you create the app or rotate its secret. Keep it on your server, never in a browser or game build.
- Private and presence channels need an auth endpoint on your backend that signs subscriptions with the app secret, as with pusher-js.
- For presence channels, sign "socket_id:channel:channel_data" and return channel_data with the auth, as in the Pusher protocol.

- [Hex: req](https://hex.pm/packages/req)
