JWT Authentication System in Django and React.js Full Stack Application | Complete Project Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we will create a full stack application that provides user authentication functionality using Json web tokens or JWT with Jango rest framework on the back end and react on the front end we will learn how to create restful apis to handle user registration login log out user information retrieval and token refreshing and then we will learn how to consume our API end points by making a HTTP requests using axius in our front end application this is going to be so much fun and informative and really really packed so grab a cup of coffee and let's get started all right so let's create a project directory where our project will live let's call it Jango react fun and let's open it in Visual Studio code all right and now we're going to create two directories one for the back end we'll call it back end and another for our front end and we will call it front end all right and now let's fire up terminal and we are going to start working on the back end so let's CD back end all right so now that we are in the backend directory we want to create a python environment I'm going to create a v environment but you are welcome to create any environment you like okay so pi- m v and I'll call my environment V and hit enter and wait a second all right looks like it was created for me okay now let's activate it V scripts activate Crypts activate all right so now that we have our Vin ready let's install Jango so pip install Jingo with a capital D and we hit enter and now we got to wait a bit right as we wait I would like to ask you to subscribe if you're enjoying this content and you could hit the like button as well that would be very cool thank you all right and now let's start a Jango project so Jango dadmin do project and let's call the project backend and we could actually create it in this directory to do this we can add period and hit enter right now we got to wait some more okay um now we have our project created for us let's try it out so Pi manage. pyun server okay let's follow link Tada it worked successfully congratulations to us all right so now let's create our application we're going to use manage.py so Pi manage.py start app and let's call our app accounts now let's hit enter and here's our app now let's go to settings.py and and add it to our installed apps I'll just write accounts and now would be a good time to go to models.py and start defining some models we want to start by defining our user model it's going to be customized so let's call it custom user and it's going to inherit from jango's abstract user so I'm going to copy the import statement from the docs and paste it right and then we want to pass in abstract user here the abstract user comes with all the functionalities in field of the default user class and according to the dogs it is highly recommended to set up custom user model even if the default user model is sufficient for you because it behaves identically to the default user but you'll be able to customize your user model in the future if the need arises however in our case we want to customize our user class we want to allow users to sign in with their email to do this we could use username field attribute and set it to email all right now since we'll be using email to sign in it's important that we set the email field to unique so no two users have the same email address so models. email field and we want to set unique to true all right another thing we want to do is we want to add another required field when users are creating an account and this should be the username field we want users to write their username and email when they create an account all right now let's define string method and we want to return self. email all right next up we want to go to our settings.py and we want to tell Jango about our custom user model so in order to do this we want to add this line oath user model and we want to set it to our user model so in this case it is accounts CU that's the name of our app right and then our model is called custom user so counts. custom user all right now let's make migrations so Pi manage.py migrations right and now let's run migrations so Pi manage. Pi myig great right let's hit enter all right so in order to be able to use our custom user model we should create a user creation form so let's create a new file and call it forms.py and that's where we're going to have our forms so we're going to define a Custom Creation form so I'm just going to copy this line so I can import it and we're going to need to also import our custom user from Models so from Models import custom user right and now let's define our user creation form actually let's call it custom user creation form all right and now let's add class mattera like so and our model is the custom user model and Fields email all right now another form that we could Define that would be handy is the user change form which is used in the admin interface to change a user's information and permission so it will help us update our users's information through the admin so let's define it let's call it custom user change form and we want to import us your change form and pass it in all right and now we want to Define class meta and pass in our model which we'll set custom user and also specify the fields and we want to set it to email oh I forgot to add a comma here and also I should add a comma here CU Fields should be a topple okay that should do it now since we know that we want to be using jango's admin site let's create a super user to be able to log into the admin so Pi manage.py create super user and hit enter uh let's give our super user an email I'm going to just input a fake email and a username and a password all right okay now let's run server so Pi manage.py run server all right and now let's try to see if we can log into our admin site let's type in the email and the password okay and our admin site is pretty much empty so let's change that uh so let's go to our admin.py right and what we want to do now is register our custom user model so let's import it from Models import custom user okay and we also want to register our forms right so uh from forms import custom user change form and custom user creation form and now let's create class custom admin user and we will want to extend jango's user admin so I'm just going to copy the import statement from the docs and paste it and then pass it in and next we want to add our user creation form so we'll use ad form to do this and we'll set it to our custom user creation form and for the form we've made for changing users info we will use form and set it to custom user change form and then we want to set our model to custom user and to register our class we can use a decorator we use admin do register custom user all right now let's go back to our admin site and refresh and we have accounts and users within it okay let's click on it and this is the super user account I created ear earlier let's click on it and we can change the username first name last name email uh status and permissions and over here we have last login and they joined so pretty cool right all right so now let's go to settings.py again and let's talk authentication by default Jingo offers us pretty awesome session based authentication but today we would like to use JWT authentication so let's install Jango rest framework okay so pip install Jango rest framework right let's hit enter okay and now we are going to need to go back up to installed apps and add rest framework just copied it from the DOT box and now I'll just paste it all right and to quickly easily and securely Implement Json web token authentication we're going to make use of Jango rest framework simple JWT all right so let's install it as usual I'll just copy the command from the docs and paste it hit enter all right and then we want to tell rest framework about the authentication we want to use all right so in our settings.py let's add rest underscore framework and we want our default authentication class to be rest framework simple JWT all right I think this should do it all right now back to the docs and let's go to settings and we want to copy this part which is our simple JWT configuration which would allow us to customize aspects and settings of our JWT of course we also need to import uh date and time so just copy the import statement and paste it right and now let's go back and and look at our our simple JWT configuration okay so our signing key is set to Jango secret key which of course in production should be kept a secret all right and in order to increase security we want to set rotate refresh token to true this will make it that every time a token is refreshed a new one is created and we also want to set black list just after rotation to true as well and this would make it so that the token that was there before rotation is blacklisted and since we set Blacklist after rotation to true we are going to need to add this to the installed apps which is uh the simple JWT token Blacklist all right and now let's apply migrations so Pi Pi rate all right now we need to create a new file and we'll call it serializers.py that's where we're going to be creating our serializers based on our custom user model so let's go ahead and import it so from Models import custom user and from Jango rest we will be using the model serializer class which will automatically generate a set of fields for US based on our model all right so let's go ahead and import serializers from Jango rest right and let's start defining our custom user serializer that will inherit from serializers do model serializer all right and now let's add class meta and specify our model custom user and now let's add in the fields that we want to have ID username and email all right now let's define user registration serializer that is going to be responsible for serializing registration requests and creating new users in our application it will also inherit from drf's model serializer all right so let's define class meta and just like we've done over here let's add in our model and the field we want right so let's also add ID username email and for registration each user would want to make a password so let's add in password but I would also like to add extra security by having password verification so let's add password one and password two okay and now we're going to need to Define password one and password two so password one it's going to be a character field so let's set it to serializers do shorefield and we want to set right only to true this would make it so that password one is for input only and it will not be included in the serialized output let's also do the exact same thing for password to so I just copied and paste it and to make sure that our password field is right only let's add extra quarks takes a dictionary so just make password and set to write only true all right and now let's create the method validate to validate our password we want to make sure that password one and password two are the same before creating the user all right so let's add an if statement I'm want to say if password one is not equal to password two then we want to raise a validation error maybe have it say passwords do not match all right and we want to return our attributes okay now another way to make our passwords more secure is to add some rules for example we could make it so that users cannot have passwords that are shorter than a digits all right so let's get a hold of our password P.G password one all right and then let's add another if statement if length password is less than eight want to raise an error so raise serializers validation error passwords must be at least eight characters all right and now finally let's define the create method so self and validated data all right and now let's get a hold of our password B validated data. pop password one next we want to just Discord password two so validated data. pop password to all right now let's write our return statement we want to create our user so custom user Doob do create user and I want to set password to password and then we want to just pass in the rest of the validated data all right so we have defined our custom user serializer and our user registration serializer oh this should be a Boolean not a St I think sorry about that please if you've been following along please make sure to correct it and remove the quotation marks if you've put any all right and oh I've actually meant to call this file serializers not serializer so I'm going to rename it before proceeding all right next up we are going to Define our login serializer so class user login serializer and it's going to inherit from serializers do serializer and our users will input an email so let's add an email field so serializers do chore field and then they will input their password so let's also add a password field it's also going to be a character field but let's set write only to true all right now let's define uh the validate method and in order to authenticate our users we are going to need to import authenticate from Jango do contri do oath all right and we want to authenticate our user so user authenticate and we'll pass in our users data oh I misspelled data here okay excellent now let's add an if statement so oh we want to check if user and user is active then we'll be returning user else we want to raise an error so serializers dot validation error and we could say incorrect credentials or something all right awesome awesome I think those serializers should work work so now it's time to go to views.py and create our views here right so the first view we'll be creating is the registration view all right so how about we call it user registration API view right and it's going to inherit from drf's generic API views so let's import it so from rest framework dot generics import Eric API view right let's pass it in so since this is a view for users to register then we want anyone to be able to access it so let's set permission classes to allow any and to use allow any we are going to need to import it so from rest underscore framework do permissions import allow any all right and now we want to point to our serializer class so let's import our serializers so from serializers import all of them okay so our serializer class for res registration was called user registration serializer all right now let's define our post method so it would be post self request and let's also add arcs quarks all right now let's get our serializer so self do get serializer and data would be request data okay next we want to make sure that the data is valid so serializer is valid and if it's not we want to raise exceptions so let's set raise exception to true all right and then let's set user to serializer Dove and token to refresh token for user and we're going to need to import refresh token from simple JWT so from rest framework simple JWT do tokens import refresh token all right and now let's set data to serializer do data and then data tokens refresh string token and our access token B string token dot access token and finally we want to return response which we're going to need to import so let's import it [Music] from rest framework do response okay and within our response we want to pass in the data and Status tatus oh we also need to import status also from rest framework import status okay so status do let's say 2011 created all right now let's define our log in API views it's also going to inherit from generic API View and just like with our user registration API view we want to set permission classes to allow any right and we want to set our serializer class as well we call it user login serializer all right and now let's define our post method take self request and AR quarks all right now now let's get a hold of our serializer uh be self. get serializer and data also be request. data excellent all right and now we want to check if our serializer data is valid so it's valid and if it's not we want want to raise an exception so I'll set raise exception to true all right and now let's set user to serializer do validated data and then we want to create an instance of our custom user serializer using the validated data so custom user serializer and we'll pass in our user okay and now let's set our token we want to refresh token for our user okay and then let's set data to serializer do dat and our tokens to refresh to the new token we've created and the access token to token. access token all right and finally let's write our return statement we return response pass in our data and send a status uh with code 200 okay all right all right now let's quickly Define the log out view so our users can log out so call it user logout API View and also inherit from generic API View and our permission classes would be is authenticated CU only logged in users should be able to log out so is then oh I need to import it as well all right so is authenticated okay and now let's define our post method so post post selfquest and Mar quarks okay now we want to try uh to get of our refresh token so request. data refresh okay and then we want to set our token to refresh token refresh token okay and then we want to Blacklist that token so token Blacklist and finally we want to return response and we want to pass in status 205 which is reset content and let's add our accept block so accept exception as e and we want to return response status going to set our status to 400 bad request awesome so now that we have our views let's set our URLs so first let's go to our backend directory our project directory we want to go to urls.py and we want to import include so that we can include our accounts app URLs and we want to add to the URLs patterns um right so let's add API and we want to include our accounts do URLs all right okay now let's go to our accounts directory again and we want to create uh urls.py file and we want to import path so from Jango URLs import path and we want to import our views so from news import all of them okay and now let's create our URL patterns list and have our path first one we want is register our register end point okay and our view is user registration API View and you want to have it be as view right and let's give it the name register user okay next uh login login and then Dash and our view was user login API view once again we want to add it as View and let's give it the name login user all right and then we want font path log out right and log out API View and just like we've done earlier it as View and let's give it the name log out user all right and finally we want to create an end point for our token so let's create path token SL refresh all right and we want to import token refresh view from rest framework simple JWT do views import token refresh View and then we'll add it here I also have it be as View and give it the name token refresh all right now let's run server and check our end points all right looks like in addition to our admin endpoint we have the API endpoint so let's follow it yes and we have the register login log out and token all right let's try register oh there it is it looks good so we could actually use it right now to create a user if we want however uh we're going to be creating a user anyways after we create a react app so let's try it then okay now let's check on our other end points let's check on our log and endpoint okay here it is okay let's check our log out right there it is awesome and now token refresh all right now since we want to be able to log in and log out users from our front end which we have not yet created we're going to need to install Jango course headers which will allow us to make requests to our Jango app from a different Origins so I'll just go to piie and copy uh the install command and I'm going to paste it and hit enter all right and now we've installed Jango course okay cool all right and now we will need to add course headers to our installed app in um settings.py so let's do that right and we're also going to need to add a course headers middleware to our middleware as well as Jango middleware common common middleware so I'm I'm just going copying this from the docs on piie and I'm going to paste it here all right and then I'm going to configure the middle we's behavior in the Jango settings just like the docs say and I'm going to be setting a course allow all Origins to true although This is highly not recommended for production because it's a security Hazard so be careful with that for now we'll just set it to True okay all right so now we could start creating our front end application so I'm going to open a new terminal and I'll CD into front end and I would like to create um my react app with v so I'm going to type in the command npm create V at latest and since I want my project to be created in this directory in the front end directory that we're in right now I'm going to add in a period and I'll hit enter all right and we want to create a react app so I'm selecting react and we want to use JavaScript right so I'm going to follow these commands so type in npmi because typing eyes faster than install I hit enter all right and now we want to run Dev so npm run Dev all right let's follow the link here's our V react app Woohoo all right all right super cool now let's go to our source directory and let's create a new folder and call it pages and we want to create a login page so call this file login. jsx uh a register page so I'll call it register. jsx and a home page so I'll call this file home. jsx and and also let's create layout do jsx all right um and now let's go to our homepage and create a functional component and let's do the same for all the others by the way I'm able to use RFC and hit enter and create uh the react component super quickly because of a plugin I have uh I will leave the name of the plugin in the video description in case you are interested all right so since we're going to want to be able to navigate between our Pages let's quickly install react router Dom so I'll just copy the command terminate server and then paste it hit enter all right so now we have react router Dom which is great all right so now let's go to our app.jsx and let's clean it up I'm going to remove all the import statements except for the app. CSX uh CSS and I'll move this and everything within the return statement all right and then I would like to import browser router from react router so I'll just copy the import statement and paste it and I'll also be importing routes and Route because we'll be also using them so routes route all right and now let's store using browser route router like so and within it will have our routes all right and let's import the page components that we've created so I'll do it quickly import layout import register and import login all right now let's add route path slash and the element we want to pass into this is our layout element okay and then we want to add route again this one will be the index and the element is going to be our home element right and next we want to add another route and this route would be the route with path log in and our element would be our login element and then we want to add another route with the path register and the element will be our register element all right and now if we run Dev Al so npm run Dev we will see our progress oh okay so we see uh our layout page so let's go to it all right now we want to import outlet and Link from react router Dom and we'll be creating some sort of super simple nav system so let's add a nav element let's add here an unordered list and have our first element be a link that links to home all right and then I'm just going to copy this part and paste it again two more times in the second part we want to link to log in so we'll have it say login and here we want to link to register so we'll have it say register maybe make it capital r all right now let's see what happens when we click on login okay so we were redirected to login but we we don't see our login page actually all we see is our layout element okay and that's where we want to use our Outlet so we here let's add Outlet cool all right so if we click on home we see home if we click on login we see login if we click on register we see register nice all right awesome so now that we have set up our routing how about we start making our register page work as well as our login page all right now let's go to our register. jsx and let's start adding some registration logic so of course we would like to be able to get inputed username email password and password too so let's begin by creating form data and set form data and we'll be using reacts Ed States so let's import it all right and we'll keep our form data in an object so first we'll have username and then email password one then password two all right so like we said we will be creating a form so let's create a form element and our form is going to have fields for our username email password one and password two which we can call confirm password all right and now let's give our Fields the appropriate types names and so on so our input field for the username should be type text and we should give it the name username and its value should be set to form data do username all right email type would be email name email and a value form data dot email password the type should be password name password one value form data. password one confirm password we'll also get the type password name password to the value for data dot password to okay awesome and now to make sure that our forign data gets updated when our user inputs anything then we should create an event handling function we can call it const handle change that we would want to trigger on change so for every input field we're going to add on change and we'll pass in our function handle change so I'm just going to add it to every input field all right so now if we try to type into our input fields we won't be able to input anything because we have set the value to our form data value and the values are set to an empty string so we literally can't input anything right now right so let's add logic to our handle change and that would allow us to input and also would make it so that our form data object is updated as we input or as our user inputs in our input Fields okay so we want want to set form data right so form data and we will be dynamically updating our form data so we want to get a hold of our Fields name and the value like so right and that's it okay okay now when we try to type we should be able to type yes awesome all right now if we want to see if our form data gets updated we can add console log form data okay all right and now I'm going to try to type something I'll type PCO all right type PCO email right so as you can see as I'm typing the form data is getting updated right cool so you probably have noticed that our form is missing a submit button so let's add it all right so let's add the button element and we'll give it the type submit and we'll have it say register all right we could also add another break here okay that looks better all right so of course the purpose of this button is to submit our users registration form so so we'll be making an event handler called Handle Sub submit to handle submitting our form and it's going to be an async function and we're going to get to it in a second um but before we do that I want to also add disabled here and set it to is loading because we don't want our users to be able to spam the submit button and just keep sending requests we want to make sure that our button is disabled when the form submission is still taking place so let's create const is loading and set is loading and set it to use State false all right so I guess the time has come to write in the logic for our handle submit and attempt to make a post request to our back end with our user registration data uh so to do this to make HTTP requests there are so many options and one of them is the fetch API uh but for this project I feel like axus would be advantageous because of how it handles Json and a bunch of other things so I will be using axus to make requests to my back end and in order to use it I'm going to need to download it so let's fire up terminal again and I'm going to terminate batch job disconnect server a come on yes right and to install axus I'll type in the command npm install axus and hit enter all right and now I have axis so I can go ahead and import it so import axus from axus all right all right now let's go back to our handle submit method and we want to prevent default and then check if is loading because we want to prevent form submission if is loading is already true right so we'll add in return like so and then we want if it's not true then we want to set is loading to true to indicate that form submission is in progress and we don't want to allow users to keep sending more forms or trying to submit more forms okay and then we want to try to send a post request to our register endpoint so let's create const response you want to await axus poost then we want to make a request to our register end point so I'll just copy the URL that leads to our register endpoint in our back end and and I'll just paste it here and then pass in the form data all right and if all goes as planned then we would like to know that so let's add console log let's write success and then pass in response data okay and now let's add all the catch block right and we want to catch if there's an error and we want to know what this error is if it's EX exist so console log and say error during registration error response data all right and now in order for handle submit to work let's add on click event listener to our button and pass and handle submit all right so now our form should work and we should be able to register users with it so let's run server again so npm run Dev okay and let's try to create a new user let's make the username test email test test.com password test 1 2 3 4 and test one two three four right let's hit enter and now let's go to our admin page and oh here's our test user it was created for us that is super cool awesome right and if we inspect and check our console we see the success message Yay oh actually let's um delete all the console log form data over here all right um all right so another thing that would be cool if we could tell our users if they succeeded in creating an account or not and it would also be nice to show them if there are errors so let's create const success message and set success message and let's initiate it to use State null and let's also create const error and set error and also initiate it to use State null now let's go back to the triy Block in our handle submit function and let's add set success message to registration successful all right and now if there's an error then we also want to tell our users so let's add if statement if error response and error response response. data then object do Keys error do response. data for each field const error message we want to set it to error do response data field then if error messages actually let's call this error messages instead of error message and and error messages do length is greater than zero then we want to set error to error messages zero all right and now um let's scroll down and let's add our error and success messages to our UI all right so if there is an error then we want to show a paragraph element that shows that error okay let's see if it would work so I'm going to try and create another user named Pico we already know that we have a username Pico already and there shouldn't be two users with the same name and let's make it have the email test to email.com and let's give it also an invalid password we've decided that passwords has to be at least eight characters in length okay let's try to hit register okay and we see the error a user with that username already exists I think it would be cooler if we make our error red so let's add style and make the color red okay I think now if we have an error it would be red let's try to create another user and give it the username test two and the email test2 email.com and let's give it an invalid password it's only for characters and then let's hit enter oh here's our error and it is red just like we wanted oh I've just noticed that our register button is still disabled and that's because I forget to enable it again so after our catch block we could add a finally block and we could set is loading to false again right and now I think that register button is going to stop being disabled we're going to test it but let's now add our success message so if we had a if we have a success message then we also want a paragraph element with the success message to show and we want to have our success text have the color green okay so let's try uh let's see if we could create a user with the username Test 2 and the email Test 2 at email.com and the password test one 2 3 4 test one two 3 4 okay let's hit register yay here is our success message cool all right now let's check if we've created this user so I'm going to refresh yay here it is we did it all right this is very cool now I think we can create the logic for our logging in as well because right now our login page is empty all right so our login. jsx is going to have so much in common with our register. jsx so I'm just going to open our register to the right and copy some stuff from it to save time first thing I'm copying is the axis import statement because we're also going to be using Aus here and just like we've done over here in register. jsx we'll also be using reacts use state to set our form data so I'll also be creating const form data and set form data be setting it to use State as well however when users are logging in they will be logging in with their email and their password all right and now let's quickly create our form just like we've done in the register. jsx I'm just going to copy the whole thing and then I will edit it so we'll also have a success message that we'd like to show but instead of having this say register you could have it say login and we will not need a user name field so I'll delete this and I'll delete everything below it other than the password field and the submit button of course but instead of register let's have it say login and instead of having this be called password one let's just have it say password and uh its value would be form data. password okay and our login form doesn't show because we have variables that we have not yet added uh so let's let's do let's add them okay so for starters let's add the handle change function because in our login it will be exactly the same this logic would work just fine we want to also add is loading and this part where where we have the success message and the uh error message we're also going to need a handle subnet function so I'm just going to copy the whole thing just paste it like so but instead of having it make a post request to register we want it to make a post request to our login endp point and instead of it saying registration successful we wanted to say login successful and instead of error during registration error during login right now here's our login page okay you know what I'm going to add another break right here all right so it definitely looks better uh however we are not done because um when our user logs in we need to persist the login and we need to save the access token and the refresh token so let's go back to our Tri block and and let's add local storage do set item and we want to set our access token [Music] to response data. tokens do access and we also want to set local storage. set item refresh token and then response. data. tokens do refresh all right now we can try to actually log in we've created user with a username test and we've created a user with a username test too so let's try logging in with test the the email for test was test test.com all right so test test.com the password was test one two 3 4 right we logged in login successful cool all right now let's try to log in within incorrect credentials okay it says incorrect credentials nice we did it all right very cool now I think it would be very nice if on our homepage we would have a message for our logged in users that says hi and then their username then thanks for logging in if they are logged in and if they're not logged in then I would like to show them the message please log in right so let's import use state from react and initialize mon username and set username to use State and then empty string oh over here I write wrote username instead of username all right and we're also going to want to keep track of whether the user is logged in or not so set log loed in and you want to initialize it to use State false okay and then we want to conditionally render this based on whether the user is logged in or not so is logged in then and we would want to render hi username thanks for logging in and otherwise you want to show please log in all right and to actually check if if our user is logged in or not we are going to need to make a get request to our back end so let's import axus and we're also going to import use effect from react all right and now let's use our use effect hook and we'll leave the dependency array empty because we will want it to run once when our component mounts and now let's define a function within our user effect hook to check if a user is logged in let's call it check logged in user and it's going to be an async function and we'll have a try catch blocks within it in our triy block we want to try and retrieve token from local storage so that's great cons token and local storage. getet item access token all right now if our token exists then we will want to make a get request to our back end to see if the token is valid and the user is authenticated and also to see if we could obtain information about the user like the user's username for example now there is only one problem we have not created such an end point but it's actually very easy to do so let's just do it now uh so uh let's go to our views.py and we want to import retrieve API view because we will be using it to Define our user API view will inherit from retrieve API view actually let's call it user info a API view okay and let's set permission classes to is authenticated that way if we make a get request to it and we're not authenticated it will return a forbidden error and let's set serializer class to custom user serializer right and to make sure that our view only returns information related to the authenticated user uh let's overwrite the get object method and return self do request. user all right and now in order to be able to access it let's go to your el.pie and let's add a path that links to path users actually user and then our API view is user info API view we want it as view let's make the name user info all right and now let's go to our API end points and see if it were added yes it is it's here here okay let's go to API SL user there it is our user info API it accepts get requests cool nice all right so let's go back to our home. jsx and continue all right so we said that if token then we would want to make a get request so let's create const config where we're going going to keep our headers so we can authenticate our get request or send in our token so we'll have authorization error token okay and now let's try to make our get request so const response we'll set it to await a.get and our end point is API SL users I'll just copy it and paste it and we want to pass in config okay now if the request is successful then we want to set is logged in to true and we want to set username to response data dot username else we want to set logged in to false and we want to set username to an empty string and in the catch block you want to add error and also set logged in to false and username to an empty string right and finally we want to call our function so check logged in user okay so now let's see if it works okay so it still says please log in so let's go to log in and let's try to log in with test test.com and the password test 1 2 3 4 okay it says login successful so let's go to home oh yeah it says hi test thanks for logging in this is super cool all right now um you guys remember we created an endpoint for logging out so let's define a function and call it handle log out and our handle logout function is going to be an async function CU we'll also be making a post request it's going to also have a tri patch block and in the tri block we're going to also try to get a hold of our tokens but here we'll try to get our refresh tokens so const refresh token local storage. get item and we want to get the refresh token all right if we find a refresh token and we want to make a post request so I wait Aus dopost and we'll be making a post to our logout end point so it was API SL logout right let's double check yep okay just copy it and paste it and we want to send our refresh token so refresh and refresh token then we want to remove our tokens from our local storage so local storage. remove item access token and then local storage. remove item refresh token and then we want to set logged in to false and set username to an empty string all right and if there is an error then we want to console log [Music] failed to log out all right and now let's add a button and have it say log out oh I need to add a div or react fragment just add a fragment okay and on click we want to handle log out all right so now let's test it of course okay but before we test it I want to show you something kind of cool in the admin that I haven't shown you earlier I think although it's been here for a while you see over here we have token Blacklist and if we check the Blacklist tokens it is currently empty all right so let's have it to the side right here and let's log in as test test.com and input our password right and we have logged in okay now let's go to our homepage and it says we're logged in it got our in our username from the back end which is super great okay now let's click on log out and look our token appeared here in blacklisted tokens so our ref fresh token was blacklisted and this is how we know that our logout functionality works we did it I would like to encourage you to play around with the admin check out the outstanding token section see what happens when you log in and play around you know make the code really your own by the way I'm going to create a GitHub repo with a code and I'm going to leave the link in the description in case you want to go through it and you know to help you follow along and stuff if you have any questions suggestions anything at all please type that down in the comments um I really hope you enjoyed the video if you have please hit the thumbs up button and please don't forget to subscribe have a lovely day and see you next time bye oh
Info
Channel: Piko Can Fly
Views: 3,047
Rating: undefined out of 5
Keywords: python, django, fullstack, webdev, javascript, backend, developer, project, beginner, friendly, coding adventure, code with, code along, tutorial, guide, smart, best, coding, coders, programming, API, portfolio project, easy, portfolio, develop, code, js, html, django templating, full-stack, design, admin, database, authentication, user class, admin class, .models, superuser, django project, settings.py, register, templates, webdev explained, login page, react, jet, jwt
Id: 1pIrRTxGnJ4
Channel Id: undefined
Length: 85min 55sec (5155 seconds)
Published: Tue Apr 16 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.