Skip to content

Commit

Permalink
fixup
Browse files Browse the repository at this point in the history
  • Loading branch information
hmpf committed Mar 5, 2024
1 parent 780e2c7 commit 11e0bb4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
2 changes: 1 addition & 1 deletion python/nav/django/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@
'django.contrib.messages.middleware.MessageMiddleware',
)

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
SESSION_SERIALIZER = 'nav.web.utils.NAVSessionJSONSerializer'
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_COOKIE_AGE = int(_webfront_config.get('sessions', {}).get('timeout', 3600))
SESSION_COOKIE_NAME = 'nav_sessionid'
Expand Down
43 changes: 41 additions & 2 deletions python/nav/web/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
#
"""Utils for views"""

from django.http import HttpResponse

from datetime import datetime
import json

from django.contrib.sessions.serializers import JSONSerializer
from django.http import HttpResponse
from django.views.generic.list import ListView


Expand Down Expand Up @@ -64,3 +66,40 @@ def wrapper(request, *args, **kwargs):
return wrapper

return wrap


class DateTimeJSONEncoder(json.JSONEncoder):
def default(self, obj):
# See "Date Time String Format" in the ECMA-262 specification.
if isinstance(obj, datetime.datetime):
result = obj.isoformat()
if obj.microsecond:
result = result[:23] + result[26:]
if result.endswith("+00:00"):
result = result[:-6] + "Z"
return result
else:
return super().default(obj)


def decode_datetime_from_json(self, s):
if set(('T', '-', ':')) < set(s):
# Potentially a datetime
new_s = s[:]
if s.endswith('Z'):
new_s = s[-1] + '+00:00'
try:
return datetime.fromisoformat(new_s)
except ValueError:
pass
return self.decode(s)


class NAVSessionJSONSerializer(JSONSerializer):
def dumps(self, obj):
return json.dumps(obj, separators=(",", ":"), cls=DateTimeJSONEncoder).encode(
"latin-1"
)

def loads(self, data):
return json.loads(data.decode("latin-1"), object_hook=decode_datetime_from_json)

0 comments on commit 11e0bb4

Please sign in to comment.