Using csrf_token as a unique identifier?

I have an online checkout with a multi step form and the form data should survive a page refresh. I am storing the form steps in an ETS table.

I don’t have any user auth - guests always checkout anonymously. Is it ok to use the csrf token to uniquely identify and store user activity? Or should I generate a unique id and store it in the session with a plug?

  def mount(_params, session, socket) do
    checkout_id = Map.get(session, "_csrf_token")

    {personalise, delivery, payment, current_step} =
      case :ets.lookup(:checkouts, checkout_id) do
        [{_checkout_id, {_, _, _, _} = form}] ->
          form

        _ ->
          form = {%Personalise{}, %Delivery{}, %Payment{}, 1}
          :ets.insert(:checkouts, {checkout_id, form})
          form
      end

    {:ok,
     socket
     |> assign(checkout_id: checkout_id)
     |> assign(step: current_step)
     |> assign(personalise: personalise)
     |> assign(delivery: delivery)
     |> assign(payment: payment)}
  end

Thanks :smiling_face:

The CSRF token resets with each navigation, so it wouldn’t be suitable for this. You could use the plug session for this, or put a unique ID in sessionStorage using a JS hook or push_event/3.

1 Like

Did a similar thing by creating a random token in a plug and store it in the session. Then with ‘live_session’ I put it in the socket. I have a simple ‘InitAssigns’ module for this.

2 Likes

Thanks for pointing me in the right direction. I now have a plug which assigns a session id and can be accessed on LiveView mount.