Using Elixir Plug.conn.assigns in multiple modules

52 views Asked by At

My session_controller.ex in a Phoenix project assigns current_user and user_token to Conn as follows.

def create(%Plug.Conn{private: %{openmaize_user: %{id: id}}} = conn, _params) do
    username = conn.private.openmaize_user.username
    IO.inspect("SessionController create: username")

    conn = conn
    |> put_current_user(username)
    |> put_session(:user_id, id)
    |> auth_info("You have been logged in", user_path(conn, :index))
  end


defp put_current_user(conn, username) do
    token = Phoenix.Token.sign(conn, "user socket", conn.private.openmaize_user.username)

    conn = conn
    |> assign(:current_user, username)
    |> assign(:user_token, token)
  end

I then tried to use the current_user in another module via Plug.Conn as follows, but Conn.assigns is null at that point.("current_user" field is just an example, and it can be any field).

The question is how do I assign values to a Conn and how do I use the values in other modules.

defmodule MyApp.GraphQLSession do
  import Plug.Conn 
  alias MyApp.{Repo, User}
  use MyApp.Web, :controller

  def root_eval(conn) do
    %{current_user: conn.assigns[:current_user]}

Conn in SessionController (successfully assigned values)

%Plug.Conn{adapter: {Plug.Adapters.Cowboy.Conn, :...},
 assigns: %{current_user: "User A",
   user_token: "SFMyNTY.g3QAAAACZAAEZGF0YW0AAAAHLIL1VECezSDyQ"},

Conn in modules outside SessionController

%Plug.Conn{adapter: {Plug.Adapters.Cowboy.Conn, :...}, **assigns: %{}**,..... nil
0

There are 0 answers