analytics/lib/plausible_web/controllers/helpers.ex
Adrian Gruntkowski bd93cf3b46
Refactor and consolidate user session logic (#4452)
* Extract session management from AuthController

* Don't explicitly pass `current_user_id` to `live_render`'s session

* Add ability to retrieve session and user from token via `UserAuth`

* Always fetch current user (or just id) via `UserAuth` API

* Introduce `UserSession` as an embedded schema for now

* Make `UserAuth.get_user/1` accept `UserSession` as an input

* Introduce LV auth context populating user data from session on mount

* Refactor `AuthPlug` and make it populate `current_user_session` as well

* Rely on authenticated user data provided by auth plug or LV context

* Make `Sites.get_for_user(!)` accept `User` struct as well

* Set `logged_in` cookie explicitly when it's out of sync with session

* Expand modules documentation a bit

* Improve and extend tests slightly
2024-08-23 10:53:33 +02:00

44 lines
1.2 KiB
Elixir

defmodule PlausibleWeb.ControllerHelpers do
import Plug.Conn
import Phoenix.Controller
def render_error(conn, status, message) do
conn
|> put_status(status)
|> put_view(PlausibleWeb.ErrorView)
|> render("#{status}.html", message: message, layout: error_layout())
end
def render_error(conn, status) do
conn
|> put_status(status)
|> put_view(PlausibleWeb.ErrorView)
|> render("#{status}.html", layout: error_layout())
end
defp error_layout,
do: Application.get_env(:plausible, PlausibleWeb.Endpoint)[:render_errors][:layout]
def debug_metadata(conn) do
%{
request_method: conn.method,
request_path: conn.request_path,
params: conn.params,
phoenix_controller: conn.private.phoenix_controller |> to_string(),
phoenix_action: conn.private.phoenix_action |> to_string(),
site_id: conn.assigns.site.id,
site_domain: conn.assigns.site.domain,
user_id: get_user_id(conn, conn.assigns)
}
end
defp get_user_id(_conn, %{current_user: user}), do: user.id
defp get_user_id(conn, _assigns) do
case PlausibleWeb.UserAuth.get_user_session(conn) do
{:ok, user_session} -> user_session.user_id
_ -> nil
end
end
end