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.

68 lines
2.0 KiB

  1. from django.contrib.auth.models import User
  2. from django.conf import settings
  3. from hc.accounts.models import Profile
  4. from hc.accounts.views import _make_user
  5. class BasicBackend(object):
  6. def get_user(self, user_id):
  7. try:
  8. q = User.objects.select_related("profile")
  9. return q.get(pk=user_id)
  10. except User.DoesNotExist:
  11. return None
  12. # Authenticate against the token in user's profile.
  13. class ProfileBackend(BasicBackend):
  14. def authenticate(self, request=None, username=None, token=None):
  15. try:
  16. profiles = Profile.objects.select_related("user")
  17. profile = profiles.get(user__username=username)
  18. except Profile.DoesNotExist:
  19. return None
  20. if not profile.check_token(token, "login"):
  21. return None
  22. return profile.user
  23. class EmailBackend(BasicBackend):
  24. def authenticate(self, request=None, username=None, password=None):
  25. try:
  26. user = User.objects.get(email=username)
  27. except User.DoesNotExist:
  28. return None
  29. if user.check_password(password):
  30. return user
  31. class CustomHeaderBackend(BasicBackend):
  32. """
  33. This backend works in conjunction with the ``CustomHeaderMiddleware``,
  34. and is used when the server is handling authentication outside of Django.
  35. """
  36. def authenticate(self, request, remote_user_email):
  37. """
  38. The email address passed as remote_user_email is considered trusted.
  39. Return the User object with the given email address. Create a new User
  40. if it does not exist.
  41. """
  42. # This backend should only be used when header-based authentication is enabled
  43. assert settings.REMOTE_USER_HEADER
  44. # remote_user_email should have a value
  45. assert remote_user_email
  46. try:
  47. user = User.objects.get(email=remote_user_email)
  48. except User.DoesNotExist:
  49. user = _make_user(remote_user_email)
  50. return user