Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/contrib/auth/middleware.py: 42%
52 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1from django.contrib import auth
2from django.contrib.auth import load_backend
3from django.contrib.auth.backends import RemoteUserBackend
4from django.core.exceptions import ImproperlyConfigured
5from django.utils.deprecation import MiddlewareMixin
6from django.utils.functional import SimpleLazyObject
9def get_user(request):
10 if not hasattr(request, "_cached_user"): 10 ↛ 12line 10 didn't jump to line 12, because the condition on line 10 was never false
11 request._cached_user = auth.get_user(request)
12 return request._cached_user
15class AuthenticationMiddleware(MiddlewareMixin):
16 def process_request(self, request):
17 if not hasattr(request, "session"): 17 ↛ 18line 17 didn't jump to line 18, because the condition on line 17 was never true
18 raise ImproperlyConfigured(
19 "The Django authentication middleware requires session "
20 "middleware to be installed. Edit your MIDDLEWARE setting to "
21 "insert "
22 "'django.contrib.sessions.middleware.SessionMiddleware' before "
23 "'django.contrib.auth.middleware.AuthenticationMiddleware'."
24 )
25 request.user = SimpleLazyObject(lambda: get_user(request))
28class RemoteUserMiddleware(MiddlewareMixin):
29 """
30 Middleware for utilizing web-server-provided authentication.
32 If request.user is not authenticated, then this middleware attempts to
33 authenticate the username passed in the ``REMOTE_USER`` request header.
34 If authentication is successful, the user is automatically logged in to
35 persist the user in the session.
37 The header used is configurable and defaults to ``REMOTE_USER``. Subclass
38 this class and change the ``header`` attribute if you need to use a
39 different header.
40 """
42 # Name of request header to grab username from. This will be the key as
43 # used in the request.META dictionary, i.e. the normalization of headers to
44 # all uppercase and the addition of "HTTP_" prefix apply.
45 header = "REMOTE_USER"
46 force_logout_if_no_header = True
48 def process_request(self, request):
49 # AuthenticationMiddleware is required so that request.user exists.
50 if not hasattr(request, "user"):
51 raise ImproperlyConfigured(
52 "The Django remote user auth middleware requires the"
53 " authentication middleware to be installed. Edit your"
54 " MIDDLEWARE setting to insert"
55 " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
56 " before the RemoteUserMiddleware class."
57 )
58 try:
59 username = request.META[self.header]
60 except KeyError:
61 # If specified header doesn't exist then remove any existing
62 # authenticated remote-user, or return (leaving request.user set to
63 # AnonymousUser by the AuthenticationMiddleware).
64 if self.force_logout_if_no_header and request.user.is_authenticated:
65 self._remove_invalid_user(request)
66 return
67 # If the user is already authenticated and that user is the user we are
68 # getting passed in the headers, then the correct user is already
69 # persisted in the session and we don't need to continue.
70 if request.user.is_authenticated:
71 if request.user.get_username() == self.clean_username(username, request):
72 return
73 else:
74 # An authenticated user is associated with the request, but
75 # it does not match the authorized user in the header.
76 self._remove_invalid_user(request)
78 # We are seeing this user for the first time in this session, attempt
79 # to authenticate the user.
80 user = auth.authenticate(request, remote_user=username)
81 if user:
82 # User is valid. Set request.user and persist user in the session
83 # by logging the user in.
84 request.user = user
85 auth.login(request, user)
87 def clean_username(self, username, request):
88 """
89 Allow the backend to clean the username, if the backend defines a
90 clean_username method.
91 """
92 backend_str = request.session[auth.BACKEND_SESSION_KEY]
93 backend = auth.load_backend(backend_str)
94 try:
95 username = backend.clean_username(username)
96 except AttributeError: # Backend has no clean_username method.
97 pass
98 return username
100 def _remove_invalid_user(self, request):
101 """
102 Remove the current authenticated user in the request which is invalid
103 but only if the user is authenticated via the RemoteUserBackend.
104 """
105 try:
106 stored_backend = load_backend(
107 request.session.get(auth.BACKEND_SESSION_KEY, "")
108 )
109 except ImportError:
110 # backend failed to load
111 auth.logout(request)
112 else:
113 if isinstance(stored_backend, RemoteUserBackend):
114 auth.logout(request)
117class PersistentRemoteUserMiddleware(RemoteUserMiddleware):
118 """
119 Middleware for web-server provided authentication on logon pages.
121 Like RemoteUserMiddleware but keeps the user authenticated even if
122 the header (``REMOTE_USER``) is not found in the request. Useful
123 for setups when the external authentication via ``REMOTE_USER``
124 is only expected to happen on some "logon" URL and the rest of
125 the application wants to use Django's authentication mechanism.
126 """
128 force_logout_if_no_header = False