authbackends.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. from django.contrib.auth import get_user_model
  2. from django.contrib.auth.backends import ModelBackend
  3. User = get_user_model()
  4. class MisagoBackend(ModelBackend):
  5. def authenticate(self, request, username=None, password=None, **kwargs):
  6. if kwargs.get("email"):
  7. username = kwargs["email"] # Bias to email if it was passed explictly
  8. if not username or not password:
  9. # If no username or password was given, skip rest of this auth
  10. # This may happen if we are during different auth flow (eg. OAuth/JWT)
  11. return None
  12. try:
  13. user = User.objects.get_by_username_or_email(username)
  14. except User.DoesNotExist:
  15. # Run the default password hasher once to reduce the timing
  16. # difference between an existing and a non-existing user (#20760).
  17. User().set_password(password)
  18. else:
  19. if user.check_password(password) and self.user_can_authenticate(user):
  20. return user
  21. def get_user(self, pk):
  22. try:
  23. manager = User._default_manager
  24. relations = ("rank", "online_tracker", "ban_cache")
  25. user = manager.select_related(*relations).get(pk=pk)
  26. except User.DoesNotExist:
  27. return None
  28. return user if self.user_can_authenticate(user) else None