middleware.py 5.2 KB

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