یک مدل Django برای پروفایل کاربریها ایجاد کنید که شامل فیلدهای مربوط به OTP مانند شماره تلفن یا آدرس ایمیل باشد.
منطق تولید و ارسال OTP را هنگام درخواست تأیید هویت کاربر پیادهسازی کنید. این میتواند در یک ویو یا سریالایزر Django انجام شود. در زیر مثال سادهای با استفاده از django_otp نمایش داده شده است:
# views.pyfrom django_otp.plugins.otp_totp.models import TOTPDevice
from rest_framework.views import APIView
from rest_framework.response import Response
classSendOTPView(APIView):
defpost(self, request):
user = request.user # Get the authenticated user
totp_device, created = TOTPDevice.objects.get_or_create(user=user, confirmed=True)
if created:
totp_device.save()
totp_device.throttle_factor = 1# Set throttle factor as needed
totp_device.generate_challenge()
totp_device.save()
totp_device.send_token() # Send OTP via email/SMSreturn Response({"message": "OTP sent successfully"})
```
احراز هویت JWT را با تأیید OTP پیادهسازی کنید. در ادامه، یک نمونه آمده است:
```python
# views.pyfrom rest_framework_simplejwt.views import TokenObtainPairView
from django_otp.plugins.otp_totp.models import TOTPDevice
from rest_framework import status
from rest_framework.response import Response
classOTPTokenObtainPairView(TokenObtainPairView):
defpost(self, request, *args, **kwargs):
# Get the OTP entered by the user
otp = request.data.get("otp")
# Verify OTP
user = request.user # Get the authenticated user
totp_device = TOTPDevice.objects.filter(user=user, confirmed=True).first()
ifnot totp_device:
return Response({"detail": "OTP device not found"}, status=status.HTTP_400_BAD_REQUEST)
ifnot totp_device.verify_token(otp):
return Response({"detail": "Invalid OTP"}, status=status.HTTP_400_BAD_REQUEST)
# Generate JWT tokenreturnsuper().post(request, *args, **kwargs)
```
URLهای خود را برای شامل کردن ویوها و JWT تنظیم کنید و از آنها برای محافظت از نقاط پایانی مورد نیاز با احراز هویت استفاده کنید.
جریان احراز هویت خود را با ارسال درخواستهایی جهت دریافت توکن JWT پس از تأیید OTP آزمایش کنید.