Skip to content

Commit 0ba0549

Browse files
committed
Enable datetime localization for client
- Detect and store client timezone in cookies - Add UserTimezoneMiddleware to activate localization based on cookies Signed-off-by: Keshav Priyadarshi <git@keshav.space>
1 parent d616ce6 commit 0ba0549

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#
2+
# Copyright (c) nexB Inc. and others. All rights reserved.
3+
# VulnerableCode is a trademark of nexB Inc.
4+
# SPDX-License-Identifier: Apache-2.0
5+
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
6+
# See https://github.com/aboutcode-org/vulnerablecode for support or download.
7+
# See https://aboutcode.org for more information about nexB OSS projects.
8+
#
9+
10+
import zoneinfo
11+
12+
from django.utils import timezone
13+
14+
15+
class UserTimezoneMiddleware:
16+
def __init__(self, get_response):
17+
self.get_response = get_response
18+
19+
def __call__(self, request):
20+
try:
21+
# Activate local timezone for user using cookies
22+
tzname = request.COOKIES.get("user_timezone")
23+
if tzname:
24+
timezone.activate(zoneinfo.ZoneInfo(tzname))
25+
else:
26+
timezone.deactivate()
27+
except Exception as e:
28+
timezone.deactivate()
29+
30+
return self.get_response(request)

vulnerabilities/templates/base.html

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,13 @@
2222
{% block content %}{% endblock %}
2323
{% include "footer.html" %}
2424
</div>
25-
25+
<script>
26+
// Since django can not determine the client’s time zone automatically.
27+
// Store client's timezone in cookies to enable localization.
28+
// https://docs.djangoproject.com/en/5.1/topics/i18n/timezones/#selecting-the-current-time-zone
29+
const currentTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
30+
document.cookie = "user_timezone=" + currentTimeZone;
31+
</script>
2632
{% block scripts %}
2733
{% endblock %}
2834
</body>

vulnerablecode/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@
102102
"django.contrib.messages.middleware.MessageMiddleware",
103103
"django.middleware.clickjacking.XFrameOptionsMiddleware",
104104
"vulnerabilities.middleware.ban_user_agent.BanUserAgent",
105+
"vulnerabilities.middleware.timezone.UserTimezoneMiddleware",
105106
)
106107

107108
ROOT_URLCONF = "vulnerablecode.urls"

0 commit comments

Comments
 (0)