{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/routing-messages-using-api-keys","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Routing Messages Using API Keys\",\n  \"order\": 48,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Routing Messages Using API Keys\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Update UserSocket\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Broadcast by public_key\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Populate lobby_list by public_key\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"Rather than send the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assign/3\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.Socket.html#assign/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \", which we've used a number of times already.\"), mdx(\"h2\", null, \"Update UserSocket\"), mdx(\"p\", null, \"We will start by updating our user socket. In our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"connect/2\"), \" function, we're assigning \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  def connect(params, socket) do\\n    user_id = params[\\\"id\\\"]\\n    user = user_id && Repo.get(User, user_id)\\n\\n    socket = if user do\\n        socket\\n        |> assign(:user_id, user_id)\\n        |> assign(:username, user.username)\\n        |> assign(:email, user.email)\\n      else\\n        socket\\n        |> assign(:user_id, nil)\\n        |> assign(:uuid, params[\\\"uuid\\\"])\\n      end\\n        |> assign(:public_key, params[\\\"public_key\\\"])\\n\\n    {:ok, socket}\\n  end\\n...\\n\")), mdx(\"p\", null, \"Then we should update our tests to take in this new parameter.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserSocketTest do\\n  use PhoenixChat.ChannelCase\\n\\n  alias PhoenixChat.{Repo, User, UserSocket}\\n\\n  test \\\"connecting to user socket as logged-in user\\\" do\\n    admin = Repo.insert!(%User{email: \\\"admin@bar.com\\\", username: \\\"admin\\\"})\\n\\n    {:ok, socket} = connect(UserSocket, %{\\\"id\\\" => admin.id, \\\"public_key\\\" => \\\"pub_key\\\"})\\n    {:ok, _, socket} = subscribe_and_join(socket, \\\"room:1\\\", %{})\\n\\n    assert socket.assigns.user_id == admin.id\\n    assert socket.assigns.email == admin.email\\n    assert socket.assigns.username == admin.username\\n  end\\n\\n  test \\\"connecting to user socket as anonymous user\\\" do\\n    {:ok, socket} = connect(UserSocket, %{\\\"uuid\\\" => 25, \\\"public_key\\\" => \\\"pub_key\\\"})\\n    {:ok, _, socket} = subscribe_and_join(socket, \\\"room:25\\\", %{})\\n\\n    refute socket.assigns.user_id\\n    assert socket.assigns.uuid == 25\\n    assert socket.assigns.public_key == \\\"pub_key\\\"\\n  end\\nend\\n\")), mdx(\"h2\", null, \"Broadcast by public_key\"), mdx(\"p\", null, \"Now it's time to match the chats from anonymous users to the admins in the organization associated with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \" they're passing along.\"), mdx(\"p\", null, \"Note that we are using the public key we stored in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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\\nthe \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"\\\"lobby_list\\\"\"), \" event for a particular user. This means that a user public key \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"\\\"foo\\\"\"), \" will only be visible to admins with public key \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"\\\"foo\\\"\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  ...\\n\\n  def handle_info(:after_join, socket) do\\n    push socket, \\\"presence_state\\\", Presence.list(socket)\\n    %{assigns: assigns} = socket\\n    id = assigns.user_id || assigns.uuid\\n    LobbyList.insert(id)\\n    broadcast! socket, \\\"lobby_list\\\", %{uuid: id, public_key: assigns.public_key}\\n    {:ok, _} = Presence.track(socket, id, %{\\n        online_at: inspect(System.system_time(:seconds))\\n      })\\n    {:noreply, socket}\\n  end\\n\\n  def handle_out(\\\"lobby_list\\\", payload, socket) do\\n    %{assigns: assigns} = socket\\n    if assigns.user_id && assigns.public_key == payload.public_key do\\n      push socket, \\\"lobby_list\\\", payload\\n    end\\n    {:noreply, socket}\\n  end\\nend\\n\")), mdx(\"p\", null, \"Then we need to update our admin channel tests to handle this new information.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  test \\\"joining admin:active_users as admin\\\" do\\n    LobbyList.insert(\\\"foo\\\")\\n    LobbyList.insert(\\\"bar\\\")\\n\\n    {:ok, %{lobby_list: lobby_list}, _socket} =\\n      socket(\\\"user_id\\\", %{user_id: 1, public_key: \\\"pub_key\\\"})\\n      |> subscribe_and_join(AdminChannel, \\\"admin:active_users\\\")\\n\\n    assert length(lobby_list) == 2\\n    assert_push \\\"lobby_list\\\", %{uuid: 1}\\n    assert_push \\\"presence_state\\\", %{}\\n    assert_push \\\"presence_diff\\\", %{joins: %{\\\"1\\\" => %{}}}\\n  end\\n\\n  test \\\"non-admin users do not receive the 'lobby_list' event on join\\\" do\\n    {:ok, %{lobby_list: _}, _} =\\n      socket(\\\"user_id\\\", %{user_id: nil, uuid: 5, public_key: \\\"pub_key\\\"})\\n      |> subscribe_and_join(AdminChannel, \\\"admin:active_users\\\")\\n\\n    refute_push \\\"lobby_list\\\", %{}\\n  end\\n...\\n\")), mdx(\"p\", null, \"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.\"), mdx(\"h2\", null, \"Populate lobby_list by public_key\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuids\"), \" in ETS using their \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"public_key\"), \" as the filter. Then we'll create a new function, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"LobbyList.lookup/1\"), \", that will allow us to retrieve all uuids in the LobbyList table with the same public_key.\"), mdx(\"p\", null, \"Note that we set the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":bag\"), \" and a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":set\"), \" in the \", mdx(\"a\", {\n    \"href\": \"http://erlang.org/doc/man/ets.html\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.LobbyList do\\n\\n  @table __MODULE__\\n\\n  @doc \\\"\\\"\\\"\\n  Create an :ets table for this module. We set the `:bag` option so that we can\\n  store multiple values with the same keys.\\n  \\\"\\\"\\\"\\n  def init do\\n    opts = [:public, :named_table, {:write_concurrency, true}, {:read_concurrency, false}, :bag]\\n    :ets.new(@table, opts)\\n  end\\n\\n  def insert(public_key, uuid) do\\n    :ets.insert(@table, {public_key, uuid})\\n  end\\n\\n  def delete(public_key) do\\n    :ets.delete(@table, public_key)\\n  end\\n\\n  def lookup(public_key) do\\n    @table\\n    |> :ets.lookup(public_key)\\n    |> Enum.map(fn {_, uuid} -> uuid end)\\n  end\\nend\\n\")), mdx(\"p\", null, \"And now that we've significantly altered our ETS table, we need to change our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"admin_channel\"), \" to use our handy new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lookup/2\"), \" function.\"), mdx(\"p\", null, \"The first change is in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"Then, in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_info/2\"), \" function, we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"LobbyList.insert/2\"), \", which now takes in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  ...\\n\\n  def join(\\\"admin:active_users\\\", payload, socket) do\\n    authorize(payload, fn ->\\n      send(self, :after_join)\\n\\n      public_key = socket.assigns.public_key\\n      lobby_list = LobbyList.lookup(public_key)\\n      {:ok, %{lobby_list: lobby_list}, socket}\\n    end)\\n  end\\n\\n  def handle_info(:after_join, socket) do\\n    %{assigns: assigns} = socket\\n    id = assigns.user_id || assigns.uuid\\n\\n    # Keep track of rooms to be displayed to admins\\n    LobbyList.insert(assigns.public_key, id)\\n    broadcast! socket, \\\"lobby_list\\\", %{uuid: id, public_key: assigns.public_key}\\n\\n    # Keep track of users that are online\\n    push socket, \\\"presence_state\\\", Presence.list(socket)\\n    {:ok, _} = Presence.track(socket, id, %{\\n        online_at: inspect(System.system_time(:seconds))\\n      })\\n    {:noreply, socket}\\n  end\\n  ...\\n\\nend\\n\")), mdx(\"p\", null, \"Finally, we need to make some minor alterations to our tests to handle the changes in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"LobbyList\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\ntest \\\"joining admin:active_users as admin\\\" do\\n  LobbyList.insert(\\\"pub_key\\\", \\\"id1\\\")\\n  LobbyList.insert(\\\"pub_key\\\", \\\"id2\\\")\\n  ...\\n\\nend\\n...\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:3000\"), \", and sign up. You'll see that you no longer have access to the chats from other organizations.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Routing Messages Using API Keys Update UserSocket Broadcast by public_key Populate lobby_list by public_key At this point in our app we can…","frontmatter":{"title":"Routing Messages Using API Keys","order":48,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"routing-messages-using-api-keys","prevNode":{"frontmatter":{"title":"Pass API Key from Frontend","active":true,"free":false,"order":47,"tech":["react"]},"fields":{"slug":"pass-api-key-from-frontend"}},"nextNode":{"frontmatter":{"title":"Deploying the API to Heroku","active":true,"free":false,"order":49,"tech":["phoenix","heroku"]},"fields":{"slug":"deploying-the-api-to-heroku"}}}},"staticQueryHashes":["1723017916"]}