11from django .contrib import auth
2+ from django .contrib .auth .backends import RemoteUserBackend
23from django .core .exceptions import ImproperlyConfigured
34from django .utils .functional import SimpleLazyObject
45
@@ -47,16 +48,23 @@ def process_request(self, request):
4748 try :
4849 username = request .META [self .header ]
4950 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 )
5356 return
5457 # If the user is already authenticated and that user is the user we are
5558 # getting passed in the headers, then the correct user is already
5659 # persisted in the session and we don't need to continue.
5760 if request .user .is_authenticated ():
5861 if request .user .username == self .clean_username (username , request ):
5962 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+
6068 # We are seeing this user for the first time in this session, attempt
6169 # to authenticate the user.
6270 user = auth .authenticate (remote_user = username )
@@ -78,3 +86,17 @@ def clean_username(self, username, request):
7886 except AttributeError : # Backend has no clean_username method.
7987 pass
8088 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