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.

auth_backends.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from django.contrib.auth.backends import ModelBackend
  2. from django.core.mail import mail_admins
  3. from django.core.exceptions import ImproperlyConfigured
  4. from oscar.core.compat import get_user_model
  5. User = get_user_model()
  6. if hasattr(User, 'REQUIRED_FIELDS'):
  7. if not (User.USERNAME_FIELD == 'email' or 'email' in User.REQUIRED_FIELDS):
  8. raise ImproperlyConfigured(
  9. "Emailbackend: Your User model must have an email"
  10. " field with blank=False")
  11. class Emailbackend(ModelBackend):
  12. """
  13. Custom auth backend that users an email address
  14. For this to work, the User model must have an 'email' field
  15. """
  16. def authenticate(self, email=None, password=None, *args, **kwargs):
  17. if email is None:
  18. if not 'username' in kwargs or kwargs['username'] is None:
  19. return None
  20. email = kwargs['username']
  21. # Check if we're dealing with an email address
  22. if '@' not in email:
  23. return None
  24. # We lowercase the host part as this is what Django does when saving a
  25. # user
  26. local, host = email.split('@')
  27. clean_email = local + '@' + host.lower()
  28. # Since Django doesn't enforce emails to be unique, we look for all
  29. # matching users and try to authenticate them all. If we get more than
  30. # one success, then we mail admins as this is a problem.
  31. authenticated_users = []
  32. for user in User.objects.filter(email=clean_email):
  33. if user.check_password(password):
  34. authenticated_users.append(user)
  35. if len(authenticated_users) == 1:
  36. # Happy path
  37. return authenticated_users[0]
  38. elif len(authenticated_users) > 1:
  39. # This is the problem scenario where we have multiple users with
  40. # the same email address AND password. We can't safely authentiate
  41. # either. This situation requires intervention by an admin and so
  42. # we mail them to let them know!
  43. mail_admins(
  44. "There are multiple users with email address: %s" % clean_email,
  45. ("There are %s users with email %s and the same password "
  46. "which means none of them are able to authenticate") % (len(authenticated_users),
  47. clean_email))
  48. return None