Django - Read the current's user authentication backend class

穿精又带淫゛_ 提交于 2019-12-10 17:15:59

问题


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?


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/5025367/django-read-the-currents-user-authentication-backend-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!