0

I am trying to make a custom authentication for my django project.I am using a custom user model by subclassing AbstractUser. Now after creating a superuser account and trying to login from admin page, i am getting the error Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive..I've double checked that my username and password are right.

After doing some research, found out that something is wrong with the custom authentication backend i am making.

from support.models import CustomUser

class UsernameIdModelBackend(object):
    def authenticate(self,username,password,uid):

        if username:
            try:
                user = CustomUser.objects.get(username=username)

                if user.check_password(password):
                    return user
            except CustomUser.DoesNotExist:
                    return None
        else:
            try:
                user= CustomUser.objects.get(uid=uid)
                return user
            except CustomUser.DoesNotExist:
                return None

     def get_user(self, user_id):
        try:
            return CustomUser.objects.get(pk=user_id)
        except CustomUser.DoesNotExist:
            return None

Ive also set AUTHENTICATION_BACKENDS in settings.py. What should be changed to correct this.Can someone please point me the right way.

PS. iam new to custom authentication and is looking forward to create one with 2 types of login.

1 Answer 1

1

Rather than doing it like this, you can just add Authentication Backend for login with uid, like this(as per documentation):

class UsernameIdModelBackend(object):
    def authenticate(self, request, uid=None):
       try:
           user= CustomUser.objects.get(uid=uid)
           return user
        except CustomUser.DoesNotExist:
          return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

And add it to AUTHENTICATION_BACKENDS like this:

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'your_path_to.backend.UsernameIdModelBackend',
)
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I was not having 'django.contrib.auth.backends.ModelBackend' in AUTHENTICATION_BACKENDS. I was using only one. Thanks. So i have to make a second one only for the login using uid?
You can use multiple backends(you can use your old custom backend which has username and password only). So user can be logged in by either of the backends, and it will be handled by django

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.