当在多个网站上使用Django allauth身份验证方法设置为“电子邮件”时,是否可以使用它?
我希望允许使用电子邮件地址bob@example.com在site1.com和site2.com创建不同的账户。
为了使用电子邮件认证,需要在设置中将UNIQUE_EMAIL设置为True,但这会阻止已经在一个网站上拥有账户的用户在另一个网站上创建账户。
当在多个网站上使用Django allauth身份验证方法设置为“电子邮件”时,是否可以使用它?
我希望允许使用电子邮件地址bob@example.com在site1.com和site2.com创建不同的账户。
为了使用电子邮件认证,需要在设置中将UNIQUE_EMAIL设置为True,但这会阻止已经在一个网站上拥有账户的用户在另一个网站上创建账户。
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
AUTHENTICATION_METHOD
保持为用户名
- 存储站点信息与用户信息一起,可以通过UserProfile或覆盖User Model实现。
- 使Email
和Site
的组合唯一。
- 覆盖LoginView
以便用户输入电子邮件;您可以将Email
和Site
的组合翻译为唯一的用户帐户和用户名,然后将其传递给allauth以执行登录。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)
然后使用自定义登录视图monkey-patch LoginView:
allauth.account.views.LoginView = CustomLoginView
有关设置Site FK和自定义认证后端的相关阅读: