from django.contrib.contenttypes.models import ContentType from django.contrib.auth.backends import ModelBackend from .models import User, Adhesion class AdhesionBackend(ModelBackend): def authenticate(self, request, 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 = User.objects.get(adhesion__id=adhesion_id) except User.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