Securing your Python Django App with One Time Passwords | How to set OTP in Django

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we will add an additional security layer for our Django application called one-time password so let me show you exactly what we are going to do over here I have a login form where I need to input my credentials but even if they are correct I won't be logged into the system right away so I'm going to put in the correct credentials and now I have one-time password in this video we are going to grab the one-time password from the terminal so this is what I'm going to do right now I'm going to copy it paste it and now I'm logged in if I log out and put in a wrong password I will have invalid username or password if I type in the correct password and I put in the wrong code over here I will get invalid one-time password if I wait over a minute with my one-time password I will have an information that my one-time password has expired so without further Ado let's get started foreign so before we begin to code let's take a look at what have I done so far so for this tutorial purposes I've created a brand new project and I named it core and currently I'm inside of the source directory in the core folder in the settings py file if we take a look at the installed apps list over here you can notice that I didn't add any applications and I won't be adding any applications in this particular video we don't need it we created the viewspy file directly in the main project folder so if we scroll down we have a login URL and then in the template section I told Django where to look for additional templates and according to those settings I place the templates folder in the main directory and I created four templates one base HTML and then three other templates which will parrot from base HTML if we scroll down to the time zone I also added my current time zone over here so this is it for the settings py file let's move to the uspy file of the core directory over here I have four views the first one is the login View and as you can see it is almost finished and this is because we are not focusing on a traditional authentication system in this particular tutorial we are focusing on adding this extra security layer and this extra security layer will be added over here so let's go through this view very quickly we are checking if the request method is equal to post then we are gathering the username and the password from the form and then we are trying to get the user with authenticate passing the request username and password and then if the user is not none we are going to be taken to the OTP which corresponds with the OTP View so usually over here we are simply logging into the system here we are going to be redirecting to another place where the login functionality will be continued so in the OTP view we will have a form with one input OTP and we will get this OTP from the form and then if everything goes correctly we will then be taken to the main view this main view is wrapped with the login required decorator and this means that only logged in users are allowed inside so if everything goes well we will be taken to the main View and from this main view we will be able to Simply log out and so those four views have been already registered by me in the urlspy file in the URL patterns starting from the main view login view OTP View and the logout view I also have a you Intel's py file for the send OTP function over here we will be generating one-time passwords and in this simple tutorial we will be getting the OTP from the terminal however if you would like to extend this example you can also send it by email over here or maybe by SMS so let's take a look at the template starting from the base HTML so this is our main template from which other templates will inherit and this is an ordinary get started bootstrap template with some few modifications the most important one is that I've placed a div with the class container margin top 3 and this div wraps our blog content okay so if we now take a look at the logic login HTML and this is a template where we have a form and in case of any errors we will also display the errors over here but the main part is the form where we have an opportunity to gather the username and the password from the user and then we have this button to submit this form so in the viewspy file we are gathering the username and the password from this particular place okay and then we have the main HTML this is just a very simple template with a home page two break lines and a button to log out and then we have an empty OTP HTML so if we take a look at the views py we can notice that we are redirecting to OTP this OTP is now empty but we can place over here OTP save this and then over here just be sure to add a super user okay and then let's try to log in I'm going to press the login button and I'm taken to the OTP so what we can do right now is to go to login grab this form with the error message as well and then in the OTP we are going to place this piece of code and make some small modifications so I'm going to delete the password okay I don't need it and then what I'm going to also do over here is to change the username to OTP the label will be OTP and the name is going to be OTP all right so now our OTP will look like this okay let's also change this login to maybe confirm confirm all right let's save this refresh and there it is all right but we are not generating one-time passwords just yet so let's actually do this and as mentioned before we will do it in the send OTP before we actually um put the code inside of this function this helper function we need to install a package called piotp so I'm going to quit the development server from running bit install by OT e and let's wait a few seconds there it is so now we can run the server again and we will Begin by importing by OTP all right so now we can generate a random secret key for OTP and I'm going to create a variable called totp tootp stands for time based one-time password so let's write pop t o t p then what we are going to do is to call potp and then random base 32 we are going to call this function and we are going to set the interval to 60 seconds um so we want to have a password valid for 60 seconds in this particular example so as the next step we can get the OTP value so OTP is going to be equal to OTP now okay so this is what the user should be inputting in the template okay if if the user input will match this then we will be very close to success okay next let's um store the secret key in the user session so we will write request session we need to name our key I'm going to call it OTP secret key and this is going to be equal totp secret okay as the next step let's set the expiration time for the OTP and as mentioned before we want our one-time password to be valid for one minute so what I'm going to do is to import something from date time so from date time we want to import date time as well as time Delta there it is and now we can create a variable called valid date and this is going to be equal date time now and we want to add one minute to this to this particular date time so we can do it with time Delta setting minutes as one like this and then again we need to store the expiration time in the user's session so again request session and this is going to be uh named let's call it OTP valid date and we are going to set it to Str ballot date okay and then over here what we could do is to send this OTP by email or by SMS but instead we are going to print with the use of fstring your one time password is and then here let's place in OTP okay so this should work let's save this and let's go to wspy file over here let's begin by importing um the send or send OTP function so from utils UI we want to import send OTP and then we are going to use it over here send OTP and we need to pass in the request okay so as the next step we can actually focus on the OTP view here what I'm going to do is to grab the first two lines from the login View and paste them in the OTP View so initially we will have the error message set to none and then we are going to do a if check the request method is equal to post then we are going to get the OTP entered by the user and also we will grab the username from the session so OTP is going to be equal and then request post and then OTP all right and from this in terms of getting the username from the session we are setting it over here so we can simply grab this part and create a variable username and set it to request session username okay now we can try to get the secret key and the OTP expiration time from the session so what I'm going to do is to create a variable OTP Secret key and this is going to be equal request session and then what we want to do is to grab the OTP secret key all right I'm going to copy this paste it below and here we will have the OTP valid until and this is going to be OTP valid um two all right so we can do a if check if OTP community secret key and OTP valid valid until is not none then what we are going to do is to convert this string because OTP valid until is a string and we want to have a python date time object okay so we will have a valid until variable and this is going to be equal date time okay so we need to import date time so from date time we want to import date time all right and here we can use date time and then from ISO format and we will pass in this OTP valid until okay and having this we can actually check if the OTP is valid we can write if valid until is greater than date time now okay so if now we have for example um this is time now let's say okay and 25 seconds okay and then valid until is let's say foreign 56 seconds okay so if this is valid until and this is date time now and our one-time password is valid for one minute this will be true okay and we can continue if it's true so um as the next step we are going to uh check the secret key okay so we will have this additional security step to P is equal to and then p o t p e we need to import import p o t p all right and then over here it's going to be totp and then OTP secret key like this and interval 60. okay and now we can do a check if top verify verify where we are passing our OTP is true and if this is the case we can now log in the user so I'm going to import login and then I'm going to write login I'm going to pass in the request and the user which we need to actually grab so the user is going to be equal and we need to do some imports over here so from Django contrib house and then models we want to import the user model and also let's just grab get object or 404 so um let's grab the user with getobjector 404 and here I'm going to pass into user and set the username as the user name okay so the username we have over here and we are getting it from um where is it from over here okay so if this is the case now we can pass in also the user and simply log in and then we will need to be redirected somewhere but before we do the redirect let's remove the secret key and OTP expiration time from the session so delete request session like this okay so we want to delete the OTP secret key and OTP valid until and then we want to return redirect and we want to be redirected to main okay and then we will have for a little bit later some else statements where we will be setting the error messages so for now I'm just going to put in everywhere pass okay and yeah I think we can try this so um yeah let's see if this will work or if we are missing something or we did something wrong in okay we have our one-time password over here I'm going to copy it and here at OTP OTP valid until line 31. OTP valid until util's OTP um okay wrong I use the wrong key sorry guys so OTP valid date like this sorry sorry about this mistake um let's try this one more time [Music] let's also change this OTP valid until over here okay let's save this and let's start from the beginning OTP I'm going to grab the one-time password confirm and this is working so we are logged in now we can log out and try it one more time foreign and this time it didn't work so the question is why um what I'm going to do is to handle those um error messages which can obviously help us and I made some mistakes so this is the first else for this uh if check then a valid until and then if OTP secret and OTP valid until it's not known we don't need one for the request method post so first of all what I'm going to do is to set an error message as invalid one time password okay I'm going to copy it paste it here we will have that one time password has expired okay and then over here we will have simply an error message with oops something went drunk okay let's uh let's also pass the error message to the template okay and let's try this from the beginning login one-time password let's copy it paste it and this worked okay let's do it one more time get the new one-time password and it worked so I don't know why why it didn't work the first time um I'm going to do it one more time just to be sure okay first I'm going to put in something else okay we have invalid one-time press password now I'm going to con input the correct one and we're taking to the home page okay I'm going to log in one more time but now I'm going to wait for this one time password and what I'm going to do in the meantime is to go to the main View and I'm going to do a if check if user name in request session then I'm going to delete this username so delete request session session username all right let's save this and then let's go over here I hope um the time has uh passed and we can actually get an error that this one-time password has expired so let's find out I'm going to paste it and we get one time password has expired all right guys so this is it I hope you guys enjoyed this tutorial if you did please consider subscribing to the channel and hope to see you soon in the next video take care and bye
Info
Channel: Pyplane
Views: 15,726
Rating: undefined out of 5
Keywords: django otp, django otp based authentication, django otp verification, django security, django one time password, django tutorial python, django authentication, django authentication tutorial, django tutorial 2023, django otp project, pyotp django, pyotp one time password, web development, django development, django development tutorial, python otp verification, python pyotp example, pyotp web app, django project 2023, pyplane django, pyplane code
Id: DDSN1Tq9hz0
Channel Id: undefined
Length: 24min 3sec (1443 seconds)
Published: Mon Feb 20 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.