我有一个名为cAdmin的应用程序,用于公司用户管理.并让Django超级用户创建该公司管理员,该管理员也存储在User Model中.我有一个名为MyCustomAuthBackend的自定义后端,它只判断CompanyAdmin model凭据.但问题是,每当我try 使用User型号的凭据登录时,也允许使用.我发现的原因是,如果第一个后端出现故障,它会跳转到下一个后端,即ModelBackend.在这个特定的APP cAdmin中,当第一个后端无法跳转到第二个后端时如何停止.

from django.contrib.auth.backends import BaseBackend
from .models import CompanyAdmin
from django.contrib.auth.hashers import make_password,check_password

class MyCustomAuthBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = CompanyAdmin.objects.get(adminName=username)
            print(user.adminPassword,"      ",make_password(password))
            if check_password(password, user.adminPassword):
                print("worked password", user.adminPassword, password)
                #user.is_authenticated = True
                print(user,"printer duser")
                return user
            
        except CompanyAdmin.DoesNotExist:
            return None 
        return None

下面给出了观点,

from django.shortcuts import render,HttpResponse
from django.views.decorators.cache import cache_control
from User.models import TicketDetails,Tickets,Category
from cAdmin.decorators import signin_required
#from cAdmin.backends import authenticate
from django.contrib.auth import authenticate,login,logout

@cache_control(no_cache=True, must_revalidate=True, no_store=True) 
def Login(request,id=None):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print("login view password")
        user=authenticate(request,username=username,password=password)
        print(user)
        if user:
            print(user)
            login(request,user)
            context = {'LoggedUser': user}
            return render(request,'cAdmin/adminDashboard.html',context) 
        else:
            return render(request, 'cAdmin/index.html',{'flag': 1})

    request.session.flush()
    return render(request, 'cAdmin/index.html',{})

后台的顺序如下所示:

` AUTHENTICATION_BACKEND=[

 'cAdmin.backends.MyCustomAuthBackend',
 'django.contrib.auth.backends.ModelBackend',

]``

我刚刚使用了一个由chat GPT生成的中间件,但该中间件无法工作

from django.contrib.auth.backends import ModelBackend

class MyAppAuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Check the current app and set the authentication backend accordingly
        if request.path.startswith('/cAdmin/'):
            print("Auth workeeeeeeeeeeeed")
            request.backend = 'cAdmin.backends.MyCustomAuthBackend'
        elif request.path.startswith('/'):

            request.backend = 'django.contrib.auth.backends.ModelBackend'
            print("lhglhflghlfshdglhfdlh")
            

        response = self.get_response(request)
        return response

推荐答案

你可以试试这个

登录定义您的自定义身份验证后端

from .. import MyCustomAuthBackend
def Login(request,id=None):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print("login view password")
        if request.path.startswith('/cAdmin/'): 
            user=authenticate(request,username=username,password=password)
            if user:
                login(request,user,,backend="django.contrib.auth.backends.ModelBackend")
                context = {'LoggedUser': user}
                return render(request,'cAdmin/adminDashboard.html',context) 
        elif request.path.startswith('/'):
            
            email_auth = MyCustomAuthBackend()
            user=email_auth.authenticate(request,username=username,password=password)
            if user:
                login(request,user,backend="cAdmin.backends.MyCustomAuthBackend")
                return render(request, 'cAdmin/index.html',{'flag': 1})

    request.session.flush()
    return render(request, 'cAdmin/index.html',{})
    

Django相关问答推荐

使用序列化器获取Django ORM auth_user. id数据

对象Django API中的对象

DRF中没有参数的视图的警告-壮观

django-filter compose 过滤的 url

通过 OrderingFilter 过滤平均和

使用自定义的AuthBackend时,无法使用request.user.is_authenticated或@login_required修饰符

Django如何在没有ctrl点击的情况下允许多选

访问默认的 django-allauth 登录和注册页面时出现 TemplateSyntaxError

有什么方法可以自动设置 Debug True Django application

Django获取具有值的相关对象的计数并将其添加到注释中

在 Bootstrap 中使单击的选项卡处于活动状态

InvalidBasesError:无法解析 [] 的基础

TestCase 类中的 setUpClass、setUpTestData 和 setUp 有什么区别?

如何在 Django 测试框架中修改会话

如何获取 Django 模型来自的应用程序?

is_valid() vs clean() Django 表单

更新Django模型对象多个字段的有效方法

使用 lambda 作为属性的默认值时,Django 1.7.1 Makemigrations 失败

__init__() 得到了一个意外的关键字参数user

UnicodeEncodeError:ascii编解码器无法编码字符