首页 > 解决方案 > Django 身份验证 login() 返回匿名用户

问题描述

我正在尝试登录到一个不是默认数据库的数据库,为此我编写了一个自定义身份验证代码,但是每当我尝试登录时,该方法都会返回一个AnonymousUser. 我不知道为什么要这样做,因为用户身份验证是使用该authenticate方法正确完成的。

任何帮助将非常感激。

我的文件

视图.py

def login_authentication(request):
    if request.method == "POST":
        form = New_Login_Form(request.POST)
        # print(request.POST)
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user_operating_company = request.POST['user_operating_company']
            user = authenticate(request, email=email,
                                password=password, db=user_operating_company)
            if user:
                login(request, user, user_operating_company)
                return redirect('test')
    else:
        form = New_Login_Form()
        return render(request, 'index.html', {'form': form})

后端.py

from django.contrib.auth.backends import ModelBackend
from .models import Account

class CustomAuthenticate(ModelBackend):
    def authenticate(self, request, email=None, password=None, db=None):
        try:
            user = Account.objects.all().using(db).get(email=email)
            if user.check_password(password):
                return user
        except:
            return None

    def get_user(self, request, email, db):
        try:
            return Account.objects.using(db).get(pk=email)
        except:
            return None

并且在

设置.py

AUTHENTICATION_BACKENDS = ('accounts.backends.CustomAuthenticate', 'django.contrib.auth.backends.ModelBackend')

编辑:

我根据@schillingt 的回答进行了更改,更新后的后端是:

from django.contrib.auth.backends import ModelBackend
from .models import Account

class CustomAuthenticate(ModelBackend):
    def authenticate(self, request, email=None, password=None, db=None):
        self.db = db
        try:
            user = Account.objects.using(db).get(email=email)
            if user.check_password(password):
                return user
        except Account.DoesNotExist:
            return None

    def get_user(self, email):
        try:
            user =  Account.objects.using(self.db).get(pk=email)
        except Account.DoesNotExist:
            return None
        return user if self.user_can_authenticate(user) else None

但现在它给了我一个错误,上面写着

'CustomAuthenticate' object has no attribute 'db'

标签: pythonpython-3.xdjangoauthenticationdjango-2.x

解决方案


我相信你的签名有误get_user。ModelBackend 是:

def get_user(self, user_id):
    try:
        user = UserModel._default_manager.get(pk=user_id)
    except UserModel.DoesNotExist:
        return None
    return user if self.user_can_authenticate(user) else None

此方法由django.contrib.auth.get_user. 您的后端是否引用了db应该使用的实例?或者是在请求中定义的?如果它是在请求中定义的,您可能必须修改该django.contrib.auth.get_user方法以向后端方法的调用提供正确的参数,get_user以便您拥有正确的db实例。

编辑:

让人觉得我错了。你不应该猴子补丁django.contrib.auth.get_user。您应该能够在后端实例上设置 db 实例authenticate,然后在get_user.


推荐阅读