backends.py 1000 B

1234567891011121314151617181920212223242526
  1. from django.contrib.auth.backends import ModelBackend, UserModel
  2. from django.contrib.auth.models import User
  3. from django.core.exceptions import MultipleObjectsReturned
  4. from django.db.models import Q
  5. class EmailBackend(ModelBackend):
  6. def authenticate(self, request, username=None, password=None, **kwargs):
  7. try:
  8. user = UserModel.objects.get(
  9. Q(username__iexact=username) | Q(email__iexact=username))
  10. except UserModel.DoesNotExist:
  11. UserModel().set_password(password)
  12. except MultipleObjectsReturned:
  13. return User.objects.filter(email=username).order_by('id').first()
  14. else:
  15. if user.check_password(password) and self.user_can_authenticate(user):
  16. return user
  17. def get_user(self, user_id):
  18. try:
  19. user = UserModel.objects.get(pk=user_id)
  20. except UserModel.DoesNotExist:
  21. return None
  22. return user if self.user_can_authenticate(user) else None