我有一个名为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