Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

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