Use default Phoenix.LiveView.Socket (#3404)

* Use default Phoenix.LiveView.Socket

* Pull socket definition highed in Endpoint config

* Simplify runtime plug session
pull/3432/head
Uku Taht 3 years ago committed by GitHub
parent 97b24c0492
commit d7cd719d4f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -13,6 +13,13 @@ defmodule PlausibleWeb.Endpoint do
# domain added dynamically via RuntimeSessionAdapter, see below
]
socket("/live", Phoenix.LiveView.Socket,
websocket: [
check_origin: true,
connect_info: [session: {__MODULE__, :runtime_session_opts, []}]
]
)
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
@ -57,14 +64,7 @@ defmodule PlausibleWeb.Endpoint do
plug(Plug.MethodOverride)
plug(Plug.Head)
plug(PlausibleWeb.Plugs.RuntimeSessionAdapter, @session_options)
socket("/live", PlausibleWeb.LiveSocket,
websocket: [
check_origin: true,
connect_info: [session: {__MODULE__, :patch_session_opts, []}]
]
)
plug :runtime_session
plug(CORSPlug)
plug(PlausibleWeb.Router)
@ -75,7 +75,11 @@ defmodule PlausibleWeb.Endpoint do
config!(:websocket_url)
end
def patch_session_opts() do
defp runtime_session(conn, _opts) do
Plug.run(conn, [{Plug.Session, runtime_session_opts()}])
end
defp runtime_session_opts() do
# `host()` provided by Phoenix.Endpoint's compilation hooks
# is used to inject the domain - this way we can authenticate
# websocket requests within single root domain, in case websocket_url()

@ -1,15 +0,0 @@
defmodule PlausibleWeb.LiveSocket do
use Phoenix.LiveView.Socket
require Logger
def connect(params, %Phoenix.Socket{} = socket, connect_info) do
case Phoenix.LiveView.Socket.connect(params, socket, connect_info) do
{:ok, %Phoenix.Socket{private: %{connect_info: %{session: nil}}}} ->
Logger.error("Could not connect the live socket: no session found")
{:error, :socket_auth_error}
other ->
other
end
end
end

@ -1,36 +0,0 @@
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.put(
runtime_opts,
:cookie_opts,
cookie_opts
|> Keyword.put_new(:domain, PlausibleWeb.Endpoint.host())
|> Keyword.put(
:secure,
Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)[:secure_cookie]
)
)
|> Map.put(:key, "_plausible_#{Application.fetch_env!(:plausible, :environment)}")
end
end
Loading…
Cancel
Save