how to send OTP in django via sms or email

Viewed 26

I need some help sending and verifying OTP in Django. am trying to add 2FA to my authentication module and I came across a package called pyotp that helps generate and verify OTP. The good thing is that am able to use this package to generate OTP but my problem is how to verify this OTP if expired or incorrect when I prompt the user to supply the otp sent to his/her phone or mail. the below code is what I have implemented from the doc but I don't know why the verification part ain't working. I could actually verify manually but that wont tell me if OTP has expired or not and i don't also know how to expire OTP after a particular time

TO GENERATE OTP

import pyotp
 base32secret3232 = pyotp.random_base32()
 otp = pyotp.TOTP(base32secret3232)
 time_otp = otp.now() 
 user.otp = time_otp
 user.save()

TO VERIFY OTP

  if totp.verify(otp):
    user.is_verified = True
    user.save()
1 Answers

after much more research, I was able to fix it. the code below will generate the otp

1. import pyotp
2. base32secret3232 = pyotp.random_base32()
3. otp = pyotp.TOTP(base32secret3232, interval=60, digits=5)
4. time_otp = otp.now() 
5. user.otp = time_otp
6. user.otp_secret = base32secret3232
7. user.save()
8. send the otp to the user's email or phone

line 1 import the package after pip install line 2 generates a secrete key, line 3 specifies the expiry time(sec) and the number of digits the otp should have line 4 generate an OTP from the secret key using the current time Lines 5 and 6 save the generated secret key and otp to the database, although you might choose not to save the otp

the code below verifies the otp

1 otp = request.GET.get('otp')
2 user_id = request.GET.get('id')

3        try:
4            user = User.objects.get(otp = otp, id = user_id)
5            if  pyotp.TOTP(user.otp_secrete, interval=60, digits=5).verify(otp):
6                user.is_verified = True
7                user.save()
8                return Response({'email':'Successully activated'},  
status=status.HTTP_200_OK)
9            else:
                return Response({'email':'Activations OTP expired or Invalid OTP'}, status=status.HTTP_400_BAD_REQUEST)
        except:
            return Response({'error': ' something went wrong'}, status=status.HTTP_400_BAD_REQUEST)

lines 1 and 2 get the otp from the user and also user_id line 4 queries the database with the above details, if the user is available line 5 verifies the supplied otp using the saved secret key. NOTE: make sure that interval=60, digits=5 used in generating the otp is the same as the one used in verifying the otp else it won't work. thanks and i hope it helps someone out there

Related