我正在尝试重新利用django-rest-framework-simplejwt以完全不同的方式进行身份验证(电话号码和短信验证码在两个不同的请求中)。问题是我已经开发了所有东西,但是由于这个身份验证系统在项目中的紧密集成,我必须手动触发 TokenObtainPairView,这样用户仍然会收到令牌并在系统中进行身份验证。
有什么办法可以做到吗?我考虑过手动触发视图,但这不起作用,因为即使我为该视图自定义序列化程序,我也无法覆盖用户的标准用户名/密码(用户没有密码并且用户名是随机的)
关于如何做到这一点的任何想法?
我目前的代码是这样的:
class LoginResource(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request):
payload = json.loads(request.body)
try:
profile = UserProfile.objects.get(phone=payload.get('phone', ''))
code = codegenerator()
profile.authentication_code = code
profile.save()
# TODO: Send the generated code over SMS
send_mail(
'Your authentication code',
'Your authentication code is: {}'.format(code),
settings.EMAIL_SEND_FROM,
(profile.email,),
fail_silently=False,
)
payload = {
"status": "success"
}
return JsonResponse(payload, status=200, safe=False)
except Exception as e:
payload = {
"status": "error",
"message": "Unable to obtain the user: {}".format(e)
}
return JsonResponse(payload, status=500, safe=False)
class ValidateCodeAndLogin(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request):
payload = json.loads(request.body)
try:
profile = UserProfile.objects.get(phone=payload.get('phone', ''))
code = payload.get('validation_code', 'INVALID')
if code == profile.authentication_code:
profile.validated = True
profile.authentication_code = ''
profile.save()
#
# TODO: Return the JWT token
#
else:
payload = {
"status": "error",
"message": "Invalid authentication code"
}
return JsonResponse(payload, status=401, safe=False)
except Exception as e:
payload = {
"status": "error",
"message": "Unable to obtain the user: {}".format(e)
}
return JsonResponse(payload, status=500, safe=False)