auth.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright 2013 The Distro Tracker Developers
  2. # See the COPYRIGHT file at the top-level directory of this distribution and
  3. # at http://deb.li/DTAuthors
  4. #
  5. # This file is part of Distro Tracker. It is subject to the license terms
  6. # in the LICENSE file found in the top-level directory of this
  7. # distribution and at http://deb.li/DTLicense. No part of Distro Tracker,
  8. # including this file, may be copied, modified, propagated, or distributed
  9. # except according to the terms contained in the LICENSE file.
  10. from __future__ import unicode_literals
  11. from django.contrib.auth import get_user_model
  12. User = get_user_model()
  13. class UserEmailBackend(object):
  14. def authenticate(self, username=None, password=None):
  15. """
  16. Implements the custom authentication method.
  17. Since a particular user may have multiple email accounts associated
  18. with their account and they should be able to log in using any one of
  19. them, this authentication backend first matches the given email to the
  20. :class:`django_email_accounts.models.User` instance to which the email
  21. is associated and then authenticates the credentials against that user
  22. instance.
  23. The signature of the method is adapted to take a username argument
  24. representing the email of the user. This way, it matches the default
  25. Django authentication backend method signature which allows admin users
  26. to log in to the admin console using any of their associated emails.
  27. :returns: :class:`django_email_accounts.models.User` instance if the
  28. authentication is successful, or ``None`` otherwise.
  29. """
  30. email = username
  31. # Find a user with the given email
  32. try:
  33. user = User.objects.get(emails__email=email)
  34. except User.DoesNotExist:
  35. return None
  36. # Check if valid log in details were provided
  37. if user.check_password(password):
  38. return user
  39. else:
  40. return None
  41. def get_user(self, user_id):
  42. try:
  43. return User.objects.get(pk=user_id)
  44. except User.DoesNotExist:
  45. return None