# Phoenix에서 실시간 이벤트와 채널 인증

> Elixir에서 Hibira 이벤트를 보내고 Phoenix 컨트롤러에서 비공개·presence 채널 구독에 서명합니다. 추가할 패키지는 없습니다: HTTP API는 HMAC-SHA256으로 서명되며 :crypto로 처리할 수 있습니다.

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

Elixir에서 Hibira 이벤트를 보내고 Phoenix 컨트롤러에서 비공개·presence 채널 구독에 서명합니다. 추가할 패키지는 없습니다: HTTP API는 HMAC-SHA256으로 서명되며 :crypto로 처리할 수 있습니다.

Package: Req

- 브라우저와 앱은 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
```

## 시작하기 전에

- 앱 시크릿은 앱을 만들거나 시크릿을 교체할 때 한 번만 표시됩니다. 서버에만 두고, 브라우저나 게임 빌드에는 절대 넣지 마세요.
- 프라이빗 채널과 프레즌스 채널에는 pusher-js와 마찬가지로, 앱 시크릿으로 구독에 서명하는 인증 엔드포인트가 백엔드에 필요합니다.
- presence 채널은 "socket_id:channel:channel_data"에 서명하고, Pusher 프로토콜처럼 channel_data를 auth와 함께 반환합니다.

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