RIO*_*RIO 6 python django django-authentication custom-authentication
我正在开发一个 Django 项目,在该项目中我定义了一个自定义用户模型,我需要为其编写自定义身份验证方法,按照我编写的文档,如下所示,但我在视图中调用它时遇到问题。 py请通过查看以下代码来帮助我
我已经定义了我的自定义后端,如下所示
我的自定义身份验证后端
from django.contrib.auth.backends import BaseBackend
from .models import User
from IntellerMatrix.CommonUtilities.constants import Constants
class AuthenticationBackend(BaseBackend):
"""
Authentication Backend
:To manage the authentication process of user
"""
def authenticate(self, email=None, password=None):
user = User.objects.get(email=email)
if user is not None and user.check_password(password):
if user.is_active == Constants.YES:
return user
else:
return "User is not activated"
else:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Run Code Online (Sandbox Code Playgroud)
设置.py
AUTHENTICATION_BACKENDS = ['Modules.users.authentication.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend', ]
Run Code Online (Sandbox Code Playgroud)
视图.py
def login(request):
email = 'ialihaider75@gmail.com'
password = 'ali'
user = # how to call here that custom authentication backend's authenticate method
if user is None:
return HttpResponse("<p>Not Valid</p>")
else:
return HttpResponse(user)
Run Code Online (Sandbox Code Playgroud)
您可以调用该authenticate(..)函数[Django-doc]
\n\n\n用于
\nauthenticate()验证一组凭据。它将凭据作为关键字参数,username对于password默认情况,根据每个身份验证后端检查它们User,如果凭据对于后端有效,则返回一个对象。所以:
from django.contrib.auth import authenticate\n\ndef login(request):\n email = \'ialihaider75@gmail.com\'\n password = \'ali\'\n user = authenticate(request, email=email, password=password)\n\n if user is None:\n return HttpResponse(\'<p>Not Valid</p>\')\n else:\n return HttpResponse(user)Run Code Online (Sandbox Code Playgroud)\n\n请注意,您实现的身份验证方法不能返回字符串。正如编写身份验证后端的文档所述:
\n\n\n\n\n(……)
\n\n无论哪种方式,
\nauthenticate()都应该检查它获取的凭据,如果凭据有效,则返回与这些凭据匹配的用户对象。如果它们\xe2\x80\x99 无效,则应返回None。
class AuthenticationBackend(BaseBackend):\n """\n Authentication Backend\n :To manage the authentication process of user\n """\n\n def authenticate(self, request, email=None, password=None):\n try:\n user = User.objects.get(email=email)\n except User.DoesNotExist:\n return None\n if user is not None and user.check_password(password):\n if user.is_active == Constants.YES:\n return user\n return NoneRun Code Online (Sandbox Code Playgroud)\n\n此外,这不会登录您的使用,这只是检查凭据是否有效。所以如果你想登录用户仍然需要调用login(..)函数[Django-doc] 。