python Django验证在退出应用时使用电子邮件和用户名

zu0ti5jz  于 2023-02-18  发布在  Python
关注(0)|答案(1)|浏览(102)

我正在努力为我退出的应用程序添加自定义AUTHENTICATION_BACKENDS。我已经完成了我的应用程序,但现在想登录用户名或电子邮件ID。我可以成功地登录用户名和密码。现在只想添加电子邮件ID以及。
我尝试在我的www.example.com AUTHENTICATION_BACKENDS = ( 'authentication.backends.EmailOrUsernameModelBackend', 'django.contrib.auth.backends.ModelBackend', )中添加以下代码settings.py
在\authentication\backends.py中我有

from django.conf import settings
from django.contrib.auth.models import User

class EmailOrUsernameModelBackend(object):
    def authenticate(self, username=None, password=None):
        print("Inside EmailorUsernameModelBackend")
        if '@' in username:
            print("User with Email")
            kwargs = {'email': username}
        else:
            print("User with Username")
            kwargs = {'username': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

其中我的\身份验证\视图. py

def login_view(request):
    form = LoginForm(request.POST or None)

    msg = None

    if request.method == "POST":

        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            user = authenticate(username=username, password=password)
            print("User=",user)
            if user is not None:
                login(request, user)
                return redirect("dashboard")
            else:
                msg = 'Invalid credentials'
        else:
            msg = 'Error validating the form'

    return render(request, "/login.html", {"form": form, "msg": msg})

如果从EmailOrUsernameModelBackend调用authenticate方法,我尝试打印一些语句,但没有打印,所以我猜由于某种原因,它没有调用该方法。
请帮助我调用自定义身份验证方法时遗漏的内容。

bnlyeluc

bnlyeluc1#

我认为问题是你没有从Django中子类化BaseBackend,而只是常规的python object。我通常做2个独立的后端,这使得我的代码更清晰,便于其他人阅读。

from django.contrib.auth.backends import BaseBackend

class EmailBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(email=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

class UsernameBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

相关问题