At this point, we have an AnonymousUser model and a 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 admin:active_users topic created previously.
We're also going to remove our admin presence from our 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.
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.
We'll start by updating our join/3 function to pass along the socket with the id of the user who joined the channel (either admin or anonymous user).
defmodule PhoenixChat.AdminChannel do @moduledoc """ The channel used to give the administrator access to all users. """ use PhoenixChat.Web, :channel require Logger alias PhoenixChat.{Presence, Repo, AnonymousUser} @doc """ The `admin:active_users` topic is how we identify all users currently using the app. """ def join("admin:active_users", payload, socket) do authorize(payload, fn -> send(self, :after_join) id = socket.assigns[:uuid] || socket.assigns[:user_id] {:ok, %{id: id}, socket} end) end ...endThen we use pattern matching to match users that have a :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 (_user_id). If you do not include this underscore, you will get a warning that there is an unused variable.
Then we create a new handle_info/2 function that matches a :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 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 uuid rather than a generic id since we are now only sending anonymous users.
defmodule PhoenixChat.AdminChannel do ... @doc """ This handles the `:after_join` event and tracks the presence of the socket that has subscribed to the `admin:active_users` topic. """ def handle_info(:after_join, %{assigns: %{user_id: _user_id}} = socket) do push socket, "presence_state", Presence.list(socket) {:noreply, socket} end def handle_info(:after_join, %{assigns: %{uuid: uuid}} = socket) do ensure_user_saved!(uuid) push socket, "presence_state", Presence.list(socket) Logger.debug "Presence for socket: #{inspect socket}" {:ok, _} = Presence.track(socket, uuid, %{ online_at: inspect(System.system_time(:seconds)) }) {:noreply, socket} endendIn our 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 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 Repo to make the change.
defmodule PhoenixChat.AdminChannel do ... defp ensure_user_saved!(uuid) do user_exists = Repo.get(AnonymousUser, uuid) unless user_exists do changeset = AnonymousUser.changeset(%AnonymousUser{}, %{id: uuid}) Repo.insert!(changeset) end endendSo 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.
It's generally good practice to validate your parameters when you receive data from a user. In our user_socket, go ahead and add a validate_params/1 function (defined later) and remove the :user_id from our socket since we are no longer passing along admin presence data.
defmodule PhoenixChat.UserSocket do ... def connect(params, socket) do user_id = params["id"] user = user_id && Repo.get(User, user_id) validate_params!(params) socket = if user do socket |> assign(:user_id, user_id) |> assign(:username, user.username) |> assign(:email, user.email) else socket |> assign(:uuid, params["uuid"]) end {:ok, socket} end ...endNow we need to define our 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 id and uuid and checking to make sure that they aren't empty. If they are, we raise an error that explicitly tells us what the problem is.
If the parameters don't match anything, then we don't do anything (do: nil is a "no operation" or "noop").
defmodule PhoeniChat.UserSocket do ... @empty ["", nil] defp validate_params!(%{"id" => id, "uuid" => uuid}) when id in @empty or uuid in @empty do raise "id or uuid must not be empty" end defp validate_params!(_), do: nilendAt 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 room_channel to make sure we're sending along the new name and avatar to our frontend.