from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.auth.backends import ModelBackend from .models import Adhesion class AdhesionBackend(ModelBackend): def authenticate(self, username=None, password=None): if not username: return None if str(username).lower().startswith("adt"): username = str(username)[3:] try: adhesion_id = int(username) except ValueError: return None user_type = ContentType.objects.get_for_model(User) try: user = Adhesion.objects.get(adherent_type=user_type, id=adhesion_id).adherent except Adhesion.DoesNotExist: User().set_password(password) # https://code.djangoproject.com/ticket/20760 else: if user.check_password(password) and self.user_can_authenticate(user): return user