Code

Ticket #2548: session_middleware.12.diff

File session_middleware.12.diff, 7.6 KB (added by SmileyChris, 7 years ago)

tests added

Line 
1Index: AUTHORS
2===================================================================
3--- AUTHORS     (revision 5468)
4+++ AUTHORS     (working copy)
5@@ -229,7 +229,7 @@
6     Karen Tracey <graybark@bellsouth.net>
7     Makoto Tsuyuki <mtsuyuki@gmail.com>
8     tt@gurgle.no
9-    Amit Upadhyay
10+    Amit Upadhyay <http://www.amitu.com/blog/>
11     Geert Vanderkelen
12     viestards.lists@gmail.com
13     Milton Waddams
14Index: django/contrib/sessions/middleware.py
15===================================================================
16--- django/contrib/sessions/middleware.py       (revision 5468)
17+++ django/contrib/sessions/middleware.py       (working copy)
18@@ -48,6 +48,21 @@
19     def delete_test_cookie(self):
20         del self[TEST_COOKIE_NAME]
21 
22+    def get_session_age(self):
23+        return self.get('_session_age', settings.SESSION_COOKIE_AGE)
24+    def set_session_age(self, seconds):
25+        " Sets the life of the session, irrespective of global settings. "
26+        if not seconds:
27+            try:
28+                del self['_session_age']
29+            except KeyError:
30+                pass
31+        else:
32+            self['_session_age'] = seconds
33+
34+    def get_expire_at_browser_close(self):
35+        return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE and ('_session_age' not in self)
36+
37     def _get_session(self):
38         # Lazily loads session from storage.
39         self.accessed = True
40@@ -92,15 +107,16 @@
41                     obj = Session.objects.get_new_session_object()
42                     session_key = obj.session_key
43 
44-                if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
45-                    max_age = None
46-                    expires = None
47-                else:
48-                    max_age = settings.SESSION_COOKIE_AGE
49-                    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
50-                new_session = Session.objects.save(session_key, request.session._session,
51-                    datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE))
52-                response.set_cookie(settings.SESSION_COOKIE_NAME, session_key,
53-                    max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
54+                session_age = request.session.get_session_age()
55+                delta_age = datetime.timedelta(seconds=session_age)
56+                if request.session.get_expire_at_browser_close():
57+                    session_age = None
58+                    expires = None
59+                else:
60+                    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + delta_age, "%a, %d-%b-%Y %H:%M:%S GMT")
61+                Session.objects.save(session_key, request.session._session, datetime.datetime.now() + delta_age)
62+                response.set_cookie(
63+                    settings.SESSION_COOKIE_NAME, session_key,
64+                    max_age=session_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
65                     secure=settings.SESSION_COOKIE_SECURE or None)
66         return response
67Index: django/contrib/sessions/tests.py
68===================================================================
69--- django/contrib/sessions/tests.py    (revision 5468)
70+++ django/contrib/sessions/tests.py    (working copy)
71@@ -10,6 +10,61 @@
72 
73 >>> s.pop('some key', 'does not exist')
74 'does not exist'
75+
76+########################
77+# session_age settings #
78+########################
79+
80+>>> from django.conf import settings
81+>>> s.get_session_age() == settings.SESSION_COOKIE_AGE
82+True
83+
84+# Custom session age
85+>>> s.set_session_age(10)
86+>>> s.get_session_age()
87+10
88+
89+# Set back to default session age
90+>>> s.set_session_age(0)
91+>>> s.get_session_age() == settings.SESSION_COOKIE_AGE
92+True
93+
94+# Allow to set back to default session age even if no alternate has been set
95+>>> s.set_session_age(0)
96+
97+###############################
98+# get_expire_at_browser_close #
99+###############################
100+
101+# A bit hackish: we're changing the setting then reverting back to
102+# the original setting just in case at the end of these tests.
103+>>> original_setting = settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
104+
105+>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
106+
107+# Custom session age
108+>>> s.set_session_age(10)
109+>>> s.get_expire_at_browser_close()
110+False
111+
112+# Default session age
113+>>> s.set_session_age(0)
114+>>> s.get_expire_at_browser_close()
115+False
116+
117+>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
118+
119+# Custom session age
120+>>> s.set_session_age(10)
121+>>> s.get_expire_at_browser_close()
122+False
123+
124+# Default session age
125+>>> s.set_session_age(0)
126+>>> s.get_expire_at_browser_close()
127+True
128+
129+>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_setting
130 """
131 
132 from django.contrib.sessions.middleware import SessionWrapper
133Index: docs/sessions.txt
134===================================================================
135--- docs/sessions.txt   (revision 5468)
136+++ docs/sessions.txt   (working copy)
137@@ -39,42 +39,71 @@
138 It implements the following standard dictionary methods:
139 
140     * ``__getitem__(key)``
141+
142       Example: ``fav_color = request.session['fav_color']``
143 
144     * ``__setitem__(key, value)``
145+
146       Example: ``request.session['fav_color'] = 'blue'``
147 
148     * ``__delitem__(key)``
149+
150       Example: ``del request.session['fav_color']``. This raises ``KeyError``
151       if the given ``key`` isn't already in the session.
152 
153     * ``__contains__(key)``
154+
155       Example: ``'fav_color' in request.session``
156 
157     * ``get(key, default=None)``
158+
159       Example: ``fav_color = request.session.get('fav_color', 'red')``
160 
161     * ``keys()``
162 
163     * ``items()``
164 
165-It also has these three methods:
166+It also has these methods:
167 
168     * ``set_test_cookie()``
169+
170       Sets a test cookie to determine whether the user's browser supports
171       cookies. Due to the way cookies work, you won't be able to test this
172       until the user's next page request. See "Setting test cookies" below for
173       more information.
174 
175     * ``test_cookie_worked()``
176+
177       Returns either ``True`` or ``False``, depending on whether the user's
178       browser accepted the test cookie. Due to the way cookies work, you'll
179       have to call ``set_test_cookie()`` on a previous, separate page request.
180       See "Setting test cookies" below for more information.
181 
182     * ``delete_test_cookie()``
183+
184       Deletes the test cookie. Use this to clean up after yourself.
185 
186+    * ``set_session_age(seconds)``
187+
188+      It takes an integer, number of seconds for which the session should be
189+      valid. This will override the default/global session expiry policy.
190+      See `browser-length sessions vs. persistent sessions`_ for default
191+      session expiry policy. To fall back to the global session expiry policy
192+      again, call ``set_session_age(0)``.
193+
194+    * ``get_session_age()``
195+
196+      Returns the age of the session (which will equal
197+      ``settings.SESSION_COOKIE_AGE`` unless it has been overridden by
198+      ``set_session_age``).
199+
200+    * ``get_expire_at_browser_close()``
201+
202+      Returns either ``True`` or ``False``, depending on whether this session
203+      expires at browser close (which will equal
204+      ``settings.SESSION_EXPIRE_AT_BROWSER_CLOSE`` unless the session age
205+      hase been overridden by ``set_session_age``).
206+
207 You can edit ``request.session`` at any point in your view. You can edit it
208 multiple times.
209 
210@@ -217,6 +246,9 @@
211 her browser. Use this if you want people to have to log in every time they open
212 a browser.
213 
214+These settings are global defaults, and can be overwritten by explicitly calling
215+``request.session.set_session_age()`` as described above in `Using sessions in views`_.
216+
217 Clearing the session table
218 ==========================
219