You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.py 5.3KB

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