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.

63 lines
2.2 KiB

8 years ago
8 years ago
8 years ago
  1. from django.contrib import auth
  2. from django.contrib.auth.middleware import RemoteUserMiddleware
  3. from django.conf import settings
  4. from hc.accounts.models import Profile
  5. class TeamAccessMiddleware(object):
  6. def __init__(self, get_response):
  7. self.get_response = get_response
  8. def __call__(self, request):
  9. if not request.user.is_authenticated:
  10. return self.get_response(request)
  11. request.profile = Profile.objects.for_user(request.user)
  12. return self.get_response(request)
  13. class CustomHeaderMiddleware(RemoteUserMiddleware):
  14. """
  15. Middleware for utilizing Web-server-provided authentication.
  16. If request.user is not authenticated, then this middleware:
  17. - looks for an email address in request.META[settings.REMOTE_USER_HEADER]
  18. - looks up and automatically logs in the user with a matching email
  19. """
  20. def process_request(self, request):
  21. if not settings.REMOTE_USER_HEADER:
  22. return
  23. # Make sure AuthenticationMiddleware is installed
  24. assert hasattr(request, "user")
  25. email = request.META.get(settings.REMOTE_USER_HEADER)
  26. if not email:
  27. # If specified header doesn't exist or is empty then log out any
  28. # authenticated user and return
  29. if request.user.is_authenticated:
  30. auth.logout(request)
  31. return
  32. # If the user is already authenticated and that user is the user we are
  33. # getting passed in the headers, then the correct user is already
  34. # persisted in the session and we don't need to continue.
  35. if request.user.is_authenticated:
  36. if request.user.email == email:
  37. return
  38. else:
  39. # An authenticated user is associated with the request, but
  40. # it does not match the authorized user in the header.
  41. auth.logout(request)
  42. # We are seeing this user for the first time in this session, attempt
  43. # to authenticate the user.
  44. user = auth.authenticate(request, remote_user_email=email)
  45. if user:
  46. # User is valid. Set request.user and persist user in the session
  47. # by logging the user in.
  48. request.user = user
  49. auth.login(request, user)