gpt4 book ai didi

python - Django Rest Framework中的OTP验证

转载 作者:行者123 更新时间:2023-12-04 15:59:34 25 4
gpt4 key购买 nike

我正在尝试制作一个 django 应用程序,我想在其中创建一个 opt 验证,但我很困惑什么是正确的方法来做到这一点。这是我到目前为止所做的:

模型.py

class User(AbstractUser):
is_shipper = models.BooleanField(default=False)
is_ftlsupp = models.BooleanField(default=False)
is_ptlsupp = models.BooleanField(default=False)
otp = models.IntegerField(default=1620122)
verified = models.BooleanField(default=False)

序列化器.py
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)

class Meta:
model = User
fields = "__all__"
read_only_fields = ('id', 'verified')

def create(self, validated_data):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])

def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)

otp = random_with_N_digits(6)
user.otp = otp
user.save()

subject = 'Please Confirm Your Account'
message = 'Your 6 Digit Verification Pin: {}'.format(otp)
email_from = '*****'
recipient_list = [str(user.email), ]
send_mail(subject, message, email_from, recipient_list)
return user

如何使用此 otp 来验证用户?
我的方法是,如果用户已创建并且他尝试登录,那么显然他没有被验证为 verified = models.BooleanField(default=False)所以他会看到一个弹出窗口,输入他在邮件中收到的 otp,如果 otp 匹配,他可以继续并登录

View .py

验证 otp
class verifyOTPView(APIView):

def post(self, request):
username = request.data["username"]
otp = int(request.data["otp"])
user = User.objects.get(username=username)
if int(user.otp)==otp:
user.verified = True
#user.otp.delete() #?? How to handle the otp, Should I set it to null??
user.save()
return Response("Verification Successful")
else:
raise PermissionDenied("OTP Verification failed")

请建议我应该如何进行,使用相同的 otp 是否明智?重置密码字段?

最佳答案

一、创建PhoneOTP模型

class PhoneOTP(models.Model):
username = models.CharField(max_length=254, unique=True, blank=True, default=False)
phone_regex = RegexValidator( regex = r'^\+?1?\d{9,14}$', message = "Phone number must be entered in the form of +919999999999.")
name = models.CharField(max_length=254, blank=True, null=True)
phone = models.CharField(validators = [phone_regex], max_length=17)
otp = models.CharField(max_length=9, blank=True, null=True)
count = models.IntegerField(default=0, help_text = 'Number of opt_sent')
validated = models.BooleanField(default=False, help_text= 'if it is true, that means user have validate opt correctly in seconds')

def __str__(self):
return str(self.phone) + ' is sent ' + str(self.otp)
然后创建一个OTP生成 View 和验证 View
class ValidatePhoneSendOTP(APIView):
permission_classes = (permissions.AllowAny, )
def post(self, request, *args, **kwargs):
name = request.data.get('name' , False)
phone_number = request.data.get('phone')
if phone_number:
phone = str(phone_number)
user = User.objects.filter(phone__iexact = phone)

if user.exists():
return Response({
'status' : False,
'detail' : 'Phone number already exists.'
})
else:
key = send_otp(phone)

if key:
old = Customer.objects.filter(phone__iexact = phone)
if old.exists():
old = old.first()
count = old.count
# if count > 20:
# return Response({
# 'status': False,
# 'detail' : 'Sending otp error. Limit Exceeded. Please contact customer support.'
# })
old.count = count + 1
old.save()
print('Count Increase', count)
return Response({
'status' : True,
'detail' : 'OTP sent successfully.'
})
else:
PhoneOTP.objects.create(
# name = name,
phone = phone,
otp = key,

)
link = f'API-urls'
requests.get(link)
return Response({
'status' : True,
'detail' : 'OTP sent successfully.'
})



else:
return Response({
'status' : False,
'detail' : 'Sending OTP error.'
})

else:
return Response({
'status' : False,
'detail' : 'Phone number is not given in post request.'
})


def send_otp(phone):
if phone:
key = random.randint(999,9999)
print(key)
return key
else:
return False


class ValidateOTP(APIView):
permission_classes = (permissions.AllowAny, )
def post(self, request, *args, **kwargs):
phone = request.data.get('phone' , False)
otp_sent = request.data.get('otp', False)

if phone and otp_sent:
old = Phone.objects.filter(phone__iexact = phone)
if old.exists():
old = old.first()
otp = old.otp
if str(otp_sent) == str(otp):
old.validated = True
old.save()
return Response({
'status' : True,
'detail' : 'OTP mactched. Please proceed for registration.'
})

else:
return Response({
'status' : False,
'detail' : 'OTP incorrect.'
})
else:
return Response({
'status' : False,
'detail' : 'First proceed via sending otp request.'
})
else:
return Response({
'status' : False,
'detail' : 'Please provide both phone and otp for validations'
})
通过这种方式,您可以通过 OTP 进行用户验证

关于python - Django Rest Framework中的OTP验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61769602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com