# 从 Phoenix 发送实时事件与频道授权

> 从 Elixir 发送 Hibira 事件，并在 Phoenix controller 中签署私有和 presence 频道订阅。无需额外的包：HTTP API 使用 HMAC-SHA256 签名，用 :crypto 即可完成。

Source: https://hibira.io/zh-cn/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)
