Browse Source

ajout backend d’auth. par email et n° d’adhérent

Élie Bouttier 8 years ago
parent
commit
8ba9b2be99
3 changed files with 43 additions and 0 deletions
  1. 14 0
      accounts/backends.py
  2. 23 0
      adhesions/backends.py
  3. 6 0
      djadhere/settings.py

+ 14 - 0
accounts/backends.py

@@ -0,0 +1,14 @@
+from django.contrib.auth import get_user_model
+from django.contrib.auth.backends import ModelBackend
+
+
+class EmailBackend(ModelBackend):
+    def authenticate(self, username, password=None, **kwargs):
+        UserModel = get_user_model()
+        try:
+            user = UserModel._default_manager.get(email__iexact=username)
+        except UserModel.DoesNotExist:
+            UserModel().set_password(password) # https://code.djangoproject.com/ticket/20760
+        else:
+            if user.check_password(password) and self.user_can_authenticate(user):
+                return user

+ 23 - 0
adhesions/backends.py

@@ -0,0 +1,23 @@
+from django.contrib.auth.models import User
+from django.contrib.contenttypes.models import ContentType
+from django.contrib.auth.backends import ModelBackend
+
+from .models import Adherent
+
+
+class AdherentBackend(ModelBackend):
+    def authenticate(self, username, password=None, **kwargs):
+        if str(username).lower().startswith("adt"):
+            username = str(username)[3:]
+        try:
+            adherent_id = int(username)
+        except ValueError:
+            return None
+        user_type = ContentType.objects.get_for_model(User)
+        try:
+            user = Adherent.objects.get(adherent_type=user_type, id=adherent_id).adherent
+        except Adherent.DoesNotExist:
+            UserModel().set_password(password) # https://code.djangoproject.com/ticket/20760
+        else:
+            if user.check_password(password) and self.user_can_authenticate(user):
+                return user

+ 6 - 0
djadhere/settings.py

@@ -107,6 +107,12 @@ AUTH_PASSWORD_VALIDATORS = [
     },
 ]
 
+AUTHENTICATION_BACKENDS = [
+    'django.contrib.auth.backends.ModelBackend',
+    'accounts.backends.EmailBackend',
+    'adhesions.backends.AdherentBackend',
+]
+
 
 # Internationalization
 # https://docs.djangoproject.com/en/1.10/topics/i18n/