Skip to content

Commit

Permalink
16995 Move language handling to Middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
m2martin committed Aug 10, 2024
1 parent f6c1642 commit f04d6c1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
4 changes: 0 additions & 4 deletions netbox/account/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,6 @@ def post(self, request):

response = self.redirect_to_next(request, logger)

# Set the user's preferred language (if any)
if language := request.user.config.get('locale.language'):
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age=request.session.get_expiry_age())

return response

else:
Expand Down
23 changes: 21 additions & 2 deletions netbox/netbox/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from django.db import connection, ProgrammingError
from django.db.utils import InternalError
from django.http import Http404, HttpResponseRedirect
from django.utils import translation

from extras.context_managers import event_tracking
from netbox.config import clear_config, get_config
Expand Down Expand Up @@ -43,12 +44,30 @@ def __call__(self, request):
login_url = f'{settings.LOGIN_URL}?next={parse.quote(request.get_full_path_info())}'
return HttpResponseRedirect(login_url)

# Check if the language should be activated before the language cookie has been set.
# This will happen for instance on the first request after login.
# The language will have been already activated by the framework if the cookie exists.
if (
request.user.is_authenticated and
settings.LANGUAGE_COOKIE_NAME not in request.COOKIES and
hasattr(request.user, 'config')
):
if language := request.user.config.get('locale.language'):
translation.activate(language)

# Enable the event_tracking context manager and process the request.
with event_tracking(request):
response = self.get_response(request)

# Check if language cookie should be renewed
if request.user.is_authenticated and settings.SESSION_SAVE_EVERY_REQUEST:
# Check if language cookie should be renewed (persistent logins) or set when it does not exist, yet
if (
request.user.is_authenticated and
hasattr(request.user, 'config') and
(
settings.SESSION_SAVE_EVERY_REQUEST or
settings.LANGUAGE_COOKIE_NAME not in request.COOKIES
)
):
if language := request.user.config.get('locale.language'):
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age=request.session.get_expiry_age())

Expand Down

0 comments on commit f04d6c1

Please sign in to comment.