| 1 |
import warnings |
| 2 |
from functools import partial |
| 3 |
from urllib.parse import urlsplit |
| 4 |
|
| 5 |
from asgiref.sync import iscoroutinefunction, markcoroutinefunction, sync_to_async |
| 6 |
|
| 7 |
from django.conf import settings |
| 8 |
from django.contrib import auth |
| 9 |
from django.contrib.auth import REDIRECT_FIELD_NAME, load_backend |
| 10 |
from django.contrib.auth.backends import RemoteUserBackend |
| 11 |
from django.contrib.auth.views import redirect_to_login |
| 12 |
from django.core.exceptions import ImproperlyConfigured |
| 13 |
from django.shortcuts import resolve_url |
| 14 |
from django.utils.deprecation import MiddlewareMixin, RemovedInDjango61Warning |
| 15 |
from django.utils.functional import SimpleLazyObject |
| 16 |
|
| 17 |
|
| 18 |
def get_user(request): |
| 19 |
if not hasattr(request, "_cached_user"): |
| 20 |
request._cached_user = auth.get_user(request) |
| 21 |
return request._cached_user |
| 22 |
|
| 23 |
|
| 24 |
async def auser(request): |
| 25 |
if not hasattr(request, "_acached_user"): |
| 26 |
request._acached_user = await auth.aget_user(request) |
| 27 |
return request._acached_user |
| 28 |
|
| 29 |
|
| 30 |
class AuthenticationMiddleware(MiddlewareMixin): |
| 31 |
def process_request(self, request): |
| 32 |
if not hasattr(request, "session"): |
| 33 |
raise ImproperlyConfigured( |
| 34 |
"The Django authentication middleware requires session " |
| 35 |
"middleware to be installed. Edit your MIDDLEWARE setting to " |
| 36 |
"insert " |
| 37 |
"'django.contrib.sessions.middleware.SessionMiddleware' before " |
| 38 |
"'django.contrib.auth.middleware.AuthenticationMiddleware'." |
| 39 |
) |
| 40 |
request.user = SimpleLazyObject(lambda: get_user(request)) |
| 41 |
request.auser = partial(auser, request) |
| 42 |
|
| 43 |
|
| 44 |
class LoginRequiredMiddleware(MiddlewareMixin): |
| 45 |
""" |
| 46 |
Middleware that redirects all unauthenticated requests to a login page. |
| 47 |
|
| 48 |
Views using the login_not_required decorator will not be redirected. |
| 49 |
""" |
| 50 |
|
| 51 |
redirect_field_name = REDIRECT_FIELD_NAME |
| 52 |
|
| 53 |
def process_view(self, request, view_func, view_args, view_kwargs): |
| 54 |
if request.user.is_authenticated: |
| 55 |
return None |
| 56 |
|
| 57 |
if not getattr(view_func, "login_required", True): |
| 58 |
return None |
| 59 |
|
| 60 |
return self.handle_no_permission(request, view_func) |
| 61 |
|
| 62 |
def get_login_url(self, view_func): |
| 63 |
login_url = getattr(view_func, "login_url", None) or settings.LOGIN_URL |
| 64 |
if not login_url: |
| 65 |
raise ImproperlyConfigured( |
| 66 |
"No login URL to redirect to. Define settings.LOGIN_URL or " |
| 67 |
"provide a login_url via the 'django.contrib.auth.decorators." |
| 68 |
"login_required' decorator." |
| 69 |
) |
| 70 |
return str(login_url) |
| 71 |
|
| 72 |
def get_redirect_field_name(self, view_func): |
| 73 |
return getattr(view_func, "redirect_field_name", self.redirect_field_name) |
| 74 |
|
| 75 |
def handle_no_permission(self, request, view_func): |
| 76 |
path = request.build_absolute_uri() |
| 77 |
resolved_login_url = resolve_url(self.get_login_url(view_func)) |
| 78 |
# If the login url is the same scheme and net location then use the |
| 79 |
# path as the "next" url. |
| 80 |
login_scheme, login_netloc = urlsplit(resolved_login_url)[:2] |
| 81 |
current_scheme, current_netloc = urlsplit(path)[:2] |
| 82 |
if (not login_scheme or login_scheme == current_scheme) and ( |
| 83 |
not login_netloc or login_netloc == current_netloc |
| 84 |
): |
| 85 |
path = request.get_full_path() |
| 86 |
|
| 87 |
return redirect_to_login( |
| 88 |
path, |
| 89 |
resolved_login_url, |
| 90 |
self.get_redirect_field_name(view_func), |
| 91 |
) |
| 92 |
|
| 93 |
|
| 94 |
class RemoteUserMiddleware: |
| 95 |
""" |
| 96 |
Middleware for utilizing web-server-provided authentication. |
| 97 |
|
| 98 |
If request.user is not authenticated, then this middleware attempts to |
| 99 |
authenticate the username from the ``REMOTE_USER`` key in ``request.META``, |
| 100 |
an environment variable commonly set by the webserver. |
| 101 |
|
| 102 |
If authentication is successful, the user is automatically logged in to |
| 103 |
persist the user in the session. |
| 104 |
|
| 105 |
The ``request.META`` key is configurable and defaults to ``REMOTE_USER``. |
| 106 |
Subclass this class and change the ``header`` attribute if you need to |
| 107 |
use a different key from ``request.META``, for example a HTTP request |
| 108 |
header. |
| 109 |
""" |
| 110 |
|
| 111 |
sync_capable = True |
| 112 |
async_capable = True |
| 113 |
|
| 114 |
def __init__(self, get_response): |
| 115 |
if get_response is None: |
| 116 |
raise ValueError("get_response must be provided.") |
| 117 |
self.get_response = get_response |
| 118 |
self.is_async = iscoroutinefunction(get_response) |
| 119 |
if self.is_async: |
| 120 |
markcoroutinefunction(self) |
| 121 |
super().__init__() |
| 122 |
|
| 123 |
# Name of request.META key to grab username from. Note that for |
| 124 |
# request headers, normalization to all uppercase and the addition |
| 125 |
# of a "HTTP_" prefix apply. |
| 126 |
header = "REMOTE_USER" |
| 127 |
force_logout_if_no_header = True |
| 128 |
|
| 129 |
def __call__(self, request): |
| 130 |
if self.is_async: |
| 131 |
return self.__acall__(request) |
| 132 |
self.process_request(request) |
| 133 |
return self.get_response(request) |
| 134 |
|
| 135 |
def process_request(self, request): |
| 136 |
# AuthenticationMiddleware is required so that request.user exists. |
| 137 |
if not hasattr(request, "user"): |
| 138 |
raise ImproperlyConfigured( |
| 139 |
"The Django remote user auth middleware requires the" |
| 140 |
" authentication middleware to be installed. Edit your" |
| 141 |
" MIDDLEWARE setting to insert" |
| 142 |
" 'django.contrib.auth.middleware.AuthenticationMiddleware'" |
| 143 |
" before the RemoteUserMiddleware class." |
| 144 |
) |
| 145 |
try: |
| 146 |
username = request.META[self.header] |
| 147 |
except KeyError: |
| 148 |
# If specified header doesn't exist then remove any existing |
| 149 |
# authenticated remote-user, or return (leaving request.user set to |
| 150 |
# AnonymousUser by the AuthenticationMiddleware). |
| 151 |
if self.force_logout_if_no_header and request.user.is_authenticated: |
| 152 |
self._remove_invalid_user(request) |
| 153 |
return |
| 154 |
# If the user is already authenticated and that user is the user we are |
| 155 |
# getting passed in the headers, then the correct user is already |
| 156 |
# persisted in the session and we don't need to continue. |
| 157 |
if request.user.is_authenticated: |
| 158 |
if request.user.get_username() == self.clean_username(username, request): |
| 159 |
return |
| 160 |
else: |
| 161 |
# An authenticated user is associated with the request, but |
| 162 |
# it does not match the authorized user in the header. |
| 163 |
self._remove_invalid_user(request) |
| 164 |
|
| 165 |
# We are seeing this user for the first time in this session, attempt |
| 166 |
# to authenticate the user. |
| 167 |
user = auth.authenticate(request, remote_user=username) |
| 168 |
if user: |
| 169 |
# User is valid. Set request.user and persist user in the session |
| 170 |
# by logging the user in. |
| 171 |
request.user = user |
| 172 |
auth.login(request, user) |
| 173 |
|
| 174 |
async def __acall__(self, request): |
| 175 |
# RemovedInDjango61Warning. |
| 176 |
if ( |
| 177 |
self.__class__.process_request is not RemoteUserMiddleware.process_request |
| 178 |
and self.__class__.aprocess_request is RemoteUserMiddleware.aprocess_request |
| 179 |
): |
| 180 |
warnings.warn( |
| 181 |
"Support for subclasses of RemoteUserMiddleware that override " |
| 182 |
"process_request() without overriding aprocess_request() is " |
| 183 |
"deprecated.", |
| 184 |
category=RemovedInDjango61Warning, |
| 185 |
stacklevel=2, |
| 186 |
) |
| 187 |
await sync_to_async(self.process_request, thread_sensitive=True)(request) |
| 188 |
return await self.get_response(request) |
| 189 |
await self.aprocess_request(request) |
| 190 |
return await self.get_response(request) |
| 191 |
|
| 192 |
async def aprocess_request(self, request): |
| 193 |
# AuthenticationMiddleware is required so that request.user exists. |
| 194 |
if not hasattr(request, "user"): |
| 195 |
raise ImproperlyConfigured( |
| 196 |
"The Django remote user auth middleware requires the" |
| 197 |
" authentication middleware to be installed. Edit your" |
| 198 |
" MIDDLEWARE setting to insert" |
| 199 |
" 'django.contrib.auth.middleware.AuthenticationMiddleware'" |
| 200 |
" before the RemoteUserMiddleware class." |
| 201 |
) |
| 202 |
try: |
| 203 |
username = request.META["HTTP_" + self.header] |
| 204 |
except KeyError: |
| 205 |
# If specified header doesn't exist then remove any existing |
| 206 |
# authenticated remote-user, or return (leaving request.user set to |
| 207 |
# AnonymousUser by the AuthenticationMiddleware). |
| 208 |
if self.force_logout_if_no_header: |
| 209 |
user = await request.auser() |
| 210 |
if user.is_authenticated: |
| 211 |
await self._aremove_invalid_user(request) |
| 212 |
return |
| 213 |
user = await request.auser() |
| 214 |
# If the user is already authenticated and that user is the user we are |
| 215 |
# getting passed in the headers, then the correct user is already |
| 216 |
# persisted in the session and we don't need to continue. |
| 217 |
if user.is_authenticated: |
| 218 |
if user.get_username() == self.clean_username(username, request): |
| 219 |
return |
| 220 |
else: |
| 221 |
# An authenticated user is associated with the request, but |
| 222 |
# it does not match the authorized user in the header. |
| 223 |
await self._aremove_invalid_user(request) |
| 224 |
|
| 225 |
# We are seeing this user for the first time in this session, attempt |
| 226 |
# to authenticate the user. |
| 227 |
user = await auth.aauthenticate(request, remote_user=username) |
| 228 |
if user: |
| 229 |
# User is valid. Set request.user and persist user in the session |
| 230 |
# by logging the user in. |
| 231 |
request.user = user |
| 232 |
await auth.alogin(request, user) |
| 233 |
|
| 234 |
def clean_username(self, username, request): |
| 235 |
""" |
| 236 |
Allow the backend to clean the username, if the backend defines a |
| 237 |
clean_username method. |
| 238 |
""" |
| 239 |
backend_str = request.session[auth.BACKEND_SESSION_KEY] |
| 240 |
backend = auth.load_backend(backend_str) |
| 241 |
try: |
| 242 |
username = backend.clean_username(username) |
| 243 |
except AttributeError: # Backend has no clean_username method. |
| 244 |
pass |
| 245 |
return username |
| 246 |
|
| 247 |
def _remove_invalid_user(self, request): |
| 248 |
""" |
| 249 |
Remove the current authenticated user in the request which is invalid |
| 250 |
but only if the user is authenticated via the RemoteUserBackend. |
| 251 |
""" |
| 252 |
try: |
| 253 |
stored_backend = load_backend( |
| 254 |
request.session.get(auth.BACKEND_SESSION_KEY, "") |
| 255 |
) |
| 256 |
except ImportError: |
| 257 |
# backend failed to load |
| 258 |
auth.logout(request) |
| 259 |
else: |
| 260 |
if isinstance(stored_backend, RemoteUserBackend): |
| 261 |
auth.logout(request) |
| 262 |
|
| 263 |
async def _aremove_invalid_user(self, request): |
| 264 |
""" |
| 265 |
Remove the current authenticated user in the request which is invalid |
| 266 |
but only if the user is authenticated via the RemoteUserBackend. |
| 267 |
""" |
| 268 |
try: |
| 269 |
stored_backend = load_backend( |
| 270 |
await request.session.aget(auth.BACKEND_SESSION_KEY, "") |
| 271 |
) |
| 272 |
except ImportError: |
| 273 |
# Backend failed to load. |
| 274 |
await auth.alogout(request) |
| 275 |
else: |
| 276 |
if isinstance(stored_backend, RemoteUserBackend): |
| 277 |
await auth.alogout(request) |
| 278 |
|
| 279 |
|
| 280 |
class PersistentRemoteUserMiddleware(RemoteUserMiddleware): |
| 281 |
""" |
| 282 |
Middleware for web-server provided authentication on logon pages. |
| 283 |
|
| 284 |
Like RemoteUserMiddleware but keeps the user authenticated even if |
| 285 |
the ``request.META`` key is not found in the request. Useful for |
| 286 |
setups when the external authentication is only expected to happen |
| 287 |
on some "logon" URL and the rest of the application wants to use |
| 288 |
Django's authentication mechanism. |
| 289 |
""" |
| 290 |
|
| 291 |
force_logout_if_no_header = False |