如何解决在 Django 中使用 Profile 属性对用户进行身份验证可能存在哪些问题?
我正在尝试使用 username 或 phone_number 和 password 对 Django 中的用户进行身份验证。我们必须扩展 User 模型以添加 phone_number 作为新属性,我使用 Profile 模型中的 OnetoOneField 并使用了 phone_number 使用自定义身份验证后端对用户进行身份验证:
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model
from django.db.models import Q
from .models import Profile
class MyBackend(BaseBackend):
def authenticate(self,request,username=None,password=None):
User = get_user_model()
try:
user = User.objects.get(Q(username=username)|Q(email=username))
except User.DoesNotExist:
try:
profile = Profile.objects.get(phone = username)
user = profile.user
except Profile.DoesNotExist:
user = None
if user and user.check_password(password):
return user
else:
return None
它似乎在使用管理员登录门户登录时有效,但我发现使用 Customusermodel 来实现这一点的建议。
这样做安全吗?要么 我是否必须创建从 AbstractBaseUser 继承的 Customusermodel?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。