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.

42 lines
1.2 KiB

  1. from django.conf import settings
  2. from django.contrib.auth.middleware import RemoteUserMiddleware
  3. def to_django_header(header):
  4. return f"HTTP_{header.replace('-', '_').upper()}"
  5. class HeaderAuthMiddleware(RemoteUserMiddleware):
  6. header = to_django_header(settings.HEADER_AUTH_USER_NAME)
  7. def process_request(self, request):
  8. if request.user.is_authenticated:
  9. return
  10. username = request.META.get(self.header)
  11. if not username:
  12. return
  13. super().process_request(request)
  14. self.process_user_groups(request.user, request.META)
  15. @classmethod
  16. def process_user_groups(cls, user, headers):
  17. if not user.is_authenticated:
  18. return
  19. groups = cls.parse_user_groups_from_header(headers)
  20. is_superuser = settings.HEADER_AUTH_ADMIN_GROUP_NAME in groups
  21. if user.is_superuser != is_superuser:
  22. user.is_superuser = is_superuser
  23. user.save()
  24. @classmethod
  25. def parse_user_groups_from_header(cls, headers):
  26. try:
  27. groups_header = headers[to_django_header(settings.HEADER_AUTH_USER_GROUPS)]
  28. except KeyError:
  29. return []
  30. else:
  31. return groups_header.split(settings.HEADER_AUTH_GROUPS_SEPERATOR)