Code

Ticket #6941: clear_session_on_logout_and_login2.diff

File clear_session_on_logout_and_login2.diff, 1.5 KB (added by mrts, 6 years ago)

Minor improvement to logout().

Line 
1Index: django/contrib/auth/__init__.py
2===================================================================
3--- django/contrib/auth/__init__.py     (revision 8160)
4+++ django/contrib/auth/__init__.py     (working copy)
5@@ -53,23 +53,30 @@
6     # TODO: It would be nice to support different login methods, like signed cookies.
7     user.last_login = datetime.datetime.now()
8     user.save()
9+    if request.session.get(SESSION_KEY, user.id) != user.id:
10+        # a different user was logged in, his data has to be cleared
11+        request.session.destroy()
12     request.session[SESSION_KEY] = user.id
13     request.session[BACKEND_SESSION_KEY] = user.backend
14     if hasattr(request, 'user'):
15         request.user = user
16 
17-def logout(request):
18+def logout(request, clear_session=True):
19     """
20-    Remove the authenticated user's ID from the request.
21+    Remove the authenticated user's ID from the request and optionally clear
22+    the session.
23     """
24-    try:
25-        del request.session[SESSION_KEY]
26-    except KeyError:
27-        pass
28-    try:
29-        del request.session[BACKEND_SESSION_KEY]
30-    except KeyError:
31-        pass
32+    if clear_session:
33+        request.session.destroy()
34+    else:
35+        try:
36+            del request.session[SESSION_KEY]
37+        except KeyError:
38+            pass
39+        try:
40+            del request.session[BACKEND_SESSION_KEY]
41+        except KeyError:
42+            pass
43     if hasattr(request, 'user'):
44         from django.contrib.auth.models import AnonymousUser
45         request.user = AnonymousUser()