@@ -76,21 +76,19 @@ def process_request(self, request):
76
76
# authenticated remote-user, or return (leaving request.user set to
77
77
# AnonymousUser by the AuthenticationMiddleware).
78
78
if request .user .is_authenticated ():
79
- try :
80
- stored_backend = load_backend (request .session .get (
81
- auth .BACKEND_SESSION_KEY , '' ))
82
- if isinstance (stored_backend , RemoteUserBackend ):
83
- auth .logout (request )
84
- except ImportError :
85
- # backend failed to load
86
- auth .logout (request )
79
+ self ._remove_invalid_user (request )
87
80
return
88
81
# If the user is already authenticated and that user is the user we are
89
82
# getting passed in the headers, then the correct user is already
90
83
# persisted in the session and we don't need to continue.
91
84
if request .user .is_authenticated ():
92
85
if request .user .get_username () == self .clean_username (username , request ):
93
86
return
87
+ else :
88
+ # An authenticated user is associated with the request, but
89
+ # it does not match the authorized user in the header.
90
+ self ._remove_invalid_user (request )
91
+
94
92
# We are seeing this user for the first time in this session, attempt
95
93
# to authenticate the user.
96
94
user = auth .authenticate (remote_user = username )
@@ -112,3 +110,17 @@ def clean_username(self, username, request):
112
110
except AttributeError : # Backend has no clean_username method.
113
111
pass
114
112
return username
113
+
114
+ def _remove_invalid_user (self , request ):
115
+ """
116
+ Removes the current authenticated user in the request which is invalid
117
+ but only if the user is authenticated via the RemoteUserBackend.
118
+ """
119
+ try :
120
+ stored_backend = load_backend (request .session .get (auth .BACKEND_SESSION_KEY , '' ))
121
+ except ImportError :
122
+ # backend failed to load
123
+ auth .logout (request )
124
+ else :
125
+ if isinstance (stored_backend , RemoteUserBackend ):
126
+ auth .logout (request )
0 commit comments