Refs #27795 -- Removed force_bytes() usage in sessions.

SessionBase.decode() is the inverse operation to SessionBase.encode().
As SessionBase.encode() always returns a string, SessionBase.decode()
should always be passed a string argument. Fixed the file backend, which
was the only backend still passing a bytestring.
This commit is contained in:
Jon Dufresne 2018-10-02 21:04:12 -07:00 committed by Carlton Gibson
parent efd8a82e26
commit bdae19cf63
3 changed files with 3 additions and 4 deletions

View File

@ -10,7 +10,6 @@ from django.utils import timezone
from django.utils.crypto import (
constant_time_compare, get_random_string, salted_hmac,
)
from django.utils.encoding import force_bytes
from django.utils.module_loading import import_string
# session_key should not be case sensitive because some backends can store it
@ -98,7 +97,7 @@ class SessionBase:
return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii')
def decode(self, session_data):
encoded_data = base64.b64decode(force_bytes(session_data))
encoded_data = base64.b64decode(session_data.encode('ascii'))
try:
# could produce ValueError if there is no ':'
hash, serialized = encoded_data.split(b':', 1)

View File

@ -75,7 +75,7 @@ class SessionStore(SessionBase):
def load(self):
session_data = {}
try:
with open(self._key_to_file(), "rb") as session_file:
with open(self._key_to_file(), "r", encoding="ascii") as session_file:
file_data = session_file.read()
# Don't fail if there is no data in the session file.
# We may have opened the empty placeholder file.

View File

@ -311,7 +311,7 @@ class SessionTestsMixin:
self.assertEqual(self.session.decode(encoded), data)
def test_decode_failure_logged_to_security(self):
bad_encode = base64.b64encode(b'flaskdj:alkdjf')
bad_encode = base64.b64encode(b'flaskdj:alkdjf').decode('ascii')
with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm:
self.assertEqual({}, self.session.decode(bad_encode))
# The failed decode is logged.