LiveView: sharing assigns from a plug and redirecting with live navigation

Hello!

I have the basic phoenix book auth plug set up, however when initializing a live view directly from the router, even though the plug is called, I can’t share the assigned current_user to it since only the user_id is shared via the session key, forcing me to fetch the user again with its id. Is there any way to share the assigns from the conn into the live view mounted socket, such to avoid this double query?

On the same subject, considering the user is not signed in and jumps to a live view route that requires a user, what would be the most idiomatic way to redirect the user to the sign in page? I used the handle_params hook for that but am curious to know if there is a better way.

Thank you!

2 Likes

Welcome to the community!

If the user is not signed in then you can handle this from Plug itself. You can redirect the user to a login page or a unauthorized page. You might want to consider Guardian for that.

For getting a signed in user you can have a plug pipeline like so -


pipeline :login_required do
    plug(Guardian.Plug.EnsureAuthenticated)
    plug(:put_user_token)
  end


defp put_user_token(conn, _) do
  user = Module.Guardian.Plug.current_resource(conn)
  conn = put_session(conn :user, user)
end

and then in your live view routes you can do this

live(“/xyz”, ModuleLive, session: [:user])

Hope it helps.

Thank you!

Is it okay to put an entire user in session like this, though? The various code blocks that are recommended when passing to the live call in the router recommend passing only the user’s id.

check the assign_new docs:

      def mount(%{user_id: user_id}, socket) do
        {:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)}
      end
2 Likes

I had tried this but was still seeing the queries being performed twice: once on the plug, and again inside the function call , fn -> Accounts.get_user!(user_id) end) (even when navigating between live links), so I assumed that assign_new was meant for nested live views, and not for live views plugged in directly from the router. Is this a wrong assumption? If so, what explains the double query still happening?

And while I have the attention of the creator, what is your opinion about the redirecting post mount? Is handle_params ok for that?

Thanks for the amazing work, Chris.