Django 自定义身份验证未对自定义用户进行身份验证

问题描述 投票:0回答:1

所以我尝试使用 Django 构建一个网站,其中有两个独立的用户群,一个是

user
,另一个是
agent
。现在我从
User
导入
from django.contrib.auth.models import User
并为
Agent
建立了一个单独的模型。我想要的是
users
agents
有不同的登录网址。
agent
可以是
agent
,而无需注册为
user
。现在我已经尝试了这段代码,它的作用是在尝试使用
agent
凭据登录后,它登录并返回正确的 html 页面,但甚至不验证这些凭据是否正确。就像即使在提供了错误的凭据后,
agent_login
仍然是
logging me in
一样。现在我想知道问题是什么以及如何解决它以便它正常工作。

我的模型.py:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phonenumber = models.IntegerField()

    def __str__(self):
        return f'{self.user.username} Profile'

class Agent(models.Model):
    name = models.CharField(max_length=100)
    password = models.CharField(max_length=100)
    image = models.ImageField(upload_to = 'Images/')
    bio = models.TextField()
    instagram = models.URLField(max_length=100)
    twitter = models.URLField(max_length=100)
    facebook = models.URLField(max_length=100)
    linkedin = models.URLField(max_length=100)
    is_featured = models.BooleanField(default = False)
    slug = models.SlugField(default='')

    def __str__(self):
        return f'{self.name} Agent Profile'

我的forms.py:

class AgentSignInForm(AuthenticationForm):
    username = forms.CharField(max_length=100)
    password = forms.PasswordInput()
    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        return cleaned_data

我的观点.py:

def agent_login(request):
    if request.method == 'POST':
        form = AgentSignInForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']
        agent = AgentBackend.authenticate(request)
        return render(request, 'users/agent_dashboard.html', {'agent': agent})
    else:
        form = AgentSignInForm()
    return render(request, 'users/agent_login.html', {'form': form,})

    
class AgentDashboard(DetailView):
    model = Agent
    template_name = 'users/agent_dashboard.html'
    slug_field = 'slug'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        agent = self.get_object()
        properties = Property.objects.filter(agent=agent)
        context['properties'] = properties
        return context

我的设置.py:

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "users.backends.AgentBackend",
]

我的后端.py:

from .models import Agent
from contextlib import suppress
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password

class AgentBackend(BaseBackend):
    def authenticate(request, username=None, password=None, **kwargs):
        # Skip authentication attempts without credentials
        if username is None or password is None:
            return

        # Get agent by name, check the password hash and return it if everything is ok
        with suppress(Agent.DoesNotExist):  
            agent = Agent.objects.get(name=username)
            if check_password(password, agent.password):
                return agent
        return None

    def get_user(self, slug):
        # Fetch and return agent if it exists
        with suppress(Agent.DoesNotExist):
            return Agent.objects.get(slug=slug)
        return None
django django-models django-views django-forms django-authentication
1个回答
0
投票

您只需验证(检查 pass 和 u_name 是否正确)他们,

        username = request.POST['username']
        password = request.POST['password']
        agent = AgentBackend.authenticate(request)

。 您需要登录它们(将它们保存为数据库中的登录用户)。

user=authenticate(request=request,username=username,password=password)
if user is not None:
    login(request,user,backend='AgentBackend')
© www.soinside.com 2019 - 2024. All rights reserved.