Is there any guidance on how to deal with authentication in LiveView?

I’m playing around with LiveView, and while most things work as expected, I’m a bit puzzled on how to deal with authentication. Guides recommend you set up your data in the mount/2 function on your LiveView. This receives the session and socket arguments, but the session I receive is simply an empty map, and the socket has none of the assigns my conn object has.

To even reach the page where my LiveView is installed, they have to be logged in (with Pow, in my case), so they most certainly have a session, so I’m a little confused why it doesn’t show up here.

I know LiveView is not final yet, but given how most apps have authentication, you’d think it would have some facilities for that. What am I missing?

2 Likes

Session has nothing to do with your http request session. Session holds data you chose to send to the liveview using live_render @conn, MyLiveView, session: %{some: data}. This is purposefully kept manual work, as all the data you put here is encoded using Phoenix.Token and inlined into the html to be send to the liveview process on connection via the liveview channel. This is needed because the http request is long finished once the channel is connected. The only non stateful way of passing data is via the html itself.
This also means you want to keep the session data small and containing only relevant information for each liveview. E.g. rather than putting the whole user struct you’d just put the user id, and retrieve the user struct within mount/2. It’s similar to how you wouldn’t put the user struct into the session cookie, but only the user id and use a plug to load the actual struct for each request.

3 Likes

Ah, that should work, thanks.