elixir-plug / plug

Compose web applications with functions
https://hex.pm/packages/plug
Other
2.84k stars 582 forks source link

Request: Support MFA tuple for Plug.Session opts #1176

Closed ukutaht closed 10 months ago

ukutaht commented 10 months ago

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

josevalim commented 10 months ago

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

:)

whatyouhide commented 10 months ago

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

ukutaht commented 10 months ago

Thanks, these facilities make the setup much simpler: https://github.com/plausible/analytics/pull/3404/commits/578fd52c798726a5b6627168e3a799fcc286bcfb

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

josevalim commented 10 months ago

No worries!