diff options
| author | Bobby <[email protected]> | 2023-05-31 18:00:28 -0400 |
|---|---|---|
| committer | Bobby <[email protected]> | 2023-05-31 18:00:28 -0400 |
| commit | aa41643172a32dc81cf6d214289e1dedf998953d (patch) | |
| tree | 49b8ca61d5d6cad866fa7fd09ebc4bf2f7f94259 /middleware | |
| parent | 6c683c5b067b019e93619557a358e7f67c2e4d7b (diff) | |
| download | thatcomputerscientist-aa41643172a32dc81cf6d214289e1dedf998953d.tar.xz thatcomputerscientist-aa41643172a32dc81cf6d214289e1dedf998953d.zip | |
Allow Anonymous Commenting
Diffstat (limited to 'middleware')
| -rw-r--r-- | middleware/tz.py | 32 | ||||
| -rw-r--r-- | middleware/uuidmiddleware.py | 4 |
2 files changed, 35 insertions, 1 deletions
diff --git a/middleware/tz.py b/middleware/tz.py new file mode 100644 index 00000000..4aa3087a --- /dev/null +++ b/middleware/tz.py @@ -0,0 +1,32 @@ +import requests + + +# make sure you add `TimezoneMiddleware` appropriately in settings.py +class TimezoneMiddleware(object): + """ + Middleware to properly handle the users timezone + """ + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + # get the user's timezone from the cookie + user_timezone = request.COOKIES.get('user_timezone') + + if not user_timezone: + x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') + + if x_forwarded_for: + remote_ip = x_forwarded_for.split(',')[0] + else: + remote_ip = request.META.get('REMOTE_ADDR') + + geo_data = requests.get(f'http://ip-api.com/json/{remote_ip}').json() + user_timezone = geo_data['timezone'] + + if user_timezone: + response = self.get_response(request) + response.set_cookie('user_timezone', user_timezone, max_age=31536000) + return response + return self.get_response(request) diff --git a/middleware/uuidmiddleware.py b/middleware/uuidmiddleware.py index fc97cd58..bf920718 100644 --- a/middleware/uuidmiddleware.py +++ b/middleware/uuidmiddleware.py @@ -1,6 +1,8 @@ import uuid -from django.core.cache import cache + from django.conf import settings +from django.core.cache import cache + class UserUUIDMiddleware: # assign a uuid to the user if they don't have one |
