Verification code before saving to database

Hello.
I’m trying to achieve something similar to OTP (One Time Password) but instead of login purposes, to authorize submitting a form and saving it to database.
I have a function that returns a random string each time it is called.
Currently, I “found” two approaches:

  • The first one is to restrict the entire form view (I am working with class-based views and in this case, CreateView) with some weird implementation of this app called django-lockdown or something like that.
  • The second one is to generate the ‘code’ in the backend, send it as context and only if the user has typed it right, it submits the form and saves normally.

Of course, the code would be sent to an administrator via email so the user needs to have some sort cleareance before doing anything with the database.
Any help would be appreciated.

Could you use django-sesame’s per-view authentication?

2 Likes

And instead of sending codes I would be sending “magic links” with expiration time, I’ll give it a try, thanks.

For anyone facing the same problem, I did this, I don’t know how secure or optimal is, but satisfies what I am trying to do without any external library, app or package, just using sessions.

  1. When sending the form, instead of saving it directly to the database, save only the modified fields to session variables i.e. request.session['foo'] = something including a variable for the random code generated only when the form is sent.
  2. Get the session variables in the other view, save them like var = request.session.get('foo') and delete them right after (from the session).
  3. Now you can compare, in another form, the codes and if they match, save the data to database, else raise an error or whatever you want.

If anyone has any suggestion of how this could be improved or is a complete nonsense, send me a message and I will edit this answer.

1 Like