Dynamically set up session domain (#3089)

* Dynamically configure session domain

* Fix up error message in runtime config
This commit is contained in:
hq1 2023-06-28 12:28:26 +02:00 committed by GitHub
parent 4ac83b6e5d
commit eb397a6c25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 2 deletions

View File

@ -233,7 +233,7 @@ if byte_size(websocket_url) > 0 and
Cross-domain websocket authentication is not supported for this server.
WEBSOCKET_URL=#{websocket_url} - host must be: '#{base_url.host}',
because BASE_URL=#{base_url} so the host is ``.
because BASE_URL=#{base_url}.
"""
end

View File

@ -9,6 +9,7 @@ defmodule PlausibleWeb.Endpoint do
# 5 years, this is super long but the SlidingSessionTimeout will log people out if they don't return for 2 weeks
max_age: 60 * 60 * 24 * 365 * 5,
extra: "SameSite=Lax"
# domain added dynamically via RuntimeSessionAdapter, see below
]
# Serve at "/" the static files from "priv/static" directory.
@ -52,7 +53,7 @@ defmodule PlausibleWeb.Endpoint do
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug PlausibleWeb.Plugs.RuntimeSessionAdapter, @session_options
socket "/live", Phoenix.LiveView.Socket,
websocket: [

View File

@ -0,0 +1,30 @@
defmodule PlausibleWeb.Plugs.RuntimeSessionAdapter do
@moduledoc """
A `Plug.Session` adapter that allows configuration at runtime.
Sadly, the plug being wrapped has no MFA option for dynamic
configuration.
This is currently used so we can dynamically pass the :domain
and have cookies planted across one root domain.
"""
@behaviour Plug
@impl true
def init(opts) do
Plug.Session.init(opts)
end
@impl true
def call(conn, opts) do
Plug.Session.call(conn, patch_cookie_domain(opts))
end
defp patch_cookie_domain(%{cookie_opts: cookie_opts} = runtime_opts) do
Map.replace(
runtime_opts,
:cookie_opts,
Keyword.put_new(cookie_opts, :domain, PlausibleWeb.Endpoint.host())
)
end
end