Python Flask Authentication Tutorial - Learn Flask Login

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome back in this video i'll show you how to build an authentication system um using flask and python so before i begin i would like to explain how we're going to build it so we're going to be using this library called flask login and we're going to be using flask to build this and what flask login does is it's going to provide user session management it's going to handle a common task of logging in logging out remembering user sessions over an extended period of time and we're going to leave the docs link in the description below also and it also states everything that it does right here and it and states stuff that it won't do and one thing that i won't do is handle user registration so we're going to have to create user registration ourselves and that's fairly easy so with that being said without further ado so now that i've explained what we're going to do we can start so first off i'll start off by installing packages i have the commands for installing the packages in the description if you're on windows copy the windows command and paste it into your terminal and hit enter if you're on mac copy the mac command and paste it into the terminal and hit enter so i'm just going to paste the mac command right here and mine's already installed mines are already installed so that's why it says requirement already satisfied yours might take um 20 seconds to two minutes since all of them so now that we have gotten our packages installed we can start creating our files and folders so i'm going to click right here onto this icon and then i'm going to click this new file icon and then i'm going to create a file called app.pi and this is the python file that we're going to be writing all of our apps code in all right and then i'm going to create two folders one of them is going to be called templates and this is where our html is going to go and then another one of them is going to be called static and this is where the css is going to go so now i've explained creating the files and all that we can finally start coding and to do this i'm just going to open up this app.file which i've which i have open right here and the first line of code that we're going to be writing is from flask import flask and this will import the flash package next i'll make the app instance so i'll do app is equal to flask and then underscore underscore name right there and now whenever we go to our web page we're going to hit a route and that route will be a forward slash and this is where all web pages hit once they're loaded so for example if you were to go to youtube.com you'd see the recommended videos first right so this is basically that so to do that write this down okay so this app.route means that whenever we hit this route we're going to render the contents that are in the function and in this case we're going to render the content inside of this home and the content inside of this home is this hello from class so whenever we um run our app and go to this route we're going to have this rendered next we're going to need a way to run our app so i'm just going to do if underscore underscore name underscore underscore is equal to underscore main underscore underscore i'm going to do app dot run and then debug is equal to true i'm putting debug is equal to true so if we get any errors we can catch them immediately and now we can finally run our app so i'm just gonna so i'm just gonna list the stuff we have in our um folder and i'm gonna run python3 app.pi okay and to run it you're gonna do python3 app.pi if you're on mac and do uh and do python app.pi if you're on windows so once i load this i'm going to go to localhost at port 5000 and as you can see when we hit this forward slash it's going to render hello from flask which is what's exactly supposed to do since hello from flask is rendered at this route so now that we have our home route set up and know how routing works we can move on to rendering pages so as you can see right here we have return hello from flask and this is just rendering plain text but instead of rendering plain text we want to return an html document and to do that i'm just going to open up explorer go into templates and then create a new file called home.html you can name it whatever you want but um for the sake of this tutorial i'm going to name it home.html so i'm going to do an exclamation point and then tab and then inside of here where it just has document i'm just going to rename this to home and then save the changes and in the body i'm just going to put a login authentication system in flask okay and instead of returning this we're going to return this so to return that i'm going to import render template and then i'm just going to put return render template home.html so what this does was previously we had return hello from flask but this time it's going to return this template right here and how this is going to work how render template works is that it goes into this templates folder and then it's going to search for the file that's passed in so right now we've passed in home.html so it's going to search for that and as you can see it's here so it's going to return the content inside of here and we can test this out so i'm just going to run our app using python3 app.pi if you're on windows do python app.pi of course and then go here and type in localhost at port5000 and as you can see whenever we hit the slash it's going to return this so our templates are rendering perfectly fine now we just need to create the login so now that i've shown you how to render templates we can start um creating pages for the login and sign up so to do this we're going to do the same thing i'm going to go into the templates folder and i've created two files and i've created login.html and register.html and inside of login.html i'm going to do the same thing i'm going to do exclamation point and then tab and then in the title i'm just going to put login and in this body i'm just going to put an h1 and i'm going to say login page okay and then we're going to add that route to our app so to do this app.route and then when we go to slash login we're going to return this login page so return render template login.html so if i go to slash login it's going to show that right here now we do the same thing for sign up so for sign up since it's basically the same thing except we're just changing a couple of words i'm gonna select all this and copy it and then paste it into register.html so right here instead of putting login i'm just going to put register instead of printing login page i'm just going to put register page and we're going to be doing the same thing here also but instead of putting login we're going to put register and inside of here i'm just going to put slash register and the function's name is going to be register and then the file's name is register so just do that now if i go into register it's going to say register page so our routing is working but um but we don't want to always you know adjust the url to decide what page we want to go to so let's say i want to go to the home page i don't want to have to go to slash let's say i want to go into the login page i don't want to have to type that in so we can add a button that will lead us to that page or a link that will lead us to that page so i'm just going to go back to the homepage and then in home.html what i'm going to do is actually in our app file i'm going to import something called url4 okay and in home.html i'm just going to make an a tag that will lead us to the login page so i'm just going to do a href and then i'm just going to have this right here and then i'm just going to put login page and then inside of this href i'm just going to do url4 and then a set of quotations and i'm going to put login and what this is going to do is that whenever we press this link it's going to lead us to this login route right here so i'm going to refresh this page and if i click it it brings us to this logging route now we can do the same thing for sign up and i'm just going to add a break a line break after this so i'm going to copy this line and then since it's the same thing i'm just going to register register right here and what this is going to do is just call this route right here so if i refresh it if i click register page it leads me to here if i click login page it leads me to here okay so this is how we know that our routing is working fine and usually in login pages if you don't have an account it's going to say it's going to have a link for you to sign up so we're going to add that and to do this i'm just going to copy the stuff from home.hmr right here so i'm just going to copy this uh register line so i'll just copy it right to that until there and then um i'm just gonna put don't have an account sign up okay and if i go into the login page it's gonna say don't have an account sign up and it's gonna lead to this register page and in register pages they have this thing where it says um already have an account log in so to do that i'm just going to copy the same thing so copy the stuff for login and then paste it right here and instead of putting log in page i'm just going to put already have an account log in okay then if i refresh it it brings me to here and if i click this it brings me to here and if i go into home it has the links for both pages so now that i've showed you guys how to do routing and rendering templates we can finally start working on the login authentication system so first i'd like to explain how this is going to work so first we're going to have a sqlite database which will connect through using sql alchemy then in our database we'll have a user table where our users will be stored the users will have a username and a password when we register we'll have a form and in that form the users will type in a username and password for them to create their account when they press the submit button the information that they typed in will be stored in the database in the user table when we log in we'll have a form that will include the username and the password and um those are going to be used to log in the user when the user presses the login button will filter the database for for the username that they entered if there's a username that if the username that they entered shows up in the database that means that their account is valid and once it's valid we're going to check if the password that they entered is correct or not if the password is correct then we're going to log them in and redirect them to a user so now that i've explained how our login authentication system is going to be built and how it's going to work we can start creating the database so to do this i'm going to create a new file called database.tp and this is our database so in order to connect to it we're going to need sql alchemy and when we installed our packages this is one of the packages that we installed so i'm going to do from flask underscore sql alchemy right here import sql alchemy and then right underneath this app right here i'm going to create the database instance so i'm going to do db is equal to sql alchemy and then pass an app next um we need to connect to this database file so to do that i'm just going to do app.config and then sql give me for a database underscore uri is going to be equal to sqlite colon and then three forward slashes so one two three database dot db so this line right here creates the database instance and this line right here connects our app file to now that we have linked our app to our database we can move on to creating database tables but first we need to add a secret key to our app and the secret key is used to secure the session cookie so right under here i'm just going to put i'm just going to type in app.config secret key so secret underscore key and then in a production environment or if you were to deploy this um this would have to be something secretive but for the simplicity of this tutorial i'm just going to put this to something simple like this is a secret key next we're going to import user mixin from flashlockin and flashlogin is one of the packages that we installed at the package installation step so i'm going to type in from flask underscore login import user mixin and now we're ready to create our table so to create our table i'll just write the code down and then i'll explain afterwards so that i can avoid any sort of confusion so this right here what i've highlighted will be the table for our database and we're going to have three columns the id column is the identity column for the user the user the username is the user's name and db.string20 means that the username will have a maximum of 20 characters and the nullable equals to false basically means that whenever we're registering this field has to be entered in and cannot be empty and the same thing goes for password the only difference is that um the password has a maximum of 80 characters once it's been hashed so we have created our table um in our app and now we just need to add these changes to our database file so to do that you're just going to open up your terminal using control backtick and then you're going to type in python or python 3 depending on your system and then you're going to do from app import db so what this is going to do is import this db variable from our app file right here app.pi and then i'm going to hit enter and then you're just going to type in db.create underscore all and this is going to create i'll create all the tables that we have in our app file into our database and then to exit out of the console you can do control d or exit and then set a parenthesis next to see if the changes have been applied or not you're just going to use sqlite3 database.db and then you're going to type in tables so dot tables and then if you see user then that means that our table has been successfully created and we're done with the database creation part and to exit out of this database search you can do dot exit so now we're done with the database table creation part um in the next clip i'll show you guys how to create the forms for registration and oh and also one thing that i forgot to mention um the username we're going to put unique is equal equal to true okay so unique is equal to true and what this means is that um there cannot be two or more of the same user names so each person will have a different username all right that's what unique is equal to true means so now that we are done with um creating databases tables and that we've linked it to our app as well as added this unique is equal to true we can start working on flask forms so i'm going to import um a few things so i'm going to import from flask underscore wtf import wtforms and then from wtforms import string field password field and submit field and then i'm going to import from from wtforms.validators import input required length and validation error okay and i'm just going to paste some code in for the form and then i'll explain what it does in a bit so right here as you can see we've created this registration form and this will inherit from the flask form and i'm just going to space this out so that you can see better so right here the username is basically where we're going to be entering our username um it's going to be a string field meaning that we can view the characters and then the validators is equal to input required basically means that this has to be filled out the length we have a minimum of four characters for our username and then a maximum of 20 and then the placeholder basically is a placeholder for the username um and you use that with the render underscore kw right there and the same thing goes for password the differences are that the instead of using stringfield it's going to be a password field so whenever we enter in our password it's going to be a bunch of black dots and then the same thing for validators it has it has to be filled out and then the minimum length for a password is 4 and then the maximum is 20. now i know there in our database we have it set to 80 but that's but um when we enter in our password uh whenever we register the password it first gets the original password and then hashes it so we don't know how long the hash is going to be so that's why we just have it set to 80 in the database but the maximum amount of characters we can enter in for our password is 20 and then we have the same placeholder right there and it says password and then this submit is basically the button to register and the button will have register written on it so that's it for our register form there's also one more thing that we need to add and that's this so i'm just going to type it out and then i'll explain to you guys in a bit so earlier i stated that unique is equal to true basically means that there can't be two or more usernames that are the same and that basically means that each username has to be different and we have that set in the database but uh what about the form so i'm just going to type a few things and then i'll explain to you guys what it does and how it's going to distinguish whether or not that username already exists or not so yeah so this is the method that we've written so what this does is basically validates or not whether there's been a username that's already similar to the one that we typed in okay so what it's going to do is query the database right here so uh this variable existing user username what it's going to do is query this database table by the username and checks if there is a similar username to what we entered in this right here and then if there is one then it's going to raise a validation error stating that that username already exists and you need to choose a different one so that's pretty much it for our register form so what this basically does it has the form itself right here and then um checks whether or not uh the username that we entered already exists or not and if it does then it's going to erase this error right here okay and now we can move on to creating our login form which is basically the same thing except we change a few of the words so i'm just going to copy this and then paste it down below and then instead of putting register form i'm just going to put login form and right here it's going to say login and that's it so we're going to be logging in using our username and then by typing our password and in the next clip i'll show you guys how to add this into our html pages so now we can start um adding our forms to our html and then once we're done with adding them to our html we can start registering and logging in users so but first i'm going to fix this silly mistake that i made so right here where it says from flask import wtforms instead of importing wtforms we're going to import flash form okay and then i'm going to start up my app so python3 app.pi and then i'm just going to go into chrome and then type in localhost 5000 right here and i'm just going to go into the login page for now and we're just going to add these forms so to do this this is fairly simple um i'm going to actually add methods here too so methods is equal to get and post it's going to be the same thing in register 2 so i'll put that there all right so now we can start so for login i'm going to create a variable called form and this form variable equal to login form and i'm going to do the same thing for register except for register we're going to have register form okay [Music] and now i'm just going to pass this form into our html template and to do that i'm just going to do form is equal to form so i'm creating this form variable in our html template and that form variable will be equal to this form which is this right here okay and i'm going to do the same thing in register 2. so put that there and then inside of here i'm just going to create a normal form so form method post action i'm just going to leave that empty for now and then form dot hidden underscore tag and then form.username form.password form dot submit so what this means right here form.username it's basically going to get this right here and then for the password it's going to get this and then for submit it's going to get that and it's the same thing in registrar so i'm just going to copy this over and then put it into register right here and then i'm going to re i'm going to refresh this page so once i refresh it you can see that the form pops up and then if i go into the register page it's going to have the same thing there too and yeah so we have our form working now the final step is to register users login users and so now that our forms are um available for us to view in html we can finally start working on the registration feature so to do this i'm going to first import bcrypt and we're going to be using bcrypt to hash our passwords so i'm going to do from flask underscore bcrypt import bcrypt and then i'll just do bcrypt it's equal to bcrypt then app all right and now i'm just going to write down the code for registration and then i'll explain what it does in a bit [Music] okay so what i've done here is basically uh whenever the form validates meaning that whenever we submit this form we're going to immediately create a hashed version of this password so um right now if i were to just type this in and not have this line right here it would just have this password enter entered in as plain text but we need to hash it in order for it to be encrypted and so that our registration process is secure so we're first going to hash the password and then we're going to create a new user once it's been hacked and the username for that new user will be the username that we enter in right here and the password will be this hash password and then once we've created that new user we're going to add them to the database and then commit those changes and once you commit them we're actually going to redirect them to the login page and to redirect them i'm just going to import redirect which i've imported right here and then i'll just do return redirect url for login okay and then right here i'm just gonna um have my username and then a password entered in and then i'm just gonna press register as you can see it redirected me to the login page and now we can check whether or not um this user is also in the database or exists in the database so i'll just open up a new terminal and then do sqlite3 database.db and then i'm just going to do select all from user with the asterisk and then a semicolon at the end and right here as you can see the account that i created has been added so the username and then the id and then this is our password so this is what i mean when it's hashed right here so our registration is done now we need to implement logging in logging out and creating a user dashboard and that'll and once we finish that we're done with this app so to get started with login we're going to first import login underscore user login manager login required log out user and current user okay and then i'll just paste some code right here and i'll explain to you what it does so this login manager part right here this is basically going to allow our app and flash login to work together to handle things when logging in loading users from ids etc okay and this load user callback this uh well this user loaded callback is used to reload the user object from the user id stored in the session okay so with that being said we can start working on the login part all right so to do this i'm just going to do if form dot validate on submit well actually before we do this we need to create the dashboard so um in here i'm just going to create a template called dashboard.html and i'm just going to have basic stuff right here i'm just going to put dashboard has a title and then i'm just gonna put hello you are logged in okay and then i'm just gonna create a route for it so at app.route slash dashboard methods i'm just going to copy this define dashboard and then we're just going to return that template all right so we have the dashboard created and we only access the dashboard if we're logged in so i'm just going to put this login required all right and now we can start working on the login form so if form dot validate on submit um we're going to first query the user to check if they exist so user is going to be equal to dot user.query.filter by username and that username it will be the form.username.data not first and this is basically used to check if the user is in the database or not and if they are then we're going to check their password hash so if uh bcrypt dot check password hash and um the bcrypt is basically going to check the user's password and compare that to the form.password.data and to see if they match all right and if they match then we're going to be logging in that user so login user and then return redirect to url for dashboard okay and you'll understand this once um this works all right so i'll just refresh this page and then i'm gonna log in so when i press logged in it says uh hello you are logged in so how this works is whenever we press the submit button it first um queried our queried us to check if we were registered or not by our username that we entered and then if we were registered then it checked our password and it compared our password that's stored in the database to the password that we entered in and if those passwords matched then it logged us in and redirected us to this dashboard right here okay and now we just need to build the logout feature so to build log out it's actually very simple we're going to do app.route and slash log out methods is equal to get and post and i'm going to have login required because in order to log out you have to be logged in so define log out and i'm just going to log out user and then return redirect url for login okay so if i go to slash logout it logged me out all right and i'm just going to add this logout link to the dashboard so i'll just put a href url for log out and then press here to log oh all right so let's log back in and then it brought me into the dashboard and then if i press this it's gonna log me out so that basically sums up this video um i hope that you guys learned something from it um and just to test our app to make sure everything's working or not let's try it again so if i go into sign up i'm just going to put well first let's test out this validation feature so this username already exists if i press register it should lead me to the login screen but if it already exists it's not going to okay so it's not letting me but if i were to put a username like one two three four five six at the end or whatever then i press register and then i put that same username right here and then press login you can see it logs me in so our app is working um if you have any questions comments or concerns or anything you'd like to ask me please feel free to leave them down down in the comments below email me or dm me on instagram and i'll try my best to reply to you thanks for watching
Info
Channel: Arpan Neupane
Views: 9,868
Rating: 4.9016395 out of 5
Keywords: flask, web development, programming, python, coding, python3, login and register, login and signup, flask authentication, flask login, coding with python, flask easy, easy programming, flask tutorial, python tutorial, python3 tutorial, how to learn flask, how to learn python, how to add authentication, how to add login to flask, how to add login system in python, sql, coding videos, programming tutorials, python programming, flask development, how to code
Id: 71EU8gnZqZQ
Channel Id: undefined
Length: 29min 35sec (1775 seconds)
Published: Fri Mar 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.