Python Django Custom Authentication with Email Verification - Complete Project Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys I'm Pico and in this video I'm going to show you exactly how to create your own secure email verification system in Jango it's going to be fun I want to make this video as quick as possible but at the same time I want to make sure that whoever is watching does not feel like they missed something that's why I'll be starting from an empty directory going to call it email ver ver for verify we're going to open it in Visual Studio code next thing we need to do is create a python environment and we got to wait a bit all right superb so now that we have the dotv environment ready let's go ahead and open new terminal now we can install D Jango so pip install D Jango hit enter we have to wait a bit while we wait I would like to ask you to hit the Thumbs Up Button if you like the content so far and to subscribe because that really motivates me to make more videos thank you okay now let's use the D Jango admin executable to start project so Jango Das admin start project and how about we call our project a mail ver pro pro for project all right let's hit enter okay and here we have the scaffolding of our project yay right let's CD into it and let's use manage.py to run server so Pi manage.py run server let's follow link Tada okay now let's disconnect next server again and let's run migrations Pi manage.py M great all right so since the point of this video is to learn how to create email verification let's begin by configuring our email settings so that we can send our users emails so the first thing I would do is create a new file and I'll call it n and that's where I would keep sensitive environment variables such as the email address that I will use to send the info I'm just going to put in fake information for now so fake fake.com and I'll also keep in my emails password which will also be fake and now in order to be able to use my environment variables in settings.py I'm going to install python. EnV the command is PIP install python d.n I'm just going to paste it and hit enter and now in order to use environment variables we have to import. EnV from load. EnV and then we got a load. EnV oh and we also need to import OS okay now let's scroll all the way to the bottom and we want to create variables to hold the email that we've added to our n file so os. Environ doget and we've named the email variable in our n file mail in all caps so we'll just get it it and now let's create a variable to hold our password so same idea os. Environ doget and we named the variable that holds our password password right yep okie dokie and now let's configure our email backend settings to do this I always like to check the docs um yeah so I'm just going to use Jango cor mail SMTP smt PP stands for a simple mail transfer protocol and I will be using Outlook to send my users emails so my email host will be SMTP D mail. outlook.com email port to 587 email use TLS true TLS stands for transport layer security and setting it to True indicates that we want to use a secure connection okay and now email host user is our email so mail email host password is our password so I'll set it to mail pass and finally we want to add the from email and we want to set it to mail next up we're going to create a new file in our project directory and we're going to call it tokens dopy and yes you've guessed it that's where we're going to Define our token generator function our token generator function is going to inherit from d jango's password reset token generator so let's quickly import it so from Jango do. oath. tokens import password reset token generator and now let's define account activation token generator which inherits from password reset token generator now let's define method make hash value self user timestamp we want to return a hashed string with our users primary key and the timestamp as well as the active status of our user whether they're active or not and now let's Define variable account activation token and let's set it to account activation token generator okay super cool now that our account activation token generator is ready that makes it a good time to create our registration form class so let's create a new file and call it forms.py and our registration form is going to inherit from the user creation form so let's import it so from Jango do contri o.4 forms we want to import user create no not user change user creation form and of course uh from Jango we want to import forms we want to also import our user models so from D Jango do contrib do oath. models import user and we're also going to need to import validation error so from Jango do core. exceptions import validation error now let's define our registration form so class registration form and like we've said it inherits from user creation form and we need an email field so email equals forms. email field and we want to make it required let's define class meta right our model is user model yay okay and our fields are username email password one and password two all right and we need to make sure that our users cannot use the same email more than once so a user cannot register with the same email um so in order to do that let's create a method how about we call it it clean email and now we want to get a hold of the email so self. clean data. get email all right and now let's add an if statement so if user doobs do filter email equal email exists then we want to raise validation error and say an account with this email address already exists right and we want to return email all right and now let's create our views let's create a new file and let's call it views.py okay how about we begin by defining our registration view I'm going to call it register user um and take send request as a Pam now let's create an instance of our registration form of course for that to be possible we are going to need to import our form so from fors import registration form and now we can create an instance of our form and then we want to check if the request method is a post method so if request. method is post then we want to bind the form to the submitted data so form registration form request. poost and we want to check if our form is valid if the form is valid then a new user instance is create using the form data so form do save we want to set commit to false and we initially want to set user as active to false as well finally we want to save that okay so by doing so our user is safe to the database however activation is pending now after saving our user we want to create an activation email so in order to be able to do that we are going to need get current site so let's import it from Jango do contrib DOS sites do shortcuts import get current site all right so let's create a variable current site and set it to get current site Quest so this gives us the current sites domain all right now let's add in mail subject and set it to let's say activate your account and our message we want to render it to string so uh let's import render to string from Jango do template. loader import render to string all right so message render to string registration slash accountor activation unor email. HTML and this is an HTML file that we have not yet created and we will be creating in a moment right let's add a comma and now let's add in our users data so user user domain current site domain U ID we're going to want to use URL safe and code base 64 so let's also import that so from Jango dos. HTTP import URL safe Bas 64 in code and we also want URL safe base 64 dcode and we also want to import Force bites so from D Jango doils do coding import Force bites uid will be URL save base 64 encode we're going to use for spites to encode our users PK all right next our token we've already defined our account activation token so let's import it so from tokens import account activation token and our token would be account activation token do make token user all right and we want to send the email to the users provided email so let's create a variable and call it to email and we want to get the email from the form so form. blind data. G email and our email should be set to email message which we should import as well from Jango doore word. email so let's import it so from Jango core. mail import email message and I'll email message we have the mail subject and the message and it will be sent to our to email that we've just set above all right and then we want to send the email so email sent and then once the message is sent we want our users to see a message so message success actually for this to work we have to also import messages so from jango.com trip import messages all right so let's go back here where we were typing so messages the success request and and our message should say please check your email to complete the registration and we want to redirect to our index page which which we have not yet created also and I'll be creating it pretty quickly okay now we want to return render request and registration slash register. HTML which we still haven't created and we want to pass in the form all right have I not imported render oh maybe I haven't right so let's import render from Jango do shortcuts import render oh boy and also redirect all right now let's quickly create an index page def index request and we'll be passing messages to our index page so let's create variable index uh let's create the variable messages to display and let's set it to messages. get message and it takes the pram request right and we want to return render request index.html which we haven't created yet and we want to pass in the messages all right cool all right now let's define our activate view let's put it under our register user view let's call it activate and it takes the PRM request as well as u b 64 and token now we want to get a whole hold of our user to do that we'll use the method get user model which we have not imported so let's import it so from Jango do. oath import get user model all right so now can set user to get user model and now we want to try to decode our user ID from base 64 so try uid would be Force underscore string which is a method we also need to import so that's important Force string all right so we want to try Force underscore string and then URL save base 64 decode and what we want to try to decode is the paston user ID all right and next up we want to try and get the correspond fing user from our database so user would be set to user doobs doget PK is uid now let's add an accept block and we want to catch several exceptions in case there are issues with the process I will add in type error value error overflow error and user does not exist and here we want to set our user to none if our authentication is successful then we want to set user to active so let's add an if statement uh to check if user is not none and account activation token do check token user token and we want to set user to active so user. active would be true and we want to save the user so user Dove and then we want to log our user in so login I guess I also need to import login I guess we can import it from here right yes so login request user and then we want to add a success message so message. success request can say your account has [Music] been successfully activated yay and then we want to return redirect reverse login have I imported reverse I guess not so let's import it so from D Jango URLs import reverse this one should be messages what am I doing something is wrong have I imported oh I didn't import login properly all right so yes now login works well else messages. error request and we want the message to say activation link is invalid or expired and we want to return redirect our users to index all right now let's go to our urls.py to define the URL patterns and map them to our our views let's delete this part and let's create the path to our index View and of course for this to work we're going to need to import it actually let's just import all of our views now let's quickly create the URL pattern for our register page so path I count slash register slash you is register user name register okay and now let's create the URL pattern for our activation email so activate slash string idb 64 slash string token we end it with a slash all right and our view was activate and the name is activate also all right and let's also add the URLs from jango's built-in authentication system so we can quickly create a login page and so on so counts oh I didn't import include so include include Jango cont trip. oath. URLs all right and now let's create a template directory let's create it in our root folder now templates okay and in order for D Jango to be able to find our templates let's tell it about its location by going to our settings.py and where we have templates defined where there's is we're going to add base there slash templates all right now let's go back to our templates directory and let's create a new folder and call it registration and that's where we're going to be keeping our authentication related templates and let's also create a file outside our registration um folder and call it index.html and another one that will call base. HTML and that would be our layout file or our base file all right let's begin by adding some HTML boiler plate and where the title is we want to create block title and let's set a default title for a page and call it email there okay okay and within our body let's just create another block and it will be our block content and block all right now let's go to our index.html and let's extend our base. HTML file and let's add block content I always like to type and block right away because I'm afraid of forgetting to write it later okay and as remember we wanted to display messages so let's add for message and messages and let's create a div element to keep our messages and let's give it the class message and add in message. tags this way will be able to style the tags according to the type and then we want to show our message and of course we got to end our for loop with and four okay and it would be cool if we could tell whether our user is authenticated or not so let's add an if statement that would say if user is authenticated and we want to say welcome and then have user. username we say thanks for logging in so I will know if we're logged in else we want to see welcome new user please log in and then we can add a link to our login page so URL login should say login and maybe are user is not register registered so let's add another link tag and to a link to oh forgot the quotation marks I always do this okay In Here Also quotation marks don't forget the quotation marks okay URL register and it should say register okay and then we want to end if oh I I I put I kept this inside the div for the messages which is not what I wanted to do so let's put the div up there before the end for and actually let's create a new div and give it the class Center and yeah I still have not decided if I will be adding CSS styling or not but just in case it's good to have classes ready and now let's go to our registration directory and create a new file and uh let's call it register do. HTML and the first thing we want to do is just like we've done in our index. HTML we want to extend base. HTML and we also want to get hold of our block content Okie doie and now let's also add then div with the class Center and we want to create a form element with the method post and action URL register we want to add a csrf token we want to render our form as speed all right and then let's add a submit button button type submit and uh our button should say register because this is where users will register let's also add blog title and have it say register okay let's create a new file and call it login. HTML and that would be our login page and I'm just going to copy the code from our uh register. HTML and just put it in the login. HTML and I'll change block title to say login and the button to say login instead of register and of course the method should be also changed to URL login all right and now let's create another file and this file will be uh our activation email actually I forgot what I called it so I'll go back to views.py yes we've called it accounts uncore Activation .html so I'm just going to copy the name and make a new file here it is and um let's write our email we want to say hi and then we want to get our user username so hi user. username and we want to say here is the activation link and now let's construct our activation link so it'll be HTTP domain and then URL activate and then uid b64 = 2 uid and token is token all right and now let's add uid b64 and set it to uid and token that set it to token and now if we run server and check our website we're supposed to see our index page and registration page login page all that and hopefully our activation email should work but before we try it let's go to our settings.py and let's add the line login uncore redirect uncore URL equal between quotation slash and that's because we want users to be redirected to the index page once they log in by default jeno redirects logged in users to accounts SL profile which we have not created all right and since we are in settings.py how about we also tell Jango where to find our Statics directory which we have not yet created but we will be creating to keep our styles. CSS file so let's add static files dares and let's set it to base D comma static okay and now let's run server so Pi manage.py run server all right here's our index page I'll hit register and I'll try to create a new account let's make our username Pico Pico and I'll add in a real email address to to see if verification works now password right let's click on register all right awesome we were directed back to our index page and we see the message please check your email to complete the registration of course we can use CSS to style our message and give it a different color and maybe we'll do that in a bit now I'll check my email to see if I Reed received the message okay maybe it's in spam yeah here it is okay it says hi Pico Pico here is the activation link right let's click on it and we were redirected to the login page so I'm just going to try to log in right Pico Pico and the password okay log in yay it says your account has been successfully activated and we are logged in it says welcome Pico Pico thanks for logging in cool how about we see if we can style our messages so I'm going to create a new directory and call it static within it I'm going to create a new directory call it CSS andin this directory I'll create styles. CSS all right and now let's just add some styling for example I'll start by changing the font family to S serif and I'll add some styling to the body I'll make display Flex align items Center justify content Center as well height 100 VH Flex Direction column all right and now let's add styling to our messages so message. error let's make the color red and for message success let's make the color green all right actually I remember that when we were redirected to the login page I did not see a message so so um I'm guessing we for I forgot to add a message block so I'm just going to do that now I'll just copy it from our index.html and I will paste it here all right and now if we want to see The Styling we've added we have to go back to our base. HTML and add the line load static and then we need to link to our CSS file so let's add the link tag link R stylesheet type text SL CSS and H EF static CSS SL styles.css all right so now hopefully when we refresh we will see our style changes and yay our Center div is in the center and now I hope that when we register again we will see changes in the color of our our messages so I'm going to try to create a new account real quick I'll call it pico2 and I'll add in a real email address and I'll hit enter the success message is green and now if I go and try to check my email yes here it is okay click on the link and yay here's our message and it is green that's cool right now let's see what would happen if we click on an invalid link the message is read we did it all right guys thank you so much for watching if you have any questions please leave them down below if you enjoyed the video please hit the thumbs up button and don't forget to subscribe thanks again have a lovely day and see you soon goodbye a
Info
Channel: Piko Can Fly
Views: 2,721
Rating: undefined out of 5
Keywords: python, django, fullstack, webdev, javascript, backend, developer, project, beginner, friendly, coding adventure, fireship, code with, code along, tutorial, guide, awesome, smart, best, cute, coding, girl, coders, girls can code, programming, API, portfolio project, easy, idea, portfolio, develop, code, js, html, django templating, full-stack, design, database, authentication, user class, django project, settings.py, register, templates, webdev explained, login page, token, email, configuration, verification
Id: UV3bZbfEizo
Channel Id: undefined
Length: 37min 58sec (2278 seconds)
Published: Sat Feb 03 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.