middleware.py 5.5 KB

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