Custom authentication backend. Django
While Bartek's answer is the correct one I'll just provide an example of another way to solve the problem by inheriting the ModelBackend
.
from django.contrib.auth.backends import ModelBackend
class EmailAuthBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except ObjectDoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
User().set_password(password)
The get_user
is already implemented by the ModelBackend
and you get the permission methods along with it.
For each custom backend in Django, you need to specify the get_user
function. See the documentation. The get_user
implementation can simply use the existing User table, like you are:
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
The reason this is required is for situations where you'd need to fetch the User via its primary key from a different source.