I continue to implement the new authentication live views based on the generated files from running mix phx.gen.auth in a demo project. I need to update the create function in UserSesssionController to authenticate with email instead of username, but this function is used by the existing login page. I rename the existing create function to create_with_username which will be a temporary change until the old login page can be deleted. I add a new create function which is an alias of the original. I then update the existing login route to use the create_with_username action in the router.ex file.

As I begin copying tests and behavior for the UserSessionController module from the generated files, some of the existing game live view tests start failing. These existing live views use the default on_mount hook that I’ve defined to set user data on the live view socket before mounting.

I remove the references to this hook from each of the three live view modules and wrap the associated live routes in a live_session block which registers the ensure_authenticated hook which I copied from the generated UserAuth module. ensure_authenticated adds the user data to the socket or sets a flash message to be displayed if the request is not authenticated.

  scope "/", MinotaurWeb do
    pipe_through [:browser, :require_authenticated_user]

    live_session :require_authenticated_user, on_mount: [{MinotaurWeb.UserAuth, :ensure_authenticated}] do
      live "/", HomeLive, :index
      live "/lobby/:lobby_id", LobbyLive, :index
      live "/game/:game_id", GameLive, :index
    end
  end

I then finish adding UserSessionController tests for authenticating with email in the updated create function. I follow the same pattern as the registration module of adding tests from generated files and implementing the dependent functions until the tests pass.

I add the /users/log_out route which will remove the user token from the session, but since the tokens are not persisted, they are not invalidated. I’ll have to implement the invalidation behavior after I add the UserToken table with Ecto.

I wrap up the new views by adding the login live view after copying all tests from the generated files. Finally, I remove the original “dead” controller-based views, routes, and unused code related to username authentication.

It took me a few hours to get the new authentication live views implemented as I methodically read through each line of code as it was added. This was worth the time investment to me since I now have a deeper understanding of how these modules work and there is less “magic” around this system compared to blindly copy/pasting generated modules.