OTP in Django Rest Framework
And Django too!

I write when I experience issues that were rather tough for me to solve or I feel it's something I learned in a complicated way and I'd like to explain them in a much easier way for anyone to understand and not experience what I experienced.
This is a straight-to-the-point article, I'll assume previous experience of Django and the Django Rest Framework as I will not be covering that in this article. This article is for you if you are working on a project and need to quickly implement OTP. This applies to Django too.
I'll be using PyOTP. PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement two-factor (2FA) or multi-factor (MFA) authentication.
First install PyOTP.
pip install pyotp
You don't need to add it to installed app. Next import in your views.py
import pyotp
You could choose to generate the OTP and use it inside the same function but I like to abstract things to keep my code organized. Create a class to generate the OTP which you can then call inside another Class or Function where you need it.
class generateKey:
@staticmethod
def returnValue():
secret = pyotp.random_base32()
totp = pyotp.TOTP(secret, interval=86400)
OTP = totp.now()
return {"totp":secret,"OTP":OTP}
PyOTP generates an activation key from base32 with an expiry time, which is the 'secret' in the code above. 'OTP' is a six digit numeric number generated randomly by PyOTP and is tied to the activation key. The interval can be set to what time you want it to be in seconds and you must use the same value when you want to verify the OTP.
To use the generated activation key and OTP, you can call it by doing something like,
key = generateKey.returnValue()
and then use it like;
otp = key['OTP']
activation_key = key['totp']
That's it. You can then make use of the OTP and activation key in whatever way you deem fit.
To verify the OTP generated, you have to make use of the activation key and the OTP itself, therfore be sure to store the activation key and OTP so that you can call the saved OTP and activation key and verify it with the OTP recieved. To verify OTP, you can do something as;
otp = request.data.get('otp')
...
activation_key = user.activation_key
totp = pyotp.TOTP(activation_key, interval=86400)
verify = totp.verify(otp)
First recieve the otp and then fetch the unique activation key you must have stored somewhere, then use pytotp to verify the activation key while passing along the expiry time you had set. Then verify OTP using the verified activation key which is 'totp' in the code above.
If you are new to Django Rest Framework and all of these is quite strange to you, worry not. I'll write another article explaining how to do this in details. Keep a tab on me.



