Django身份验证login()返回匿名用户

时间:2020-09-22 15:40:52

标签: python python-3.x django authentication django-2.x

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

任何帮助将不胜感激。

我的文件

views.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})

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

settings.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'

1 个答案:

答案 0 :(得分:0)

我相信您的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实例。

编辑:

This使得我好像错了。您无需猴子修补django.contrib.auth.get_user。您应该能够在authenticate的后端实例上设置数据库实例,然后在get_user中使用它。

相关问题