配置为ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
的Django AllAuth中是否有任何方法可以从输入"USERNAME OR EMAIL"
发送文本并自动进行身份验证?我的意思不是前端逻辑,只是AllAuth身份验证。因此,它将获得带有字段"username_email" : "myusername", "password" : "password"
或"username_email" : "myemail@gmail.com", "password" : "password"
的JSON,并且它将自动检查是否有昵称或电子邮件为myusername
的用户并且密码为password
。在第二种情况下,它还将检查昵称或电子邮件为myemail@gmail.com
的用户是否存在,其密码为password
。如果是这样,将对用户进行身份验证。有什么想法吗?
答案 0 :(得分:0)
您需要自定义身份验证后端doc
类似这样的东西:
class MyAuthenticationBackend:
def authenticate(self, email_username=None, password=None):
if "@" in email_username:
try:
user = User.objects.get(email=email_username)
except User.DoesNotExist:
return None
else:
try:
user = User.objects.get(username=email_username)
except User.DoesNotExist:
return None
if getattr(user, 'is_active', False) and user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
然后在表单视图中:
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.shortcuts import redirect
class LoginView(FormView):
template_name = 'my-auth/login.html'
form_class = LoginForm
def form_valid(self, form):
data = form.cleaned_data
user = authenticate(email_username=data['email_username'], password=data['password'])
if user is None:
form.add_error(None, _('Wrong email/username'))
return self.form_invalid(form)
login(self.request, user)
return redirect('somewhere')