Skip to content

Commit e0578f4

Browse files
committed
feat: add middleware to auto select user language
1 parent a14a61d commit e0578f4

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/ol_openedx_course_translations/ol_openedx_course_translations/apps.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,8 @@ class OLOpenedXCourseTranslationsConfig(AppConfig):
1919
ProjectType.CMS: {
2020
SettingsType.COMMON: {PluginSettings.RELATIVE_PATH: "settings.common"},
2121
},
22+
ProjectType.LMS: {
23+
SettingsType.COMMON: {PluginSettings.RELATIVE_PATH: "settings.common"},
24+
},
2225
},
2326
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# python
2+
import re
3+
4+
from django.utils.deprecation import MiddlewareMixin
5+
from opaque_keys.edx.keys import CourseKey
6+
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
7+
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
8+
from openedx.core.djangoapps.user_api.preferences.api import set_user_preference
9+
10+
11+
class CourseLanguageCookieMiddleware(MiddlewareMixin):
12+
"""
13+
Sets language preference cookie and user preference based on course language.
14+
"""
15+
16+
COURSE_URL_REGEX = re.compile(
17+
r"^/courses/(?P<course_key>course-v1:[A-Za-z0-9._-]+(?:\+[A-Za-z0-9._-]+)+)(?:/|$)",
18+
re.IGNORECASE,
19+
)
20+
COOKIE_NAME = "openedx-language-preference"
21+
22+
def process_response(self, request, response):
23+
path = getattr(request, "path_info", request.path)
24+
match = self.COURSE_URL_REGEX.match(path)
25+
if not match:
26+
return response
27+
28+
course_key_str = match.group("course_key")
29+
try:
30+
course_key = CourseKey.from_string(course_key_str)
31+
overview = CourseOverview.get_from_id(course_key)
32+
except Exception: # noqa: BLE001
33+
return response
34+
35+
language = getattr(overview, "language", None)
36+
response.set_cookie(
37+
self.COOKIE_NAME,
38+
language or "",
39+
max_age=60 * 60 * 24 * 180,
40+
httponly=False,
41+
samesite="Lax",
42+
)
43+
44+
# Set user preference if authenticated
45+
if language and hasattr(request, "user") and request.user.is_authenticated:
46+
set_user_preference(request.user, LANGUAGE_KEY, language)
47+
48+
return response

0 commit comments

Comments
 (0)