At this point in our app we can create a new organization from our frontend, but the organizations don't really mean anything since our messages aren't associated with an organization. So in order to separate the messages based on organization, we need to update our channels so that admins can only see messages of other admins and so that admins can only see messages associated with the API keys of their organizations.
Rather than send the public_key as data along with every message, we've required the client to connect to the socket with the key in the params, so we now have access to that key via assign/3 (docs), which we've used a number of times already.
We will start by updating our user socket. In our connect/2 function, we're assigning :public_key from our params whether the user is an anonymous user or an administrator. Note that in our anonymous client the token comes directly in the params while in our admin dashboard, it comes from our user information.
... def connect(params, socket) do user_id = params["id"] user = user_id && Repo.get(User, user_id) socket = if user do socket |> assign(:user_id, user_id) |> assign(:username, user.username) |> assign(:email, user.email) else socket |> assign(:user_id, nil) |> assign(:uuid, params["uuid"]) end |> assign(:public_key, params["public_key"]) {:ok, socket} end...Then we should update our tests to take in this new parameter.
defmodule PhoenixChat.UserSocketTest do use PhoenixChat.ChannelCase alias PhoenixChat.{Repo, User, UserSocket} test "connecting to user socket as logged-in user" do admin = Repo.insert!(%User{email: "admin@bar.com", username: "admin"}) {:ok, socket} = connect(UserSocket, %{"id" => admin.id, "public_key" => "pub_key"}) {:ok, _, socket} = subscribe_and_join(socket, "room:1", %{}) assert socket.assigns.user_id == admin.id assert socket.assigns.email == admin.email assert socket.assigns.username == admin.username end test "connecting to user socket as anonymous user" do {:ok, socket} = connect(UserSocket, %{"uuid" => 25, "public_key" => "pub_key"}) {:ok, _, socket} = subscribe_and_join(socket, "room:25", %{}) refute socket.assigns.user_id assert socket.assigns.uuid == 25 assert socket.assigns.public_key == "pub_key" endendNow it's time to match the chats from anonymous users to the admins in the organization associated with the public_key they're passing along.
Note that we are using the public key we stored in socket.assigns in the previous lesson. We use this public key to filter out the admins that do not have the same public keys from receiving
the "lobby_list" event for a particular user. This means that a user public key "foo" will only be visible to admins with public key "foo".
defmodule PhoenixChat.AdminChannel do ... def handle_info(:after_join, socket) do push socket, "presence_state", Presence.list(socket) %{assigns: assigns} = socket id = assigns.user_id || assigns.uuid LobbyList.insert(id) broadcast! socket, "lobby_list", %{uuid: id, public_key: assigns.public_key} {:ok, _} = Presence.track(socket, id, %{ online_at: inspect(System.system_time(:seconds)) }) {:noreply, socket} end def handle_out("lobby_list", payload, socket) do %{assigns: assigns} = socket if assigns.user_id && assigns.public_key == payload.public_key do push socket, "lobby_list", payload end {:noreply, socket} endendThen we need to update our admin channel tests to handle this new information.
... test "joining admin:active_users as admin" do LobbyList.insert("foo") LobbyList.insert("bar") {:ok, %{lobby_list: lobby_list}, _socket} = socket("user_id", %{user_id: 1, public_key: "pub_key"}) |> subscribe_and_join(AdminChannel, "admin:active_users") assert length(lobby_list) == 2 assert_push "lobby_list", %{uuid: 1} assert_push "presence_state", %{} assert_push "presence_diff", %{joins: %{"1" => %{}}} end test "non-admin users do not receive the 'lobby_list' event on join" do {:ok, %{lobby_list: _}, _} = socket("user_id", %{user_id: nil, uuid: 5, public_key: "pub_key"}) |> subscribe_and_join(AdminChannel, "admin:active_users") refute_push "lobby_list", %{} end...So now we're properly sorting which users will receive the lobby_list associated with a particular public_key. The next step is to ensure that each lobby_list is populated with the right anonymous users.
We want to populate the list of chatrooms in the admin's sidebar only with chatrooms/users that have the same public key. To do this, we store uuids in ETS using their public_key as the filter. Then we'll create a new function, LobbyList.lookup/1, that will allow us to retrieve all uuids in the LobbyList table with the same public_key.
Note that we set the :bag option for our :ets table so that it can store multiple values with the same key. You can read more about ETS tables and the difference between a :bag and a :set in the (docs).
defmodule PhoenixChat.LobbyList do @table __MODULE__ @doc """ Create an :ets table for this module. We set the `:bag` option so that we can store multiple values with the same keys. """ def init do opts = [:public, :named_table, {:write_concurrency, true}, {:read_concurrency, false}, :bag] :ets.new(@table, opts) end def insert(public_key, uuid) do :ets.insert(@table, {public_key, uuid}) end def delete(public_key) do :ets.delete(@table, public_key) end def lookup(public_key) do @table |> :ets.lookup(public_key) |> Enum.map(fn {_, uuid} -> uuid end) endendAnd now that we've significantly altered our ETS table, we need to change our admin_channel to use our handy new lookup/2 function.
The first change is in our join/3 function, in which we get a list of uuids of users with the same public key as the current admin and send it back to the frontend to be displayed in the sidebar.
Then, in our handle_info/2 function, we use LobbyList.insert/2, which now takes in a public_key, to keep track of rooms to be displayed to the proper admins. And finally we push the presence state of these users to track which users are online.
defmodule PhoenixChat.AdminChannel do ... def join("admin:active_users", payload, socket) do authorize(payload, fn -> send(self, :after_join) public_key = socket.assigns.public_key lobby_list = LobbyList.lookup(public_key) {:ok, %{lobby_list: lobby_list}, socket} end) end def handle_info(:after_join, socket) do %{assigns: assigns} = socket id = assigns.user_id || assigns.uuid # Keep track of rooms to be displayed to admins LobbyList.insert(assigns.public_key, id) broadcast! socket, "lobby_list", %{uuid: id, public_key: assigns.public_key} # Keep track of users that are online push socket, "presence_state", Presence.list(socket) {:ok, _} = Presence.track(socket, id, %{ online_at: inspect(System.system_time(:seconds)) }) {:noreply, socket} end ...endFinally, we need to make some minor alterations to our tests to handle the changes in our LobbyList.
...test "joining admin:active_users as admin" do LobbyList.insert("pub_key", "id1") LobbyList.insert("pub_key", "id2") ...end...Granted, we aren't doing much in the way of authentication, but we now have a functional app! Try opening an incognito window or a different browser, go to localhost:3000, and sign up. You'll see that you no longer have access to the chats from other organizations.