elixir-plug / plug

Compose web applications with functions

Home Page:https://hex.pm/packages/plug

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Request: Support MFA tuple for Plug.Session opts

ukutaht opened this issue · comments

Use-case: configuring session_opts in a Phoenix application at runtime. In a typical Phoenix.Endpoint, the session opts are passed to both Phoenix.LiveView.Socket as well as Plug.Session. For the former, a MFA tuple can be used:

https://github.com/plausible/analytics/blob/842bbb79955405fd4222e479a9d11f00a1a81d95/lib/plausible_web/endpoint.ex#L62-L67

It is slightly annoying that the same helpers cannot be used to configure Plug.Session. Instead the only solution I've found is to create a custom plug that patches the opts at runtime:

https://github.com/plausible/analytics/blob/842bbb79955405fd4222e479a9d11f00a1a81d95/lib/plausible_web/plugs/runtime_session_adapter.ex#L19-L36

And use it in the endpoint:
https://github.com/plausible/analytics/blob/842bbb79955405fd4222e479a9d11f00a1a81d95/lib/plausible_web/endpoint.ex#L60

Allowing Plug.Session to be configured with a MFA tuple in the same way as LiveView.Socket would save time, effort, and make the endpoint configuration less error-prone.

Let me know if you think it's worth a PR

Yes, the custom plug is the way to go. Just not though the custom plug can be simpler:

plug :my_session

def my_session(conn, _opts) do
  opts = build_your_options_here()
  Plug.Session.call(conn, Plug.Session.init(opts))
end

:)

...or Plug.run(conn, [{Plug.Session, opts}]) 🙃

Thanks, these facilities make the setup much simpler: plausible/analytics@578fd52

I think we can live without the MFA tuple 😀 Sorry for not researching all the options before requesting a feature

No worries!