Django-阅读当前的用户身份验证后端类 [英] Django - Read the current's user authentication backend class

查看:164
本文介绍了Django-阅读当前的用户身份验证后端类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Django的自定义身份验证后端,以自动从旧版系统创建和登录用户.我的Backend班级是这样的:

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.

使用request.user.backend表示user没有后端属性...,我无法从会话中读取它(使用request.session._auth_user_backend),因为Django模板系统抱怨变量和属性可能不以下划线".

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".

我正在使用django.contrib.auth.views.login允许用户登录.我想念什么?

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

推荐答案

当用户使用django.contrib.auth.authenticate(username='foo',password='bar')函数进行身份验证时,backend属性将添加到user对象.

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

此函数依次调用您在settings.py文件中指定的所有AUTHENTICATION_BACKENDS,直到能够使用其中之一成功进行身份验证.

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.

如果您的用户已登录"但没有backend属性,则可能意味着您没有正确地对其进行身份验证.也许应该在调用django.contrib.auth.authenticate函数时直接调用SFIUserBackend.authenticate函数?

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?

查看这些自定义身份验证文档.

这篇关于Django-阅读当前的用户身份验证后端类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆