Is it possible to hold an assignment to a LiveView socket and keep it as long as the socket is connected?

Since all the LiveView pages in my Phoenix app requires the user to be logged in (thru OAuth2), I suppose I can create a LiveView socket connection after the last OAuth2 redirect and assign the current user to the socket. Whenever I need the current user, I can just grab the current user from the socket.assigns (or something alike).

But when I tried this approach, I was facing 2 problems:

  1. I can’t find a way to override or modify Phoenix.LiveView.Socket.connect/3.
  2. The assigns are lost when the user visits another page.

For the first problem, for now I just copy the relevant part of the code from the module Phoenix.LiveView.Socket, modify it a bit, and change this line

socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]

in the endpoint.ex to

socket "/live", MyAppWeb.LiveViewSocket, websocket: [connect_info: [session: @session_options]]

It’s not elegant because I have to access socket.private, but at least it works.

For the second problem, I just can’t find a way to solve it. I’ve tries putting the current user in the process dictionary of the current process, but it turned out that the process handling connection and the process handling liveview rendering are 2 different processes.

Does anyone have the same problem? What’s your solution?

P.S. Since I saw the Phoenix.LiveView.put_flash/3, maybe it could be better also have a Phoenix.LiveView.put_session/3?

This guide should be relevant :

https://hexdocs.pm/phoenix_live_view/security-model.html

1 Like