mitgliederverwaltung/lib/mv_web/live_user_auth.ex
Moritz a7ad608051 fix(auth): redirect a live-view socket in the user-required guard
LiveSession.assign_new_resources/2 is typed to return a Phoenix.Socket, which made the on_mount redirect type-incompatible. The authenticated-routes live_session already assigns current_user, so the guard reads it from socket.assigns directly. Also assign the locale into the socket actually used by the no-user redirect instead of discarding it.
2026-06-02 12:19:21 +02:00

56 lines
1.6 KiB
Elixir

defmodule MvWeb.LiveUserAuth do
@moduledoc """
Helpers for authenticating users in LiveViews.
"""
import Phoenix.Component
use MvWeb, :verified_routes
alias AshAuthentication.Phoenix.LiveSession
alias Phoenix.LiveView
# This is used for nested liveviews to fetch the current user.
# To use, place the following at the top of that liveview:
# on_mount {MvWeb.LiveUserAuth, :current_user}
def on_mount(:current_user, _params, session, socket) do
return_to = session[:return_to]
socket =
socket
|> assign(:return_to, return_to)
|> LiveSession.assign_new_resources(session)
{:cont, session, socket}
end
def on_mount(:live_user_optional, _params, _session, socket) do
if socket.assigns[:current_user] do
{:cont, socket}
else
{:cont, assign(socket, :current_user, nil)}
end
end
def on_mount(:live_user_required, _params, _session, socket) do
case socket.assigns do
%{current_user: %{} = user} ->
{:cont, assign(socket, :current_user, user)}
_ ->
{:halt, LiveView.redirect(socket, to: ~p"/sign-in")}
end
end
def on_mount(:live_no_user, _params, session, socket) do
# Set the locale for not logged in user (default from config, "de" in dev/prod).
locale = session["locale"] || Application.get_env(:mv, :default_locale, "de")
_ = Gettext.put_locale(MvWeb.Gettext, locale)
socket = assign(socket, :locale, locale)
if socket.assigns[:current_user] do
{:halt, LiveView.redirect(socket, to: ~p"/")}
else
{:cont, assign(socket, :current_user, nil)}
end
end
end