phoenix_playground
phoenix_playground copied to clipboard
Session is empty when mount/3 is called the second time
I ran into this when trying to create a simple token-based auth for the liveview.
This might be fixable by a custom endpoint which passes @session_options to the socket "/live", Phoenix.LiveView.Socket call. But it would be nice to have sessions working in liveview as expected in PhoenixPlayground.Endpoint which is missing this option.
I added this demo script to demonstrate this problem of using sessions in liveviews.
When you run it, you can see that first mount prints this:
12:52:58.137 [info] GET /
12:52:58.140 [debug] Processing with LiveWithSession.Elixir.LiveWithSession/2
Parameters: %{}
Pipelines: [:browser]
[examples/demo_live_with_session.exs:21: LiveWithSession.mount/3]
session #=> %{"user_id" => "testuser"}
But then, when the connection is upgraded to websocket, we see this:
12:52:58.188 [info] CONNECTED TO Phoenix.LiveView.Socket in 23µs
Transport: :websocket
Serializer: Phoenix.Socket.V2.JSONSerializer
Parameters: %{"vsn" => "2.0.0"}
12:52:58.208 [debug] MOUNT LiveWithSession
Parameters: %{}
Session: %{}
[examples/demo_live_with_session.exs:21: LiveWithSession.mount/3]
session #=> %{}
As you can see, the session object is blank when mount is called for the second time (for the websocket).
A potential fix is to change this line in endpoint.ex :
socket "/live", Phoenix.LiveView.Socket
to
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]],
longpoll: [connect_info: [session: @session_options]]
This is how Phoenix's default endpoint behaves and was also suggest in this forum thread.
A few extra things I noticed:
- README as well as example scripts are using v0.1.6 even though latest version on Hex is 0.1.7
- I tried to add a failing test for this but
PhoenixPlayground.Testdoes not support a:plugoption which is needed to use both a LiveView and a custom Plug