RobertoSchneiders

RobertoSchneiders

I’ve been reading about session management on Phoenix LiveView for the last couple of days and can’t seem to find a solution for this problem.

My app is basically entirely built with live views, almost all redirects are live redirects. Most views can be accessed whether you are logged in or not, similar to an e-commerce app. I have a basic authentication system generated by the mix phx.gen.auth. The login is a post HTTP request (so we can set the session cookie).

When a user logs in, ideally, the other tabs that are opened in the same browser would notice that and act accordingly. Another option would be to update the session state of those tabs once the user does an action, e.g. click on a link and navigate to another view. The problem is that everything is a live redirect so the other tabs don’t update the session state unless the user refreshes the page, which is not a great user experience.

Does anyone have any idea on how to solve this?

I’m wondering if it would be possible to force a full page reload on the other tabs when logging in.

Showing Posts 1 to 10

shamanime

shamanime

You’ve implemented phx.gen.auth so you’re probably aware of the LiveView disconnect when the user logs out. That forces the tabs to reload.

If you come up with a way to identify all the tabs which belongs to the same guest user (ip?, browser fingerprint?, setting an identifier in the session at first page load and using it afterwards [like a fake user id]?) and set the live_socket_id accordingly, you can also disconnect all the “guest” LiveViews to force a page reload that will fetch the newly signed in user.

thomas.fortes

thomas.fortes

My naive first approach would be something like:

  1. At any new tab check if there’s a token (preferably tamper proof) in local storage and send it to the server, if not, ask for one from the server with an unique identifiable payload (maybe an UUID) and save it in the local storage, in this case only the first page load will actually create a token.

  2. Using on_mount use attach_hook/4 to handle the pushed event with the uuid to subscribe to a “guest#{uuid}” channel and the incoming handle_info/2 messages from pubsub.

  3. When the user successfully log in you can broadcast a message to the guest#{uuid} channel that will be handled by the handle_info/2 callback of all liveviews subscribed to that channel.

Security considerations aside (short lived tokens, single use, yadda, yadda, yadda) I think someone could build it in a couple hours.

A bit more javascript than I like to write though…

thomas.fortes

thomas.fortes

Ok, did a proof of concept.

Global hook at app.html.heex

<main id="main" phx-hook="MainHook" class="px-4 py-20 sm:px-6 lg:px-8">
  <div class="mx-auto max-w-2xl">
    <.flash_group flash={@flash} />
    <%= @inner_content %>
  </div>
</main>

The hook

Hooks.MainHook = {
    mounted() {
        let token = localStorage.getItem("uuid")
        if(token == null) {
            // here you should push an event to the server and fetch a
            // tamper proof token and save it to localStorage and
            // all other security considerations
            token = "1234"
        }
        this.pushEvent("subscribe_to_channel", {uuid: token})
    }
}

The module attaching the server hooks

defmodule ExampleWeb.MultipleTabs do
  import Phoenix.LiveView

  def on_mount(:default, _params, _session, socket) do
    {:cont,
     socket
     |> attach_hook(
       "subscribe_to_channel",
       :handle_event,
       &subscribe_to_channel/3
     )
     |> attach_hook(:handle_reload, :handle_info, &reload_page/2)}
  end

  defp reload_page(_msg, socket) do
    # Here you'll need to figure out a way to get the url
    # to redirect to the correct place
    {:cont, socket |> redirect(to: "/")}
  end

  defp subscribe_to_channel("subscribe_to_channel", %{"uuid" => uuid}, socket) do
    # Here you should validate the token before subscribing
    Phoenix.PubSub.subscribe(Example.PubSub, "reload##{uuid}")
    {:cont, socket}
  end
end

And then just put it in a live session in the router

    live_session :default, on_mount: ExampleWeb.MultipleTabs do
      live "/", HomeLive
    end

Then you can call Phoenix.PubSub.broadcast(Example.PubSub, "reload#1234", []) from anywhere and all pages will redirect to /.

Security considerations aside it is pretty simple.

RobertoSchneiders

RobertoSchneiders OP

wow, that was awesome. Thank you both @shamanime @thomas.fortes for your help. The proof of concept was incredibly helpful.

It’s working as expected but I had to change the subscribe_to_channel function to return {:halt, socket} instead of :cont.

  defp subscribe_to_channel("subscribe_to_channel", %{"uuid" => uuid}, socket) do
    Phoenix.PubSub.subscribe(Swayze.PubSub, "reload##{uuid}")
    {:halt, socket}
  end

I’m not sure why but with :cont I was getting an error:

[debug] HANDLE EVENT "subscribe_to_channel" in AppWeb.HomeLive
  Parameters: %{"uuid" => "1234"}
"running subscribe_to_channel"
function AppWeb.HomeLive.handle_event/3 is undefined or private
AppWeb.HomeLive.handle_event("subscribe_to_channel", %{"uuid" => "1234"}, #Phoenix.LiveView.Socket...)

I noticed that the subscribe_to_channel was being executed and the error would happen after that so I tried the :halt and it worked but, to be honest, I’m not 100% sure why. In your example, Is the event being sent to HomeLive after being processed by the subscribe_to_channel function?

thomas.fortes

thomas.fortes

Had the same error, not in my computer right now but if I recall correctly I used an empty handle event in my liveview (just a catch all handle event that does nothing and just returns {:noreply, socket})

Hermanverschooten

Hermanverschooten

If all your tabs are in the same session, could you not store your channel-id in the session?
Then there is no need for localstorage.
If the tabs are in different sessions, I would not want them to automagically login to this user.

RobertoSchneiders

RobertoSchneiders OP

AFAIK, the session is stored in a cookie by default and live views have no access to it, unless you make an HTTP request, read the session information you want, and then store it somehow in the LiveView.

In my case, I’m not doing any HTTP requests (unless of course, the user refreshes the page) so I can’t really use session information to update the live view states.

Hermanverschooten

Hermanverschooten

To get to your live view initially you have to do a GET request, there in mount/3 you have access to the session. So each tab would have access to the session and use a “token” stored in it to connect to you channel that will them when there was a login.

RobertoSchneiders

RobertoSchneiders OP

not quite, because the other tabs already have the liveview mounted, they were opened before the user logged in, so no HTTP requests will be made from that point on.

Hermanverschooten

Hermanverschooten

But when you opened that tab a GET request was issued to your app.

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
csmr
Hi all, I’m new here and would like to hear peoples views on my Elixir/Phoenix based game-engine! :smiley: Mutonex gamedesign was finish...
New
Stef-Verniers
Hello I’ve been coding in Elixir for almost two years now because of my current job where we implemented Elixir in our application. But ...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews