I’m currently building an authentication system in Phoenix LiveView where users can register and log in via a modal without a full page reload. My process involves logging the user in immediately after registration and then displaying a PIN verification modal.
In a traditional Phoenix controller, I’d typically use conn
to manage session data, like this:
def log_in_user(conn, user, params \\ %{}) do
token = Account.generate_user_session_token(user)
user_return_to = get_session(conn, :user_return_to)
conn
|> renew_session()
|> put_token_in_session(token)
|> maybe_write_remember_me_cookie(token, params)
|> redirect(to: user_return_to || signed_in_path(conn))
end
However, I’m struggling to adapt this to LiveView. Since LiveView primarily works with socket
instead of conn
, I’m not sure how to properly manage the session and authentication state. I initially tried passing the socket
to the above function, but it didn’t work as expected because it requires conn
.
I understand that LiveView’s lifecycle means that data set on conn
during the static render isn’t accessible in the live render. I’ve read that using assign_new
to set session data or using the new on_mount
callback in LiveView could help, but I’m unsure how to apply these concepts when my session management relies heavily on conn
.
Has anyone successfully managed this transition from conn
-based session handling to a LiveView-compatible approach? Any best practices for structuring the code so that it’s reusable across both traditional controllers and LiveViews?
Thanks in advance for any advice or examples!