Skip to content

Commit 68bb1d2

Browse files
fix(locale): guard LiveView mounts against legacy nil session locales
The pre-localize PutSession plug wrote the CLDR tag's gettext_locale_name into the session verbatim, which could be nil. Such a session matched the on_mount pattern and Gettext.put_locale/2 raises on nil, crashing every LiveView mount for that browser until the cookie is replaced. Only accept binary locale values; anything else falls back to the Gettext default. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 922d1f6 commit 68bb1d2

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

lib/teslamate_web/live/init_assigns.ex

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,15 @@ defmodule TeslaMateWeb.InitAssigns do
66
import Phoenix.Component
77

88
def on_mount(:locale, _params, session, socket) do
9+
# is_binary: the pre-localize PutSession plug wrote the CLDR tag's
10+
# gettext_locale_name verbatim, which could be nil — and
11+
# Gettext.put_locale/2 raises on nil.
912
case session do
10-
%{"gettext_locale" => locale} -> Gettext.put_locale(TeslaMateWeb.Gettext, locale)
11-
_other -> :ok
13+
%{"gettext_locale" => locale} when is_binary(locale) ->
14+
Gettext.put_locale(TeslaMateWeb.Gettext, locale)
15+
16+
_other ->
17+
:ok
1218
end
1319

1420
{:cont, assign(socket, :locale, Gettext.get_locale(TeslaMateWeb.Gettext))}

test/teslamate_web/locale_test.exs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,18 @@ defmodule TeslaMateWeb.LocaleTest do
128128
assert html =~ "Einstellungen"
129129
end
130130

131+
test "LiveView mounts ignore legacy nil session locales" do
132+
assert {:cont, socket} =
133+
TeslaMateWeb.InitAssigns.on_mount(
134+
:locale,
135+
%{},
136+
%{"gettext_locale" => nil},
137+
%Phoenix.LiveView.Socket{}
138+
)
139+
140+
assert socket.assigns.locale == "en"
141+
end
142+
131143
test "supported_locales config stays in sync with the Gettext locales" do
132144
configured =
133145
:localize

0 commit comments

Comments
 (0)