Django custom authentication back-end doesn't work
Ok, I have tried this before with Django 2.0.5, but it stopped working with Django 2.1. I researched here and found that custom authentication backend class now expects parameter request in method authenticate. So the final code for Django 2.1 is:
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwars):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
Working in Django 3.x
Custom Authentication file would look like:
from django.contrib.auth import get_user_model
User = get_user_model()
class EmailAuthBackend(object):
"""It provides the functionality to slide down to email to login,
instead of just username"""
def authenticate(self,request,username=None,password=None):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
return None
except User.DoesNotExist:
return None
def get_user(self,user_id):
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:
return None
and in the settings.py we need to put:
#Custom Authentication Backend
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'user_accounts.custom_auth_backend.EmailAuthBackend',
]