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.
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
defp put_user_token(conn, _) do
user = Module.Guardian.Plug.current_resource(conn)
conn = put_session(conn :user, user)
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?