{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/persist-anonymous-users","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\": \"Persist Anonymous Users\",\n  \"order\": 30,\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, \"Persist Anonymous Users\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Add anonymous users to admin channel\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Validate params\")), mdx(\"p\", null, \"At this point, we have an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AnonymousUser\"), \" model and a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset/2\"), \" to add them to the database, but we aren't triggering this addition anywhere. In this section, we trigger a database addition when an anonymous user joins our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"admin:active_users\"), \" topic created previously.\"), mdx(\"p\", null, \"We're also going to remove our admin presence from our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"active_users\"), \" to make our frontend code simpler (so we don't need to filter out admins any longer) and so we aren't passing along any extra data. We're still keeping track of the admin presence on the backend and we will use that later on.\"), mdx(\"p\", null, \"We also add some simple validations on the params we pass on our socket connection. For example, we want to raise an error if both the id and uuid params are empty. This helps to simplify our code and lets the frontend know if something is missing.\"), mdx(\"h2\", null, \"Add anonymous users to admin channel\"), mdx(\"p\", null, \"We'll start by updating our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join/3\"), \" function to pass along the socket with the id of the user who joined the channel (either admin or anonymous user).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  @moduledoc \\\"\\\"\\\"\\n  The channel used to give the administrator access to all users.\\n  \\\"\\\"\\\"\\n\\n  use PhoenixChat.Web, :channel\\n  require Logger\\n\\n  alias PhoenixChat.{Presence, Repo, AnonymousUser}\\n\\n  @doc \\\"\\\"\\\"\\n  The `admin:active_users` topic is how we identify all users currently using the app.\\n  \\\"\\\"\\\"\\n  def join(\\\"admin:active_users\\\", payload, socket) do\\n    authorize(payload, fn ->\\n      send(self, :after_join)\\n      id = socket.assigns[:uuid] || socket.assigns[:user_id]\\n      {:ok, %{id: id}, socket}\\n    end)\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Then we use pattern matching to match users that have a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":user_id\"), \" (which are our admins) and return the socket without adding any data. This is effectively filtering out our admins on the backend so we don't need to run the filter on the frontend and it ensures we aren't sending extra, unnecessary data to our frontend. Recall that an underscore denotes a variable that will not be used in the body of the function (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"_user_id\"), \"). If you do not include this underscore, you will get a warning that there is an unused variable.\"), mdx(\"p\", null, \"Then we create a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_info/2\"), \" function that matches a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":uuid\"), \" for an anonymous user. As soon as this anonymous user joins, we check to make sure that the user is saved to the database using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ensure_user_saved\"), \", which we define below. Then, just as before, we track the presence state of this user and push it to our socket, with the only difference that we are now sending a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" rather than a generic \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" since we are now only sending anonymous users.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  ...\\n\\n  @doc \\\"\\\"\\\"\\n  This handles the `:after_join` event and tracks the presence of the socket that\\n  has subscribed to the `admin:active_users` topic.\\n  \\\"\\\"\\\"\\n  def handle_info(:after_join, %{assigns: %{user_id: _user_id}} = socket) do\\n    push socket, \\\"presence_state\\\", Presence.list(socket)\\n    {:noreply, socket}\\n  end\\n\\n  def handle_info(:after_join, %{assigns: %{uuid: uuid}} = socket) do\\n    ensure_user_saved!(uuid)\\n\\n    push socket, \\\"presence_state\\\", Presence.list(socket)\\n    Logger.debug \\\"Presence for socket: #{inspect socket}\\\"\\n    {:ok, _} = Presence.track(socket, uuid, %{\\n      online_at: inspect(System.system_time(:seconds))\\n    })\\n    {:noreply, socket}\\n  end\\nend\\n\")), mdx(\"p\", null, \"In our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ensure_user_saved/1\"), \" function, we need to check if the user already exists. If the user does exist, then we do nothing. If the user does not exist, then we create a new user with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" passed in as a parameter. Recall that to add something to the database, you first need to create a changeset, then pass that changeset to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo\"), \" to make the change.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannel do\\n  ...\\n\\n  defp ensure_user_saved!(uuid) do\\n    user_exists = Repo.get(AnonymousUser, uuid)\\n    unless user_exists do\\n      changeset = AnonymousUser.changeset(%AnonymousUser{}, %{id: uuid})\\n      Repo.insert!(changeset)\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"So now, when an anonymous user joins a channel for the first time we add them to the database. You should be careful where you add validations like this because they can quickly get out of control. For example, imagine if we added this validation on every message that was received rather than on join. This would accomplish the same thing but would require dozens/hundreds of additional database reads per user.\"), mdx(\"h2\", null, \"Validate params\"), mdx(\"p\", null, \"It's generally good practice to validate your parameters when you receive data from a user. In our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_socket\"), \", go ahead and add a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_params/1\"), \" function (defined later) and remove the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":user_id\"), \" from our socket since we are no longer passing along admin presence data.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserSocket do\\n  ...\\n\\n  def connect(params, socket) do\\n    user_id = params[\\\"id\\\"]\\n    user = user_id && Repo.get(User, user_id)\\n    validate_params!(params)\\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(:uuid, params[\\\"uuid\\\"])\\n      end\\n\\n    {:ok, socket}\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Now we need to define our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_params/1\"), \" function. Ideally, we want to raise an error as early as possible so we can track it down easier. In this case, we're pattern matching our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" and checking to make sure that they aren't empty. If they are, we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"raise\"), \" an error that explicitly tells us what the problem is.\"), mdx(\"p\", null, \"If the parameters don't match anything, then we don't do anything (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"do: nil\"), \" is a \\\"no operation\\\" or \\\"noop\\\").\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoeniChat.UserSocket do\\n\\n  ...\\n\\n  @empty [\\\"\\\", nil]\\n  defp validate_params!(%{\\\"id\\\" => id, \\\"uuid\\\" => uuid})\\n  when id in @empty or uuid in @empty do\\n    raise \\\"id or uuid must not be empty\\\"\\n  end\\n\\n  defp validate_params!(_), do: nil\\nend\\n\")), mdx(\"p\", null, \"At this point, our app is storing anonymous users when they join for the first time and we are sending only the anonymous user's data to our frontend. The next step is to update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room_channel\"), \" to make sure we're sending along the new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"name\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"avatar\"), \" to our frontend.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Persist Anonymous Users Add anonymous users to admin channel Validate params At this point, we have an  AnonymousUser  model and a…","frontmatter":{"title":"Persist Anonymous Users","order":30,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"persist-anonymous-users","prevNode":{"frontmatter":{"title":"Create Anonymous User Model","active":true,"free":false,"order":29,"tech":["phoenix"]},"fields":{"slug":"create-anonymous-user-model"}},"nextNode":{"frontmatter":{"title":"Broadcast Active and Inactive Users","active":true,"free":false,"order":31,"tech":["phoenix"]},"fields":{"slug":"broadcast-active-and-inactive-users"}}}},"staticQueryHashes":["1723017916"]}