使用电子邮件和密码验证用户

使用电子邮件和密码验证用户

本文介绍了使用电子邮件和密码验证用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,只允许用户通过username登录。我决定只允许用户通过电子邮件而不是用户名登录。

I have a form that only allow users to login via username . I decided to only allow user to login via email instead of username.

首先,这不是与通过电子邮件登录有关的任何问题的重复,因为在我的情况下,我在用户继续进行视图中的最终登录之前,先在 forms.py 中验证并验证用户,这样我就有机会提出错误的登录密码等错误。

First, this is not a duplication of any question relating to logging via email because in my scenario, I validate and authenticate the user in forms.py before he proceed to the final login in views so it give me the chance to raise an error for incorrect login passwords etc.

我面临的问题是,我修改了 forms.py 以在电子邮件不存在的情况下引发错误。可以,但是不允许用户通过他的电子邮件登录。

The issue i'm facing is I modified my forms.py to raise an error if the email doesn't exist which works but It wouldn't let the user login via his email.

 def LoginRequest(request):
     form = LoginForm(request.POST or None)
     if request.POST and form.is_valid():
         user = form.login(request)
         if user:
             login(request, user)
             return HttpResponseRedirect(reverse('Hello'))

     return render(request, 'login.html',{'form': form})

这是我的原著仅允许用户通过用户名登录的inal代码

This is my original code which only allow users to login via username

 class LoginForm(forms.Form):
     username = forms.CharField()
     password = forms.CharField(
        widget=forms.PasswordInput(render_value=False)
        )

     def clean(self):
         username = self.cleaned_data.get('username')
         password = self.cleaned_data.get('password')
         user = authenticate(username=username, password=password)
         if not user or not user.is_active:
             raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
         return self.cleaned_data

     def login(self, request):
         username = self.cleaned_data.get('username')
         password = self.cleaned_data.get('password')
         user = authenticate(username=username, password=password)
         return user

这是我修改后的代码,只允许用户通过电子邮件登录。我想了很多方法,但这是我想到的最好的主意。有点令人困惑。
问题是,它不允许用户登录。我不明白为什么。

This is my modified code which only allow users to login via email. I thought a lot about how I would do it but this is the best idea I came up with. Sorry it's a bit confusing.The problem is, it wouldn't let the user login. I don't understand why.

 class LoginForm(forms.Form):
     username = forms.CharField()
     password = forms.CharField(
            widget=forms.PasswordInput(render_value=False)
        )

     def clean(self):
         user = self.cleaned_data.get('username')
         password = self.cleaned_data.get('password')

         if User.objects.filter(email=user).exists():
             password = self.cleaned_data.get('password')
             user = authenticate(username=user.username, password=password)
             if not user or not user.is_active:
                 raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
             return self.cleaned_data

     def login(self, request):
         username = self.cleaned_data.get('username')
         password = self.cleaned_data.get('password')
         user = authenticate(username=username, password=password)
         return user

有人可以帮我吗?

推荐答案

dougis 指出您正在尝试使用电子邮件对用户进行身份验证,但是 authenticate 函数根据用户名和密码对用户进行身份验证。通过电子邮件(完整的工作表)对用户进行身份验证:

As dougis pointed out you are trying to authenticate the user using email, But authenticate function authenticates user based on username and password. So here is the trick to authenticate the user using email (complete working form):

from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth import authenticate

class LoginForm(forms.Form):
    email = forms.CharField()
    password = forms.CharField(
        widget=forms.PasswordInput(render_value=False)
        )

    def clean(self):
        user = self.authenticate_via_email()
        if not user:
            raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
        else:
            self.user = user
        return self.cleaned_data

    def authenticate_user(self):
        return authenticate(
            username=self.user.username,
            password=self.cleaned_data['password'])

    def authenticate_via_email(self):
        """
            Authenticate user using email.
            Returns user object if authenticated else None
        """
        email = self.cleaned_data['email']
        if email:
            try:
                user = User.objects.get(email__iexact=email)
                if user.check_password(self.cleaned_data['password']):
                    return user
            except ObjectDoesNotExist:
                pass
        return None

views.py

def LoginRequest(request):
    form = LoginForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        user = form.authenticate_user()
        login(request, user)
        return HttpResponseRedirect(reverse('Hello'))

    return render(request, 'login.html',{'form': form})

这篇关于使用电子邮件和密码验证用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:05