@@ -53,21 +53,19 @@ def process_request(self, request):
5353 # authenticated remote-user, or return (leaving request.user set to
5454 # AnonymousUser by the AuthenticationMiddleware).
5555 if request .user .is_authenticated ():
56- try :
57- stored_backend = load_backend (request .session .get (
58- auth .BACKEND_SESSION_KEY , '' ))
59- if isinstance (stored_backend , RemoteUserBackend ):
60- auth .logout (request )
61- except ImproperlyConfigured as e :
62- # backend failed to load
63- auth .logout (request )
56+ self ._remove_invalid_user (request )
6457 return
6558 # If the user is already authenticated and that user is the user we are
6659 # getting passed in the headers, then the correct user is already
6760 # persisted in the session and we don't need to continue.
6861 if request .user .is_authenticated ():
6962 if request .user .get_username () == self .clean_username (username , request ):
7063 return
64+ else :
65+ # An authenticated user is associated with the request, but
66+ # it does not match the authorized user in the header.
67+ self ._remove_invalid_user (request )
68+
7169 # We are seeing this user for the first time in this session, attempt
7270 # to authenticate the user.
7371 user = auth .authenticate (remote_user = username )
@@ -89,3 +87,17 @@ def clean_username(self, username, request):
8987 except AttributeError : # Backend has no clean_username method.
9088 pass
9189 return username
90+
91+ def _remove_invalid_user (self , request ):
92+ """
93+ Removes the current authenticated user in the request which is invalid
94+ but only if the user is authenticated via the RemoteUserBackend.
95+ """
96+ try :
97+ stored_backend = load_backend (request .session .get (auth .BACKEND_SESSION_KEY , '' ))
98+ except ImproperlyConfigured :
99+ # backend failed to load
100+ auth .logout (request )
101+ else :
102+ if isinstance (stored_backend , RemoteUserBackend ):
103+ auth .logout (request )
0 commit comments