How to authenticate user based on email address django

0 votes
30 views
asked Apr 4 by Eva

I have a django application, i want to authenticate user based on email without overwriting User model, the only idea i have in my mind is to check email and password and do autheticate on user, but this will not be a generic solution. I also want the same for admin too.

1 Answer

0 votes
answered Apr 4 by anonymous

you can create custom authetication backend and point that backend using you django settings.

settings.py

AUTHENTICATION_BACKENDS = [
    'project.backends.UserModelEmailBackend',  
    'django.contrib.auth.backends.ModelBackend', 
]

UserModelEmailBackend.py

from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class UserModelEmailBackend(ModelBackend):

    def authenticate(self, username="", password="", **kwargs):
        try:
            user = get_user_model().objects.get(email__iexact=username)
            if check_password(password, user.password):
                return user
            else:
                return None
        except get_user_model().DoesNotExist:
            return None
Welcome , qPocho is an online community for programmers share there knowledge.
...