1
1
from django .contrib import auth
2
+ from django .contrib .auth .backends import RemoteUserBackend
2
3
from django .core .exceptions import ImproperlyConfigured
3
4
from django .utils .functional import SimpleLazyObject
4
5
@@ -47,16 +48,23 @@ def process_request(self, request):
47
48
try :
48
49
username = request .META [self .header ]
49
50
except KeyError :
50
- # If specified header doesn't exist then return (leaving
51
- # request.user set to AnonymousUser by the
52
- # AuthenticationMiddleware).
51
+ # If specified header doesn't exist then remove any existing
52
+ # authenticated remote-user, or return (leaving request.user set to
53
+ # AnonymousUser by the AuthenticationMiddleware).
54
+ if request .user .is_authenticated ():
55
+ self ._remove_invalid_user (request )
53
56
return
54
57
# If the user is already authenticated and that user is the user we are
55
58
# getting passed in the headers, then the correct user is already
56
59
# persisted in the session and we don't need to continue.
57
60
if request .user .is_authenticated ():
58
61
if request .user .username == self .clean_username (username , request ):
59
62
return
63
+ else :
64
+ # An authenticated user is associated with the request, but
65
+ # it does not match the authorized user in the header.
66
+ self ._remove_invalid_user (request )
67
+
60
68
# We are seeing this user for the first time in this session, attempt
61
69
# to authenticate the user.
62
70
user = auth .authenticate (remote_user = username )
@@ -78,3 +86,17 @@ def clean_username(self, username, request):
78
86
except AttributeError : # Backend has no clean_username method.
79
87
pass
80
88
return username
89
+
90
+ def _remove_invalid_user (self , request ):
91
+ """
92
+ Removes the current authenticated user in the request which is invalid
93
+ but only if the user is authenticated via the RemoteUserBackend.
94
+ """
95
+ try :
96
+ stored_backend = auth .load_backend (request .session .get (auth .BACKEND_SESSION_KEY , '' ))
97
+ except ImproperlyConfigured :
98
+ # backend failed to load
99
+ auth .logout (request )
100
+ else :
101
+ if isinstance (stored_backend , RemoteUserBackend ):
102
+ auth .logout (request )
0 commit comments