使用电子邮件 ID 作为唯一密钥的自定义用户模型的 Django 身份验证
Django authentication with custom user model with email-id as unique key
为了在电子邮件 ID 上实现唯一约束(不重复默认用户模型字段),我这样做了
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# some extra fields
class Meta:
unique_together = ('email', )
然后在设置文件中 AUTH_USER_MODEL = 'myApp.User'
mysql table 将两列(用户名和电子邮件)显示为 UNI 键。
到目前为止看起来不错,但在身份验证方面,我不确定我哪里出错了。但它不是 working/loggin-in
当用户名是唯一密钥并且我们通过用户名而不是电子邮件登录时,此代码有效。
任何 help/leads 将不胜感激。
编辑:我是否必须编写自定义模型后端(在此处解释 http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/)
但不确定如何,我在这里看到很多代码 https://github.com/django/django/blob/master/django/contrib/auth/init.py
您需要这样定义 backends.py:
from django.contrib.auth.models import User, check_password
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
""" Get a User object from the user_id. """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
然后在您的设置文件中添加:
AUTHENTICATION_BACKENDS = ('backends.EmailAuthBackend',)
这将启用电子邮件登录。
有关详细信息,请访问 this。
为了在电子邮件 ID 上实现唯一约束(不重复默认用户模型字段),我这样做了
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# some extra fields
class Meta:
unique_together = ('email', )
然后在设置文件中 AUTH_USER_MODEL = 'myApp.User'
mysql table 将两列(用户名和电子邮件)显示为 UNI 键。
到目前为止看起来不错,但在身份验证方面,我不确定我哪里出错了。但它不是 working/loggin-in
当用户名是唯一密钥并且我们通过用户名而不是电子邮件登录时,此代码有效。
任何 help/leads 将不胜感激。
编辑:我是否必须编写自定义模型后端(在此处解释 http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) 但不确定如何,我在这里看到很多代码 https://github.com/django/django/blob/master/django/contrib/auth/init.py
您需要这样定义 backends.py:
from django.contrib.auth.models import User, check_password
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
""" Get a User object from the user_id. """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
然后在您的设置文件中添加:
AUTHENTICATION_BACKENDS = ('backends.EmailAuthBackend',)
这将启用电子邮件登录。
有关详细信息,请访问 this。