defmodule ToweropsWeb.Plugs.RuntimeSession do @moduledoc """ Wrapper around `Plug.Session` that resolves session salts at runtime. The signing and encryption salts come from environment variables (`SESSION_SIGNING_SALT` / `SESSION_ENCRYPTION_SALT`) via `config/runtime.exs`. Because `Plug.Session` is compiled into the endpoint pipeline with its options baked in, this plug defers `Plug.Session.init/1` until the first request and caches the result in `:persistent_term`. """ @behaviour Plug @impl true def init(static_opts), do: static_opts @impl true def call(conn, static_opts) do Plug.Session.call(conn, session_opts(static_opts)) end defp session_opts(static_opts) do case :persistent_term.get({__MODULE__, :opts}, nil) do nil -> opts = Plug.Session.init(static_opts ++ ToweropsWeb.Endpoint.runtime_session_opts()) :persistent_term.put({__MODULE__, :opts}, opts) opts opts -> opts end end end