Search code examples
djangodjango-rest-frameworkdjango-views

problem in otp validation during login in django rest


I am trying to send otp and then validate otp for login. I am able to send otp but it is not validating for some reason.

the code for sending otp is below and it is working fine-

class SendOTP(APIView):
permission_classes = (AllowAny, )
def post(self, request, *args, **kwargs):
    email = request.data.get('email')
    if email:
        email  = str(email)
        user = User.objects.filter(email__iexact = email)

        if user.exists():
            key = send_otp(email)

            if key:
                old = User.objects.filter(email__iexact=email)
                if old.exists():
                    old = old.first()
                    count = old.count
                    old.count = count + 1
                    old.save()
                    print('Count Increase', count)
                    return Response({
                        'status': True,
                        'detail': 'OTP sent successfully.'
                    })

code for generating 6 digit otp is -

def send_otp(email):
if email:
    digits = [i for i in range(0, 10)]
    key = ""
    for i in range(6):
        index = math.floor(random.random() * 10)
        key += str(digits[index])
    print(key)
    return key
else:
    return False

code for validating email and otp is below but it is not working-

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

    if email and otp_sent:
        e_mail = User.objects.filter(email__iexact = email)
        if e_mail.exists():
            e_mail = e_mail.first()
            otp = e_mail.otp
            print(otp, e_mail, otp_sent)
            if str(otp_sent) == str(otp):
                old.validated = True
                old.save()
                try:
                    payload = JWT_PAYLOAD_HANDLER(old)
                    jwt_token = JWT_ENCODE_HANDLER(payload)
                    update_last_login(None, old)
                except User.DoesNotExist:
                    raise serializers.ValidationError(
                        'User with given email and password does not exists'
                    )
                return Response({
                    'status' : True,
                    'email': email,
                    'token': jwt_token,
                    'detail' : 'OTP mactched.'
                    })

            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 email and otp for validations'
            })

it's is showing None for otp = e_mail.otp. is there a way to make it work?


Solution

  • I don't see where old.otp is being set in the SendOTP class, that's probably why it's None. Should be something like this:

    old.count = count + 1
    old.otp = key
    old.save()
    

    Also, if old.exists(): looks weird in ValidateOTP, since there is no references to the old variable, probably should be if e_mail.exists().