问题描述
我正在尝试使用 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 (将#修改为@)