我们可以通过实现我们自己的电子邮件身份验证后端来做到这一点。
您可以执行以下操作:
第 1 步在设置中替换自定义用户模型:
由于我们不会使用 Django 的默认 User 模型进行身份验证,我们需要在 settings.py 中定义我们的自定义 MyUser 模型。在项目的设置中将MyUser 指定为AUTH_USER_MODEL。
AUTH_USER_MODEL = 'myapp.MyUser'
Step-2 编写自定义身份验证后端的逻辑:
要编写我们自己的身份验证后端,我们需要实现至少两种方法,即get_user(user_id) 和authenticate(**credentials)。
from django.contrib.auth import get_user_model
from django.contrib.auth.models import check_password
class MyEmailBackend(object):
"""
Custom Email Backend to perform authentication via email
"""
def authenticate(self, username=None, password=None):
my_user_model = get_user_model()
try:
user = my_user_model.objects.get(email=username)
if user.check_password(password):
return user # return user on valid credentials
except my_user_model.DoesNotExist:
return None # return None if custom user model does not exist
except:
return None # return None in case of other exceptions
def get_user(self, user_id):
my_user_model = get_user_model()
try:
return my_user_model.objects.get(pk=user_id)
except my_user_model.DoesNotExist:
return None
Step-3 在设置中指定自定义身份验证后端:
编写自定义身份验证后端后,在AUTHENTICATION_BACKENDS 设置中指定此身份验证后端。
AUTHENTICATION_BACKENDS 包含要使用的身份验证后端列表。 Django 尝试在其所有身份验证后端进行身份验证。如果第一个身份验证方法失败,Django 会尝试第二个,依此类推,直到尝试了所有后端。
AUTHENTICATION_BACKENDS = (
'my_app.backends.MyEmailBackend', # our custom authentication backend
'django.contrib.auth.backends.ModelBackend' # fallback to default authentication backend if first fails
)
如果通过MyEmailBackend 的身份验证失败,即无法通过email 对用户进行身份验证,那么我们使用Django 的默认身份验证ModelBackend,它将尝试通过MyUser 模型的username 字段进行身份验证。