Django - Why do I need to specify the user.backend when logging in with a custom backend?

Viewed 299

The code works as is, I'm just hoping somebody can provide an explanation here.

I set up a custom backend for my app. Code below:

from django.contrib.auth.backends import BaseBackend
from django.contrib.auth import get_user_model


class AuthenticationBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None, email=None):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=email)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

And here is the view:

def login_view(request):

    form = LoginForm(request.POST or None)
    if request.POST and form.is_valid():
        user = form.login(request)
        if user:
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, user)
            print(request.user)
            return redirect('tasks')

    context = {
        'form': form
    }

    return render(request, 'users/login/index.html', context)

Along with the form (Note much of the login functionality was abstracted to the form)

class LoginForm(forms.Form):
    email = forms.CharField(max_length=255, required=True, widget=forms.TextInput(attrs={'class': 'form_input'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form_input'}), required=True)

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')
        user = authenticate(email=email, password=password)
        if not user or not user.is_active:
            raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
        return self.cleaned_data

    def login(self, request):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')
        user = authenticate(email=email, password=password)
        return user

In the login_view code, I had an issue. Before adding the "user.backend = ..." line, the system would login the user successfully, however upon redirecting to the 'tasks' view, the user would go back to Anonyomous.

After specifying the backend for the user prior to login, the code works fine.

Why do I need to specify the backend for the user prior to login? Is this because I'm using a custom backend? Did I mess up on the code somewhere?

Thank you in advanced!

1 Answers

Actually when you create more than one backend in the Django and register that backend in the Django settings Django is not able to identify for which backend this login functionality is so for that we have to specify the backend at login time or the other way is you can delete the default Django login backend but, if you delete that after that Django admin login might not work.

Related