I am trying to make a django app in which I want to create a opt verification but I am confused what is the right approach to do it. Here's what I have done so far:
Models.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)
Serializers.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
How can I use this otp to verify the user?
My approach is that if the user is created and he tries to login then obviously he is unverified as verified = models.BooleanField(default=False) so he'd be shown a pop up to enter the otp he received on his mail and if the otp matches he can proceed and log-in
Views.py
To verify 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")
Please suggest how should I proceed and would it be wise to use the same otp field for Resetting the password?