kelsey_l

kelsey_l

Am I using session storage correctly with LiveView?

I’m working on a “learn something” project at work using Phoenix LiveView. My team is building a planning poker app (similar to the one featured at ElixirConf). We had the idea to not have registered users but instead to try to track users using cookies or local storage. We wanted to do this so we can know which connection is the person who created a particular prompt (“How many story points do you think __ feature should be?”). Originally we thought cookies would be the way to go but then I saw this thread: Accessing cookies in Phoenix.Socket connect - #18 by josevalim (“Still I don’t think we should allow cookies to be read.” @josevalim )

Here is my first implementation. I created a plug to put a token in the session.

defmodule PokerWeb.SessionToken do
  @impl Plug

  def init(opts) do
    opts
  end

  @impl Plug
  @spec call(Plug.Conn.t(), any) :: Plug.Conn.t()
  def call(conn, _opts) do
    case Plug.Conn.get_session(conn, :user_token) do
      nil ->
        timestamp =
          DateTime.utc_now()
          |> to_string()

        token = Phoenix.Token.sign(PokerWeb.Endpoint, "user_salt", timestamp)

        conn
        |> Plug.Conn.put_session(:user_token, token)

      _ ->
        conn
    end
  end
end

Router:

defmodule PokerWeb.Router do
  use PokerWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug Phoenix.LiveView.Flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug PokerWeb.SessionToken
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", PokerWeb do
    pipe_through :browser

    live "/rooms/new", RoomLive.New, session: [:user_token] # here is the token being made available to the live view
    live "/rooms/:id", RoomLive.Show, session: [:user_token]
    live "/lobby", LobbyLive.Index, session: [:user_token]
    get "/", PageController, :index
  end

end

LiveView:

defmodule PokerWeb.RoomLive.Show do
    use Phoenix.LiveView
    use Phoenix.HTML

    alias PokerWeb.RoomView
    alias Poker.Lobby

    def render(assigns) do
      RoomView.render("show.html", assigns)
    end

    def mount(session, socket) do
      {:ok, assign(socket, :user_token, session.user_token)} # here token added to socket assigns
    end

    def handle_params(%{"id" => id}, _uri, socket) do
      {:noreply, fetch(socket, id)}
    end

    defp fetch(socket, id) do
      assign(socket, room: Lobby.get_room(id))
    end
end

show.html.leex

<h2><%= @room.name %></h2>
<%= if @room.token == @user_token do %>
    <div class="rounded-lg p-6 bg-gray">
        <p>You are admin of this room</p>
    </div>
<% end %>
Slug: <%= @room.slug %>
<hr/>
<%= link "Back", to: Routes.live_path(@socket, PokerWeb.LobbyLive.Index) %>

When a room is created, one of the fields on the Room schema is the token.

The idea is to only persist this data for 24 hours.

Thanks in advance if you can point me in the right direction!

Marked As Solved

sb8244

sb8244

Author of Real-Time Phoenix

LiveView has approached this a bit differently—i think maybe because it’s a more controlled experience between the server and frontend. The LV team can ensure security through signing tokens, so the raw data is never passed to the socket.

LV signs a session when it mounts the view and then this is used in the LV mount function to receive information about the user. You can configure this to include session information (such as a user ID), and it will be managed by LV if the attribute exists in the plug session.

I think this will get you what you need without custom code (or at least without much). It also may depend on how you’re mounting the view. The docs at Phoenix.LiveView.Router — Phoenix LiveView v1.2.5 show how to do this with the router based mounting.

Edit: actually you’re doing this already. I think the key takeaway is that you don’t need to sign it yourself. LV will handle that for you. Since you’re using the token as an ID, you probably don’t need to change anything. You could generate a unique string a different way, but yours looks good to me.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement