我正在开发一个 Django 项目,在该项目中我定义了一个自定义用户模型,我需要为其编写自定义身份验证方法,按照我编写的文档,如下所示但是我在 View 中调用它时遇到问题.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
settings.py
AUTHENTICATION_BACKENDS = ['Modules.users.authentication.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend', ]
Views.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)
最佳答案
您可以调用 authenticate(..)
function [Django-doc]
Use
authenticate()
to verify a set of credentials. It takes credentials as keyword arguments,username
andpassword
for the default case, checks them against each authentication backend, and returns aUser
object if the credentials are valid for a backend. So:
from django.contrib.auth import authenticate
def login(request):
email = 'ialihaider75@gmail.com'
password = 'ali'
user = authenticate(request, email=email, password=password)
if user is None:
return HttpResponse('<p>Not Valid</p>')
else:
return HttpResponse(user)
请注意,您实现的身份验证方法不能返回字符串。作为documentation on writing an authentication backend说:
(…)
Either way,
authenticate()
should check the credentials it gets and return a user object that matches those credentials if the credentials are valid. If they’re not valid, it should returnNone
.
class AuthenticationBackend(BaseBackend):
"""
Authentication Backend
:To manage the authentication process of user
"""
def authenticate(self, request, email=None, password=None):
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return None
if user is not None and user.check_password(password):
if user.is_active == Constants.YES:
return user
return None
此外,这不会登录您的使用,这只是检查凭据是否有效。所以你还是需要调用
login(..)
function [Django-doc]如果你想登录用户。
关于python - 如何在views.py中调用django自定义编写的AuthenticationBackend的authenticate()方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60126770/