gpt4 book ai didi

使用电子邮件作为用户名和多个站点的Django allauth

转载 作者:行者123 更新时间:2023-12-04 04:33:06 31 4
gpt4 key购买 nike

在多个站点上使用时,是否可以将Django allauth的身份验证方法设置为“email”?

我的目标是允许电子邮件地址为bob@example.com的用户在site1.com上创建一个帐户,并在site2.com上创建一个单独的帐户。

为了使用电子邮件身份验证,我需要在设置中将UNIQUE_EMAIL设置为True,但这可以防止已经在一个站点中拥有帐户的用户在另一个站点中创建帐户。

最佳答案

我假设您想允许为Django设置中的每个站点分别注册同一封电子邮件。

查看allauth代码;目前看来,这样做是不可行的,这可能是因为allauth在用户注册过程中并未考虑站点ID。

class AppSettings(object):

class AuthenticationMethod:
USERNAME = 'username'
EMAIL = 'email'
USERNAME_EMAIL = 'username_email'

class EmailVerificationMethod:
# After signing up, keep the user account inactive until the email
# address is verified
MANDATORY = 'mandatory'
# Allow login with unverified e-mail (e-mail verification is
# still sent)
OPTIONAL = 'optional'
# Don't send e-mail verification mails during signup
NONE = 'none'

def __init__(self, prefix):
self.prefix = prefix
# If login is by email, email must be required
assert (not self.AUTHENTICATION_METHOD ==
self.AuthenticationMethod.EMAIL) or self.EMAIL_REQUIRED
# If login includes email, login must be unique
assert (self.AUTHENTICATION_METHOD ==
self.AuthenticationMethod.USERNAME) or self.UNIQUE_EMAIL

一种方法是,如下所示:
-将allauth AUTHENTICATION_METHOD保留为用户名
-将网站与用户信息一起存储在用户资料中,或者通过覆盖用户模型来存储。
-使 EmailSite的组合唯一。
-覆盖 LoginView,以便用户输入电子邮件;您可以将 EmailSite的组合转换为唯一用户帐户和用户名;您可以将其传递给allauth以执行登录。

假设您使用Sites框架;您的代码如下所示:
from allauth.account.views import LoginView
from django.core.exceptions import ObjectDoesNotExist


class CustomLoginView(LoginView):

def get_user():
email = request.POST.get('email')
current_site = Site.objects.get_current()
try:
user = User.objects.get(email=email, site=current_site)
except ObjectDoesNotExist:
pass # Handle Error: Perhaps redirect to signup
return user


def dispatch(self, request, *args, **kwargs):
user = self.get_user()
request.POST = request.POST.copy()
request.POST['username'] = user.username
return super(CustomLoginView, self).dispatch(request, *args, **kwargs)

然后用自定义登录 View 对LoginView进行猴子修补:
allauth.account.views.LoginView = CustomLoginView
有关设置站点FK和自定义身份验证后端的相关阅读:
  • How to get unique users across multiple Django sites powered by the "sites" framework?
  • https://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend
  • 关于使用电子邮件作为用户名和多个站点的Django allauth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49692700/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com