Django - Read the current's user authentication backend class

4.2k views Asked by At

I am using a custom authentication backend with Django, to automatically create and login users from a legacy system. My Backend class is this:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from sfi.models import Employee
import base64, hashlib

class SFIUserBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        if not username or not password:
            return

        digest = base64.standard_b64encode(hashlib.md5(password).digest())
        user = None
        try:
            employee = Employee.objects.get(login=username, passwd=digest)
            user, created = User.objects.get_or_create(username=username)
            if created:
                # setting attributes
                user.first_name = employee.names[:30]
                user.last_name = employee.surnames[:30]
                user.is_staff = True
                user.save()
        except Employee.DoesNotExist:
            pass

        return user

So far, it works fine. However, I need to read the backend class of the currently logged user in a template.

Using request.user.backend says that user does not have the attribute backend... and I cannot read it from the session (using request.session._auth_user_backend) because the Django template system complains that "Variables and attributes may not begin with underscores".

I am using django.contrib.auth.views.login to allow users login. What am I missing?

3

There are 3 answers

0
lprsd On

You should read it in the the view and send an appropriate human form of that class name as the message.

1
Chris W. On

The backend attribute is added to the user object when the user authenticates using the django.contrib.auth.authenticate(username='foo',password='bar') function.

This function in turn calls all of the AUTHENTICATION_BACKENDS you have specified in your settings.py file, until it is able to authenticate successfully using one of them.

If your users are "logged in" but don't have a backend attribute that probably means you're not properly authenticating them. Maybe you're calling your SFIUserBackend.authenticate function directly, when you should be calling the django.contrib.auth.authenticate function?

Check out these custom authentication docs.

0
OrangeDog On

While authenticate() adds the user.backend attribute and login() saves it in the session, for some reason get_user() does not add it back to the user. I have submitted a patch.

Therefore, in order to access it in another request, you need request.session[django.contrib.auth.BACKEND_SESSION_KEY].

You can also write a custom tag or add it to your context (under whatever name you want) for ease of use.