# 從 Phoenix 發送即時事件與頻道授權

> 從 Elixir 發送 Hibira 事件，並在 Phoenix controller 簽署私有與 presence 頻道訂閱。不需要額外套件：HTTP API 以 HMAC-SHA256 簽名，用 :crypto 就能完成。

Source: https://hibira.io/zh-tw/guides/phoenix

從 Elixir 發送 Hibira 事件，並在 Phoenix controller 簽署私有與 presence 頻道訂閱。不需要額外套件：HTTP API 以 HMAC-SHA256 簽名，用 :crypto 就能完成。

Package: Req

- 瀏覽器與 App 以 pusher-js 或任何 Pusher 用戶端訂閱；Phoenix 只要一個簽名的 POST 就能發送。
- 同一個 HMAC 也用來簽署頻道訂閱與 Live Chat 驗證訪客。

## 1. 安裝

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

## 2. 發送事件

```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. 簽署頻道訂閱

```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
```

## 開始之前

- 應用程式的密鑰只會在建立應用程式或輪替密鑰時顯示一次。請只放在伺服器上，不要放進瀏覽器或遊戲的建置檔。
- 私人頻道與 presence 頻道需要後端提供授權端點，用應用程式密鑰簽署訂閱，做法和 pusher-js 相同。
- presence 頻道要簽署 "socket_id:channel:channel_data"，並把 channel_data 跟 auth 一起回傳，與 Pusher 協定相同。

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