annad

annad

Liveview, phx.gen.auth and server-side session data

I’m posting this for beginners who are new to Phoenix LiveView and web development (like myself). I really struggled to get my head wrapped around storing server-side session data. Below is the problem Use Case and solution that ended up being crazy easy to set up … if you know what to do. :slight_smile:

For those who are experienced in Liveview … please feel free to make any corrections! I’m just trying to contribute to the community when I figure things out in hopes it will make it easier for others.

First, I want to thank @hive and @kokolegorille for their help with this. Both provided examples that helped me understand how to use OTP. Also want to reference this blog post that was super helpful: Persistent session data via a database in Phoenix LiveView – The Pug Automatic

ASSUMPTION: This example assumes you are using phx.gen.auth for authentication and you have a working knowledge of how that works.

USE CASE: This is not my app, but it is a good example to explain the use case. Think of a typical real estate website like Zillow or Redfin. A user will often start searching the website without being logged in. The user selects a bunch of filters to target their search of properties. If they find a property they like, they “save” that property. As soon as they click on “save”, they are asked to log into the website so that the property can be saved to their user profile. After the “save” is executed, the app will redirect the user back to the search page and ALL of the filters will still be in place. You never want the user to lose their pre-selected filters. That would be annoying.

LIVE VIEW: To implement this, I used two LiveViews:

Unauthenticated Liveview
Index.ex (lists the resources and allows the user to select filters without being logged in)

Authenticated Liveview - this path sits behind [:require_authenticated_user] in the router
Save_Resource.ex (allows user to save resource after redirecting them to login)

PROBLEM:

When the user selects “Save”, they are redirected to the Save_Resource Liveview. The key word here is “redirected.” The assigns from Index are not passed along. Even if you implemented Save as a component, you’d still need to redirect the user to Login and again that would flush the assigns. The advantage to using a Liveview behind the “authenticated” path in the router is that it automatically handles the login enforcement. But that redirection also means that all of the FILTERS that the user selected could be potentially lost. We want the user to return to Index and still have all of their filters in place. This is the key problem being solved by the solution below.

So there are two options for storing those filters:

  1. Send them back as params in live_redirect which would create a very heavy and ugly URL
  2. Store the filter criteria in server side storage.

Ok, there is a third option of storing them as cookies, but this example is focused on the server side. :slight_smile:

Both @hive and @kokogorille helped me understand how to use OTP to store and retrieve the filter criteria on the server. Here are the steps:

ROUTER.ex
Create a plug to generate a unique session_id. First add the plug name to the browser pipeline

pipeline :browser do
	# …
	plug :assign_session_id
end

At the bottom of the router.ex file, add the function to set a unique ID number to the session if it is not already set.

defp assign_session_id(conn, _) do
    if get_session(conn, :session_id) do
      # If the session_id is already set, don't replace it.
      conn
    else
      session_id = Ecto.UUID.generate()
      conn |> put_session(:session_id, session_id)
    end
  end

MYAPP/key_value_store.ex
Create this file (and call it whatever you want). The code in this file is used to store and retrieve session data as key/value pairs.

defmodule MyApp.KeyValueStore do
  use Agent

  def start_link(initial_value \\ %{}) do
    Agent.start_link(fn -> %{} end, name: __MODULE__)
  end

  def store(key, val) do
    Agent.update(__MODULE__, &Map.put(&1, key, val))
  end

  def get(key) do
       Agent.get(__MODULE__, &Map.get(&1, key))
  end
end

APPLICATION.ex
Add this to def start(_type, _args) so that the KeyValueStore is created when the app is started

   def start(_type, _args) do
      children = [
         # …
        MyApp.KeyValueStore
   ]

   # …
end

USER_AUTH.ex
Add this code into user_auth.ex so that you don’t lose your session_id when it calls renew_session() on the conn:

def log_in_user(conn, user, params \\ %{}) do

   # The line below is auto generated with phx.gen.auth. Notice that it’s doing the 
   # same thing we’re doing with the session_id.  It’s grabbing the token so that
   # it can be assigned back into conn AFTER renew_session() is called
   token = Users.generate_user_session_token(user)

  # Add this line to grab the existing session id
  session_id = get_session(conn, :session_id)

  conn
    |> renew_session()
    |> put_session(:session_id, session_id) # put the session_id back into the conn!
    |> put_session(:user_token, token)
    … # the rest of the code just stays

end

INDEX.ex
In mount, add the session_id to the assigns. You’re able to access session[“session_id”] thanks to that plug in the router.

def mount(_params, session, socket) do
    # …
   socket = assign(socket, :session_id, session[“session_id”]

{:ok, socket}
end

Now store the session data you want to access across LiveViews. This is just a function inside my Index.ex file. I call it from another function when I want the filter criteria stored.

defp store_search_criteria(socket) do

    criteria = “Whatever you are going to store.  This can be a List, Map, etc”

    # Put it in the store with the session_id
    MyApp.KeyValueStore.store(socket.assigns.session_id, criteria)

  end

In my app the control flows as follows:
Index.ex → SaveResource.ex → phx.gen.auth Login code → SaveResource → Index

When the user “saves” the resource, the router will check if the user is authenticated and send the user to login if that is required. Then the user will be redirected back to SaveResource and then ultimately redirected back to Index. So by the time the control makes it back to Index … those assigns are LONG gone!!!

INDEX.ex
Once back in Index, the user should be shown the resources AND the filters they applied before the save. The following code retrieves the filter criteria from the storage and resets the search to reflect those pre-selected filters:

defp apply_action(socket, :index, _params) do

    # Retrieve criteria from storage
    criteria = KeyValueStore.get(socket.assigns.session_id)

    # Update criteria in my app if there are preselected filters
    if criteria != nil do
      socket
           |> assign(:resourceform, nil)
           |> assign(:resource_forms,
              Resourceforms.list_resource_forms(criteria))
    else
      socket |> assign(:resourceform, nil)
             |> assign(:resource_forms, list_resource_forms())
    end
end

Be sure to restart phx.server after updating the files.

AND THAT’S IT!!!

One last note is that you will have to do periodic cleanup of the KeyValue store. My next challenge is to figure out how to do periodically clear the storage using a scheduled OTP event.

First Post!

kokolegorille

kokolegorille

Well done, next step is to use GenServer, so that You can send yourself a periodic message, to clear old session automatically.

I just want to point this code…

It is not going to do what You think it does, because of the immutable nature of Elixir :slight_smile:

Where Next?

Popular in Discussions Top

jswny
I would like to better understand what the advantages/disadvantages of umbrella applications are compared to structuring your app as as s...
New
cvkmohan
The upcoming Phoenix 1.6 release looks very interesting. Became a habit to watch the commits - and - what they are bringing in. phx.gen...
New
Fl4m3Ph03n1x
Background A few days ago I was listening to The future of Elixir from Elixir Talks, with Dave Thomas (@pragdave ) and Brian Mitchell. I...
New
mmport80
I have put far too much effort into Dialyzer over the last year or so - and basically - I doubt it’s worth the effort. It’s not as easy ...
New
arpan
Hello everyone :wave: Today I am very excited to announce a project that I have been working on for almost 3 months now. The project is...
New
Ankhers
Just a little information upfront. Generally speaking, if I feel like I need to either break a pipe chain or use an anonymous function in...
New
New
shishini
I think this twitter post and youtube video didn’t get as much attention as I hoped I am still new to Elixir, so can’t really judge ...
New
chulkilee
Here are the list of HTTP client libraries/wrappers, and some thoughts on HTTP client in general. I’d like to hear from others how they w...
New
Markusxmr
Since Drab has been developed for a while in the open, introducing the Liveview functionality in a way it happend appears to undermine th...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement