我在 Django 中使用自定义身份验证后端,以从旧系统自动创建和登录用户。我的 Backend
类是这样的:
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
到目前为止,它工作正常。但是,我需要在模板中读取当前登录用户的后端类。
使用 request.user.backend
表示 user
没有属性后端...我无法从 session 中读取它(使用 request. session._auth_user_backend
) 因为 Django 模板系统提示“变量和属性不能以下划线开头”。
我正在使用 django.contrib.auth.views.login
来允许用户登录。我错过了什么?
最佳答案
当用户使用 django.contrib.auth.authenticate(username='foo',password) 进行身份验证时,
函数。backend
属性被添加到 user
对象='bar')
此函数依次调用您在 settings.py
文件中指定的所有 AUTHENTICATION_BACKENDS
,直到它能够使用其中之一成功进行身份验证。
如果您的用户“已登录”但没有 backend
属性,这可能意味着您没有正确验证他们。也许你在直接调用你的 SFIUserBackend.authenticate
函数,而你应该调用 django.contrib.auth.authenticate
函数?
查看这些 custom authentication docs .
关于python - Django - 读取当前的用户认证后端类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5025367/