Get_session returns nil. What am I doing wrong?

I have a simple authentication scheme (it’s dead simple, just an email with no password) and I am setting a session on form submission. For some reason when I try to retrive the session cookie information Plug.Conn.get_session returns nil. I want to know why and what I am doing wrong.

Here is the form submission controller:

defmodule AppxWeb.SessionController do
  use AppxWeb, :controller
  alias Appx.Accounts.User
  alias Appx.Repo

  def index(conn, _params) do
    render(conn, "index.html")
  end

  def create(conn, params) do           # form post to create session
    IO.inspect("created fake session")
    user = Repo.get_by(User, email: params["email"])
    IO.inspect("____USER ID")
    IO.inspect(user.id) # id displays as expected
    Plug.Conn.put_session(conn, :user_id, user.id)

    render(conn, "index.html")
  end
end

Here is a controller for a page where I attempt to get the session id.
It doesn’t work and returns nil.

defmodule AppxWeb.VideoController do
  use AppxWeb, :controller
  alias Appx.Accounts.User
  alias Appx.Repo

  def index(conn, _params) do
    id = Plug.Conn.get_session(conn, :user_id)

    IO.inspect(id) # nil  ... ???

    render(conn, "index.html")
  end
end
1 Like

Conn structs like most things in erlang/elixir are immutable. So, in order for a change to be seen, you need to pass a new conn struct with session set to your next (render in this case) function.

  def create(conn, %{"email" => email_address}) do           # form post to create session
    IO.inspect("created fake session")
    case Repo.get_by(User, email: email_address) do
      %User{id: user_id} ->
        IO.inspect(user_id, label: "____USER ID") # id displays as expected
        conn
        |> put_session(:user_id, user_id)
        |> render("index.html") # maybe replace with redirect (if it's a POST request)
      nil ->
        conn
        |> put_flash(:error, "#{email_address} not found")
        |> redirect(to: session_path(conn, :index))
    end
  end
4 Likes