Search code examples
djangodjango-authentication

django custom authentication backend is not being called


I am using Django 3.1, and trying to figure out why my custom Authentication backend isn't being called.

In my settings.py file I have:

AUTHENTICATION_BACKENDS = (
    'sizzy.backends.EmailBackend',
)

And in my sizzy.backends.py file I have:

from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.backends import ModelBackend
from .models import User

class EmailBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            print("Trying the email backend!")
            user = User.objects.get(email=username)
            print("Got the user")
            if user.check_password(password): # check valid password
                return user
            print("password didn't work")
        except ObjectDoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            print("Getting the user of the Email Bkacned")
            return User.objects.get(pk=user_id)
        except ObjectDoesNotExist:
            return None

I then open up the manage.py shell and input:

from django.contrib.auth import authenticate
email = "billypop@a.pop"
password = "password"
user = authenticate(username=email, password=password)

And it outputs:

Login failed. Credentials:
{'username': 'billypop@a.pop', 'password': '********************'}

And I don't see any print statements. "Trying to get the Email Backend!" is never printed. Am I missing something? I tried changing my settings file to point to sizzy.backends.EmailBackendqwertyui just as a sanity check, and that threw an error instead of Login failed. So the backend is being loaded somehow I think, but never called.

I've also tried changing out ModelBackend for BaseBackend, with the same results.


Solution

  • It seems the function signature of authenticate(...) method is not correct, it should be as

    class EmailBackend(ModelBackend):
        def authenticate(self, request, username=None, password=None, **kwargs):
            # do something