Code

Ticket #8122: 8122-r8277.diff

File 8122-r8277.diff, 7.8 KB (added by jcassee, 6 years ago)
Line 
1Index: django/contrib/sessions/backends/base.py
2===================================================================
3--- django/contrib/sessions/backends/base.py    (revision 8277)
4+++ django/contrib/sessions/backends/base.py    (working copy)
5@@ -18,13 +18,12 @@
6     """
7     Base class for all Session classes.
8     """
9-    TEST_COOKIE_NAME = 'testcookie'
10-    TEST_COOKIE_VALUE = 'worked'
11 
12     def __init__(self, session_key=None):
13         self._session_key = session_key
14         self.accessed = False
15         self.modified = False
16+        self.cookie_received = (session_key is not None)
17 
18     def __contains__(self, key):
19         return key in self._session
20@@ -62,15 +61,19 @@
21             return value
22 
23     def set_test_cookie(self):
24-        self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE
25+        from warnings import warn
26+        warn('set_test_cookie() is deprecated. It is no longer required.')
27 
28     def test_cookie_worked(self):
29-        return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE
30+        from warnings import warn
31+        warn('test_cookie_worked() is deprecated. Use request.cookie_received')
32+        return self.cookie_received
33 
34     def delete_test_cookie(self):
35-        del self[self.TEST_COOKIE_NAME]
36+        from warnings import warn
37+        warn('delete_test_cookie() is deprecated. It is no longer required.')
38 
39-    def encode(self, session_dict):
40+    def encode(self, session_dict):
41         "Returns the given session dictionary pickled and encoded as a string."
42         pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
43         pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
44Index: django/contrib/sessions/middleware.py
45===================================================================
46--- django/contrib/sessions/middleware.py       (revision 8277)
47+++ django/contrib/sessions/middleware.py       (working copy)
48@@ -22,18 +22,25 @@
49             if accessed:
50                 patch_vary_headers(response, ('Cookie',))
51             if modified or settings.SESSION_SAVE_EVERY_REQUEST:
52-                if request.session.get_expire_at_browser_close():
53-                    max_age = None
54-                    expires = None
55-                else:
56-                    max_age = request.session.get_expiry_age()
57-                    expires_time = time.time() + max_age
58-                    expires = cookie_date(expires_time)
59                 # Save the session data and refresh the client cookie.
60                 request.session.save()
61-                response.set_cookie(settings.SESSION_COOKIE_NAME,
62-                        request.session.session_key, max_age=max_age,
63-                        expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
64-                        path=settings.SESSION_COOKIE_PATH,
65-                        secure=settings.SESSION_COOKIE_SECURE or None)
66+                self.set_session_cookie(request, response,
67+                        request.session.session_key)
68+            elif not request.session.cookie_received:
69+                # Set a temporary cookie
70+                self.set_session_cookie(request, response, '')
71         return response
72+
73+    def set_session_cookie(self, request, response, value):
74+        if request.session.get_expire_at_browser_close():
75+            max_age = None
76+            expires = None
77+        else:
78+            max_age = request.session.get_expiry_age()
79+            expires_time = time.time() + max_age
80+            expires = cookie_date(expires_time)
81+        response.set_cookie(settings.SESSION_COOKIE_NAME, value,
82+                max_age=max_age, expires=expires,
83+                domain=settings.SESSION_COOKIE_DOMAIN,
84+                path=settings.SESSION_COOKIE_PATH,
85+                secure=settings.SESSION_COOKIE_SECURE or None)
86Index: tests/regressiontests/sessions_regress/__init__.py
87===================================================================
88Index: tests/regressiontests/sessions_regress/tests.py
89===================================================================
90--- tests/regressiontests/sessions_regress/tests.py     (revision 0)
91+++ tests/regressiontests/sessions_regress/tests.py     (revision 0)
92@@ -0,0 +1,79 @@
93+# -*- coding: utf-8 -*-
94+
95+from django.test import TestCase
96+from django.http import HttpRequest, HttpResponse
97+from django.contrib.sessions.middleware import SessionMiddleware
98+from django.conf import settings
99+
100+class SessionMiddlewareTest(TestCase):
101+    def test_no_cookie(self):
102+        """
103+        Tests that the session middleware works when the client does not send
104+        a session cookie.
105+        """
106+        middleware = SessionMiddleware()
107+        request = HttpRequest()
108+        middleware.process_request(request)
109+        assert not request.session.cookie_received
110+        response = middleware.process_response(request, HttpResponse())
111+        assert settings.SESSION_COOKIE_NAME in response.cookies
112+        assert response.cookies[settings.SESSION_COOKIE_NAME].value == ''
113+
114+    def test_empty_cookie(self):
115+        """
116+        Tests that the session middleware works when the client sends an empty
117+        session cookie.
118+        """
119+        middleware = SessionMiddleware()
120+        request = HttpRequest()
121+        request.COOKIES[settings.SESSION_COOKIE_NAME] = ''
122+        middleware.process_request(request)
123+        assert request.session.cookie_received
124+        response = middleware.process_response(request, HttpResponse())
125+        assert not settings.SESSION_COOKIE_NAME in response.cookies
126+
127+    def test_valid_cookie(self):
128+        """
129+        Tests that the session middleware works when the client sends a valid
130+        session cookie.
131+        """
132+        # First get valid session id
133+        middleware = SessionMiddleware()
134+        request = HttpRequest()
135+        middleware.process_request(request)
136+       request.session['test'] = 'test'
137+        response = middleware.process_response(request, HttpResponse())
138+        sessionid = response.cookies[settings.SESSION_COOKIE_NAME].value
139+       assert sessionid != ''
140+        # Now check behavior for valid session id
141+        request = HttpRequest()
142+        request.COOKIES[settings.SESSION_COOKIE_NAME] = sessionid
143+        middleware.process_request(request)
144+        assert request.session.cookie_received
145+       assert request.session['test'] == 'test'
146+        response = middleware.process_response(request, HttpResponse())
147+        assert not settings.SESSION_COOKIE_NAME in response.cookies
148+
149+    def test_invalid_cookie(self):
150+        """
151+        Tests that the session middleware works when the client sends an
152+        invalid session cookie.
153+        """
154+        # First get valid session id
155+        middleware = SessionMiddleware()
156+        request = HttpRequest()
157+        middleware.process_request(request)
158+       request.session['test'] = 'test'
159+        response = middleware.process_response(request, HttpResponse())
160+        sessionid = response.cookies[settings.SESSION_COOKIE_NAME].value
161+       assert sessionid != ''
162+        # Now check behavior for invalid session id
163+        request = HttpRequest()
164+        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'invalid'
165+        middleware.process_request(request)
166+        assert request.session.cookie_received
167+       assert 'test' not in request.session
168+        response = middleware.process_response(request, HttpResponse())
169+        assert settings.SESSION_COOKIE_NAME in response.cookies
170+        assert response.cookies[settings.SESSION_COOKIE_NAME] != ''
171+        assert response.cookies[settings.SESSION_COOKIE_NAME] != sessionid
172Index: tests/regressiontests/sessions_regress/models.py
173===================================================================
174--- tests/regressiontests/sessions_regress/models.py    (revision 0)
175+++ tests/regressiontests/sessions_regress/models.py    (revision 0)
176@@ -0,0 +1 @@
177+# models.py file for tests to run.