How to implement OTP based verification before letting the user to create a new password using pyotp?

Question:

I am very new to Django rest framework. I am building APIs for my mobile application.
In forgot password module, I have the below flow

  1. Ask user to enter mobile
  2. check existence
  3. If exists – > send OTP
  4. Verify and let user create a new password.

But in this case, I would like to know the way of handle the below situation.

When one user requests otp and waiting for it to verify, meanwhile another user requests for OTP
At this time, how to handle the both users?
I thought of

  1. creating the dictionary and save the user id as key and otp as value in views.py to verify particular user.
  2. store the otp temporarily until it verifies.

Which is the secured way and any alternative for this kind of scenario?

Asked By: Eswar

||

Answers:

You should create a table look like this:

===== UserOTP =====
user: foreign-key to user
code: CharField, random generated code here (or token)
create_date: auto-fill created datetime
used_date: nullable datetime field

Then on each password reset request create a row on this table, send generated code to user via SMS or Email,

And then on another end-point receive the code from user and check it (for expiration and used before, belongs to this user and etc.) then continue password reset process.

Answered By: pedram

There is a better way to do this, since otp are for temporary use, there is no use case for storing them in database, we can use hashlib.blake2s(b'otp', key=b'secretkey').hexdigest() to generate a hashed string and send it to user and then accept the same hashstring in the otp verification request and check for truthy of hashstring generated from user shared otp, this is oneway to handle otp verification.

The hashlibs blake2s accepts only bytestring, and you can also use any other hashing algorithm for this purpose. I am also open to ideas if there are any better ways to do this, please update in comments.

Using sessions would be better choice as it works for both django and djangorestframework.

Answered By: Santhosh Reddy