Storing login redirect in GET request_path in session does not capture params(phoenix 1.5.4)

So when the user has not logged-in yet, I capture the login redirect in the conn.request_path:

Route in leex:
<a href="<%= Routes.checkout_new_path(@conn, :new, %{product_stripe_id: product.stripe_id}) %>" class="rounded-full btn btn-primary" role="button">

Since this route :require_user_authentication via the router.ex, it will store it like this(maybe_store_return_to):

  def require_authenticated_user(conn, _opts) do
    if conn.assigns[:current_user] do
      conn
    else
      conn
      |> put_flash(:error, "You must login to access this page.")
      |> maybe_store_return_to()
      |> IO.inspect(label: "after maybe_store_return_to")
      |> redirect(to: Routes.user_session_path(conn, :new))
      |> halt()
    end
  end

  defp maybe_store_return_to(%{method: "GET", request_path: request_path} = conn) do
    put_session(conn, :user_return_to, request_path)
  end

  defp maybe_store_return_to(conn), do: conn

  defp signed_in_path(_conn), do: "/"

But this does not capture the param “product_stripe_id”.

expected/preferred contents of user_return_to:

"user_return_to" => "/checkout/new?product_stripe_id=prod_asdfasdfasdf123"

actual contents of user_return_to::

"user_return_to" => "/checkout/new"

This is how currently handle things after login:

  def login_user(conn, user, params \\ %{}) do
    IO.inspect(user, label: "login_user user")
    IO.inspect(params, label: "login_user params")

    # cart can be nil if the unlogged-in user didn't add something to the cart
    cart = get_session(conn, "shopping_cart") || []
    IO.inspect(cart, label: "UserAuth login_user shopping_cart")

    token = Accounts.generate_user_session_token(user, params["org_id"])
    user_return_to = get_session(conn, :user_return_to)
    IO.inspect(user_return_to, label: "login_user user_return_to")

    conn
    |> renew_session()
    |> put_session(:user_token, token)
    |> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}")
    |> put_session("shopping_cart", cart)
    |> maybe_write_remember_me_cookie(token, params)
    |> redirect(to: user_return_to || signed_in_path(conn))

    conn
  end

Any suggestions on optimal way to store the GET params? Or how to store the full GET with the params in the first place?

1 Like

You’ll want to use Phoenix.Controller.html#current_path/1 - it adds the query string to the path, if one was given.

  defp maybe_store_return_to(%{method: "GET"} = conn) do
    put_session(conn, :user_return_to, current_path(conn))
  end
3 Likes

Yup, thanks that nailed it.