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.

54 lines
1.8 KiB

  1. from django.contrib.auth.models import User
  2. from hc.accounts.models import Profile
  3. from django.contrib.auth.backends import RemoteUserBackend
  4. from hc.accounts import views
  5. from django.conf import settings
  6. class BasicBackend(object):
  7. def get_user(self, user_id):
  8. try:
  9. q = User.objects.select_related("profile")
  10. return q.get(pk=user_id)
  11. except User.DoesNotExist:
  12. return None
  13. # Authenticate against the token in user's profile.
  14. class ProfileBackend(BasicBackend):
  15. def authenticate(self, request=None, username=None, token=None):
  16. try:
  17. profiles = Profile.objects.select_related("user")
  18. profile = profiles.get(user__username=username)
  19. except Profile.DoesNotExist:
  20. return None
  21. if not profile.check_token(token, "login"):
  22. return None
  23. return profile.user
  24. class EmailBackend(BasicBackend):
  25. def authenticate(self, request=None, username=None, password=None):
  26. try:
  27. user = User.objects.get(email=username)
  28. except User.DoesNotExist:
  29. return None
  30. if user.check_password(password):
  31. return user
  32. class CustomHeaderBackend(RemoteUserBackend):
  33. def clean_username(self, username):
  34. if settings.REMOTE_USER_HEADER_TYPE == "ID": return username
  35. # "EMAIL" and "ID" are the only two values that should reach here
  36. if settings.REMOTE_USER_HEADER_TYPE != "EMAIL":
  37. raise Exception(f"Unexpected value for REMOTE_USER_HEADER_TYPE ({settings.REMOTE_USER_HEADER_TYPE})!")
  38. #else, it's the email address
  39. try:
  40. return User.objects.get(email=username).username
  41. except User.DoesNotExist:
  42. return views._make_user(username).username