Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Activate the time zone after the authentication middlewares

Roland Geidercc424767eb90
diff --git a/wger/core/middleware.py b/wger/core/middleware.py
index 3c9f65e3c..a1770e6d0 100644
--- a/wger/core/middleware.py
+++ b/wger/core/middleware.py
@@ -168,20 +168,26 @@ class AuthProxyHeaderMiddleware(MiddlewareMixin):
class TimezoneMiddleware:
"""
- Activates the current user's stored time_zone for the duration of the
- request, default is server's global TIME_ZONE
+ Activates the requesting user's time zone for the duration of the request
+
+ This is for rendering only: it decides the offset of the timestamps in a
+ response and the zone a date filter is resolved in. What day a stored row
+ counts for is derived from the zone of the user the row belongs to, which
+ is not necessarily the one asking.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
+ # wger
+ from wger.core.models import UserProfile
+
user = getattr(request, 'user', None)
if user is not None and user.is_authenticated:
try:
timezone.activate(user.userprofile.zone_info)
- except Exception:
- # Falls back to Django's default (settings.TIME_ZONE)
+ except UserProfile.DoesNotExist:
timezone.deactivate()
else:
timezone.deactivate()
diff --git a/wger/core/migrations/0028_userprofile_timezone.py b/wger/core/migrations/0028_userprofile_timezone.py
index 8014fc033..334a2169a 100644
--- a/wger/core/migrations/0028_userprofile_timezone.py
+++ b/wger/core/migrations/0028_userprofile_timezone.py
@@ -1,5 +1,4 @@
# Django
-from django.conf import settings
from django.db import migrations, models
# wger
@@ -16,7 +15,8 @@ class Migration(migrations.Migration):
model_name='userprofile',
name='time_zone',
field=models.CharField(
- default=settings.TIME_ZONE,
+ blank=True,
+ default='',
max_length=50,
validators=[validate_timezone],
verbose_name='Timezone',
diff --git a/wger/core/models/profile.py b/wger/core/models/profile.py
index 9135db5be..feaaacbd7 100644
--- a/wger/core/models/profile.py
+++ b/wger/core/models/profile.py
@@ -19,6 +19,7 @@ import datetime
import decimal
from zoneinfo import (
ZoneInfo,
+ ZoneInfoNotFoundError,
available_timezones,
)
@@ -72,9 +73,11 @@ def birthdate_validator(birthdate):
def validate_timezone(value: str) -> None:
"""
Validates that the given string is a real IANA timezone name.
+
+ An empty value is allowed and means that no client has reported one.
"""
- if value not in available_timezones():
- raise ValidationError(f'"{value} is not a valid IANA timezone name')
+ if value and value not in available_timezones():
+ raise ValidationError(f'"{value}" is not a valid IANA timezone name')
class UserProfile(models.Model):
@@ -341,12 +344,17 @@ class UserProfile(models.Model):
time_zone = models.CharField(
verbose_name='Timezone',
max_length=50,
- default=settings.TIME_ZONE,
+ blank=True,
+ default='',
validators=[validate_timezone],
)
"""
IANA timezone name (e.g. "Europe/Berlin") used to compute what calendar day
a workout session, log, or other "local" event counts for.
+
+ Empty means no client has reported one. That is not the same as the instance
+ timezone: features that would rather say nothing than say something wrong
+ check for it, see the time trophies.
"""
#
@@ -467,12 +475,18 @@ class UserProfile(models.Model):
@property
def zone_info(self) -> ZoneInfo:
"""
- Returns the parsed ZoneInfo object for this user's timezone
+ The user's timezone, falling back to the instance one
+
+ This is the only place the fallback is spelled out. Use
+ ``time_zone`` itself to tell a reported zone from an assumed one.
"""
+ if not self.time_zone:
+ return timezone.get_default_timezone()
+
try:
return ZoneInfo(self.time_zone)
- except Exception:
- return ZoneInfo(settings.TIME_ZONE)
+ except (ZoneInfoNotFoundError, ValueError):
+ return timezone.get_default_timezone()
def calculate_bmi(self):
"""
diff --git a/wger/manager/models/session.py b/wger/manager/models/session.py
index a2d4dbfe5..6f52f9ce5 100644
--- a/wger/manager/models/session.py
+++ b/wger/manager/models/session.py
@@ -133,9 +133,10 @@ class WorkoutSession(models.Model):
"""
The calendar day this session counts for, e.g. for streaks
- A session that runs over midnight counts for the day it started on. The
- day is derived in the instance timezone; there is no per-user timezone
- yet, see the ORM equivalent ``datetime_start__date``.
+ A session that runs over midnight counts for the day it started on, in
+ the timezone of the user it belongs to and not in the one of whoever is
+ asking. An ORM lookup such as ``datetime_start__date`` resolves in the
+ active timezone instead and is not an equivalent.
"""
if not self.datetime_start:
return None