How to authenticate user based on email address django

0 votes
asked Apr 4, 2017 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, 2017 by anonymous

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


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):
            user = get_user_model().objects.get(email__iexact=username)
            if check_password(password, user.password):
                return user
                return None
        except get_user_model().DoesNotExist:
            return None