我一直在为django应用程序开发custom authentication backend,并且试图理解django为什么建议使用自定义身份验证后端,而不是仅在视图中实现身份验证逻辑。我可以体会到这种设计是模块化的,可以帮助解决各个问题,但这似乎是多余的工作。这是我的实现:
from django.contrib import auth
class Backend:
def authenticate(self, request, **credentials):
email = credentials.get('email', '')
password = credentials.get('pw', '')
user = auth.get_user_model().objects.filter(email=email, password=password).first()
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
class MyAuthViewset(mixins.CreateModelMixin, viewsets.GenericViewSet):
...
def create(...):
# Creates users that pass validation
@action(detail=False, methods['get'])
def login(self, request, *args, **kwargs):
email = credentials.get('email', '')
password = credentials.get('pw', '')
user = auth.authenticate(email=email, pw=password)
if User is None:
return Response(status=status.HTTP_404_NOT_FOUND)
auth.login(request, user)
return Response(status=status.HTTP_302_FOUND)
以下是仅使用视图的实现:
from django.contrib import auth
class MyAuthViewset(mixins.CreateModelMixin, viewsets.GenericViewSet):
...
def create(...):
# Creates users that pass validation
@action(detail=False, methods['get'])
def login(self, request, *args, **kwargs):
user = auth.get_user_model().objects.filter(email=email, password=password).first()
if User is None:
return Response(status=status.HTTP_404_NOT_FOUND)
auth.login(request, user)
return Response(status=status.HTTP_302_FOUND)