Django and React Tutorial // 3 - Authenticate Users with React and Django

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so in the last video I said that we were going to add Redux to this application that involved react and Jenga and while diving into that I kind of realized that we could take it one step further and instead of just adding Redux we're going to actually add orth indication to the project so what you can see here is that there's this login button and that's what's been added to the application so I'm just demoing it to you right now and if we click on login then we get this login form and we can actually change that into the signup form and then actually create a user now I've got inside this incognito browser the actual admin of the application so here you can see everything and if I go to users we only have one user at the moment so let's actually sign up using this form and we'll just put in some dummy data here and if I click signup then it actually put a little bit of a spinner there for probably a few milliseconds and we can see that we now have this logout option and actually we have Redux yet in our Chrome browser to see that we've actually been logged in so we've got all the start and all success and we've got this token that is actually coming from the rest framework so now if I actually just refresh this we've got the user that's now signed up there and I can go to the tokens and see that we have these tokens that were created one for the admin user and one for Matt the user that I just created now so that just shows that the system is working so that was the signup if I log out now and go back to login I can log in to that actual user that I just created now and if I log in we are logged in as well [Music] okay so to get started all you have to do is just go to our github repository for the previous videos which is this DJ react repository so once you get here you'll want to clone this repository and so what you want to do is then just open up a terminal so that you can work in so I've got my directory that I've got my terminal open in and I'm going to start by saying get in it so we've initialize the repository and then we just have to say git clone and we need to get this URL here so we grab that clone into this repository and now that we've got to the repository so if we just list this out we've got that DJ react folder so I'm going to navigate into that and now we can see all the code which is the latest version that I just showed in the demo and so now we just need to navigate to the correct commit so the actual starting files for this video so to do that we just have to say get reset - - hard and then the commit hash so to find the commit hash that you need you just have to go to the commit SIA on the repository and then whichever commit you wanted to start at so this is at the end of the second video code so we click there and we can see the commit is right there so we just have to copy that paste that there and it will move the head to that pot date so now we can actually get rid of the git repository and so on windows it's slightly different I think it's rmdir so remove directory and then get otherwise it should be removed directories that get so one of those two for Mac it would be RM dash RF get so once you execute that that means that it's no longer a git repository and so now we can actually get started with opening us up in Visual Studio code and running the service so I'm going to navigate into the front-end here and we'll go into the Skua folder and we first need to install everything so we say NPM I so install and then we can just run NPM start to run that UI and so there we go we're back at the starting code from the previous video and so now I'm just going to open this up in Visual Studio code okay so I've got it open in Visual Studio code now and just to get our back-end working we're going to navigate into our back-end folder and I'm going to create a virtual environment so we'll just say virtual envy Envy and so now we have that and I'm just going to activate it with sourcing the ebin activates and then I'm going to install the requirements and with that we can then change into our source directory and we'll say python managed supply run server so that's got the back end up now and now if we refresh this we should see some dots that come through and there it is so we don't actually want to start with the back end this time like we did in the previous videos we're going to start with the front end and the reason for that is because the backing is actually really really easy so we'll sort that out at the end but the front end requires quite a lot of stuff so essentially what we want to do is we want to create some kind of back end which will use Django rest framework to get the token for the user that signs up and then store that token in the browser and that token essentially will serve as the users authentication so if there is no token present in the browser then we assume that the that the user is not logged in and if they do have a token then they are logged in so immediately what we can do is we can change this navbar here at the top to just include the links that we'll need so let's do that it's all going to the source folder and we're going to go to our containers into layout and here we've got our menu items so the first one we'll just add here as posts and then we'll add login and we can get rid of that second one there and now we've got our posts and our login me but to actually navigate to these links we need to include the link component which we've already imported from the reactor rooted on packaged and so that will essentially act like an anchor tag that when you click it you it will actually just navigate you to that URL so will that path so we just have to add a link like this and we have to specify the two property which in this case four posts will be slash because that's how we have it currently and then we'll actually just copy this here and we want to add login which will go to slash login bear in mind that we will have to add in some logic over here to add in a third menu item and that item would only be displayed if the user was authenticated or was not a syndicated so right now the users not authenticated so it would show login once we login it must show logout so that's just something to think about there we'll handle soon but for now let's get started with actually implementing react redux so what I'm going to do is create a folder inside our source folder which is our store now inside the store I'm going to create an actions folder and I'm going to create a reducers folder bear with me for just a second and then I'll explain everything that has to do with react redux so inside actions I'm going to create this action types dot JS file and I'm going to create both layers inside actions and inside reducers I'm going to create author J's as well now essentially the store is something that reacted redux users to maintain the state for the entire application and the store is broken up into two parts the actions and the reducers so the action is something that we want to define that takes place so inside our action types we'll define all the types of things that can happen such as logs in logs out that kind of thing the reducer essentially takes the state and returns only a piece of it that you need so that's what these two folders are going to contain the actions is going to contain what actually is the find take place but the reducer is going to actually do it and return the state that you need so it's actually just best to demonstrate this and talk too much so we'll jump into it inside action types I'm going to create a few constant variables here and this is essentially so that you don't have to type strings the whole time so this is more the best practice practices kind of thing so we'll say constant auth start equals to or the start I'm just going to copy that a few times and we're going to change them to have auth success which will be all success and then we'll have author fail and the last one will be auth logout so very simple so those are just the action types so things that can happen that are related to the authentication so that's what we're going to do basically contain you in the store are things related to authentication so that's it for action time so you can close that and inside our author jeaious inside our actions folder we're going to define the methods that will take place on receiving those actions so what I'm going to do is import those actions so I'm going to import star as action types from action types so we basically got access to all of these variables and we're going to create the functions or the methods that will take place on receiving those actions so I'm going to say export constant or start and this function essentially all it does is it returns an object and when working with the actions the objects that we need to return always have to include a type so this type property always has to be included and the type is this action type so a message so we say action types dot fourth start so that essentially is the message that is received when we execute the auth start method and we're going to do the same thing for the other methods so we'll say export constant auth success and in order to have a successful login we're going to take in the token so we say it takes in a token just like that and we return an object now the object contains the type of property as we just said it has to and the type or the message essentially is the auth success method message and then we're also going to include the token and that token is coming in as one of the parameters for the method stick with me if you aren't understanding this just yet you'll understand when all the pieces are connected and will continue with both fail and we'll say that this takes in an error we actually don't need the brackets for that and again it returns an object and this time the type is I'm sure you can guess the pattern now action types dot auth fail and then the error will also pass in and so now we just need to handle what's going to take place when we login when we log out so let's continue and create another function which I'm going to call all login now in order to login we need two parameters and I'm doing this in hindsight of knowing what those parameters are for the Django rest framework but essentially this is something you would figure out by just looking at what the parameters you need once you've set up the backend but it's very intuitive to know that you would need a username and a password so that's what you need to login and essentially what we want to do when we log in is we return a dispatch now dispatch is basically a method a call to action so we say return dispatch this dispatch method will essentially return a dispatch of the auth start method that we just defined yet so it's basically saying tell us that or alert us that the auth start has taken place so basically once the auth login is called we then just say dispatch or start so we're saying our authentication process has started so that will basically just be an alert that we that we can look at and then we'll want to actually log the user into the rest framework so to do that we're just going to say Axios dot post and this Axios package we need to import so we'll just say import taxes from Axios like that we already have that installed as one of the requirements so we want to post these parameters to a URL on our back-end and so we're going to post this to our local host so so 127.0.0.1 port 8000 and then the URL is going to be rest auth login now even if you didn't have this setup yet you could just go and change your back into suit this later so this doing this in hindsight or doing this without even knowing from the beginning is fine because you can change this any time you want so we're going to basically log the user in at that URL and we need to post the details to actually log reuse in so that would be the username so you post a username and we post the password so this is the object that's being passed into the post request or the data that's being posted and once we have posted that we're going to get a response and we can access the response using dot then because this is returning a promise now in the response we're going to get back a key and that is essentially what you what is returned from Django rest framework once you have successfully logged in so it's going to generate the key or give you the key that is already assigned to the user so essentially we just need to grab that key and we'll say response data key and then I'm going to create an expiration date and the expiration date can be whatever you want for your application but let's say we want it to be one hour so we'll say constant expiration date equals to a new date and inside this new date object we need to call new date as well and we need called the get time method from that and then essentially just add on this calculation which is basically adding the time that will give us one hour in the future so that's essentially what this huge long call does so with that you've got the expiration date and then we want to store those variables so the token and the expiration date in the local storage of the browser now this API is available in the browser so we just say local storage dot set item and then it's the key so the key and the values are basically in the dictionary so we'll store the token and the ver the value of the token is this token parameter that we got from the response and then we can do the same concept with the expiration date so we store the expiration date and the value is the expiration date that we just created and so this essentially is the logic that you need to persist the user's session in the application because we can't just store it in the state of the application or with redux because once the application reloads then that dot has gone it's refreshed so we need to store it in something that persists and an example of that is the local storage so once you've actually stored those variables then we just have to dispatch the auth success because we've gotten to this point and in order to dispatch that we need to pass in the token so we just pass the token in like that and now I'm going to actually create a method that will check whether our expiration date has expired so I'm gonna call this the check auth time art method so we'll just say check auth time art and all it takes is an expiration date as the parameter and inside here we return another dispatch and all it does is it sets a timeout so a timeout basically is something that will be executed after a certain amount of time so this will make an anonymous function and the time that we want to wait until executing what's inside these curly braces is the actual expiration time so here I'm going to say expiration time and actually we can change that date to time there and just say times 1000 so that that's because the set time art is in milliseconds so we need to take it from seconds to milliseconds and what we want to do inside the set time art once the expiration date has arrived then we want to dispatch log out and this logout method I'm going to define as well so we'll just check this take this check out or check off time out method and pass this on at the bottom here so essentially what we're doing is once the user has successfully logged in with the token then we are executing the check or timeout method to take place so basically setting a timer and so we just need to dispatch that check or the timeout and the parameter is the expiration time which I'm going to set as 3600 so 2,600 seconds which goes in here times a thousand gives you one hour and so now I will just define the logout method here so I'm going to say export Const and I'm actually going to put that in front of the check off timeout as well so we say logout is the name of this method and inside here essentially to logout the user we just need to remove its credentials so we just say local storage dot remove item and this would be the user item and then the expiration date so I just come and grab that there so we're removing those values from local storage and then I'm just going to return an object and inside here will be the type and the type is auth log just like that so we basically defined a method for every action type so the old start which is this action type all start the odd success which takes in the token as well the arrow which takes in an error and then the logout which is only returning the action type of logout now the reason why we're actually defining these they may they may seem pretty pointless now but they actually have a purpose later on because essentially these these are events so when these events take place they're basically signals for when you can do something else so maybe you want to redirect the user to a different page or maybe you want to display some kind of data depending on what the action is so these methods here we're going to actually use them later on and you'll see how they actually used the it's just important to get them to find now in the beginning and then we have the logout method which very simply just removes those items from the local storage the check or timeout which is basically setting a timer for our logout to take place which we've defined there's an hour and then you've got the Earth login method which takes in the username and password posts it to the database or to the backend and with the response we then store it in the local storage and then dispatch our all success and dispatch the check timeout and so one last thing just to add on to the stock then here is just to add a catch so in case we posted an incorrect set of values here in our post so we just say catch the error and we will dispatch the failure and just pass in that error as the parameter to the or fail and so now I'm actually just going to copy the login method here and I'm gonna paste it at one more time and we're just going to change the name to sign up so these are just two different methods that we're defining and in the sign up we're going to take in an email we're going to take in password one and we're going to take password two again those are the parameters that are required by Django rest framework so that's why I know exactly that that's required obviously you could then change it in the backend - maybe not require an email so again you can change it to it if you want and this time the URL is different so this goes to registration like that but the method is pretty similar so we dispatch all the start we post to this URL and the data this time just needs to be updated so we now have the email we have password one and we have password - so that's the data being posted we'll still get a response who will still get the token will still create the expiration date and actually all of this is pretty much the same so if you could use outsource that to one convenience method and then just call that convenience method as well I'm not going to do that though but feel free to improve this and so essentially that is that is the order sign up so that was the only difference was essentially this data now what I'm going to do is I'm going to create a file inside our store and I'm going to call it the utility Vij's now inside here is essentially just a convenience method that we'll be using to update the object properties so I'm going to say export Const update object and it's going to take in two parameters the first one is the old object and the second one is the updated properties taking the old object and we are returning it as a new object with the updated parameters or updated properties so we just have to say return another object and here I'm using the spread to create a clone of the old object so we're getting all the parameters or all the fields of the old object and then we just update it with all the updated properties like that so essentially that will take the object and replace whatever keys we have in this object that are the same in this updated properties it'll basically replace them with the new set of keys and values so we can actually just close that file now and I'm going to close action types and the orth actions as well so now we're working inside the auth file inside the reducers folder and again I'm going to import our action types so import action types from and here we need to go one folder back into actions action types and then I'm going to import our method we just created which is the updated object and we'll import that from the utility so the import update object and now in the reducer here we define our initial state so this is like the initial state of the entire application so this could be stuff like loading any errors and in in this case for the authentication would be the token so I'm going to say constant initial state equals to this object I'm going to set the token as null and I'm going to define the error as null and the loading as false these two will play around with later just to make it a little bit nicer and so essentially what we're doing now is recreating the methods that go hand-in-hand with our actions that we just created so this first one will be off start now the reducers job is to take in the initial state so we pass in the state and to take in the action essentially what it does is it must return the state that is updated so we'll say return update object because that's the method that we just imported for convenience and it takes in the old object which is the state and the updated properties which in this case are the error and the loading values so essentially what this method is doing when we sang or start we want to say that the error is null and that loading is true so essentially the spinner that we would declare later would start spinning once aught start is is is dispatched and then when the earth success is dispatched then we say loading is false and the spinner will disappear so we'll say error is null loading is true so this will return an object of the state and basically just manipulating the states values and so we'll do the same thing with the earth success so we'll say both success it takes in the States takes in an action some of them don't actually use the action but we're just passing it in for consistency and so here we return an updated object and again we pass in the state into the object and the parameters to update in the object are the token because now if this is all success then coming from the action would be that token now remember this action here if we just go back to this actions or file when we dispatch the earth success here this method it takes in a token and it returns this object now this object contains the earth success as a type which is basically just a message and it contains the token so this here is what's basically going into this here so the action is going is being received that's one of the properties or one of the parameters of the reducer which is this all success so basically it's taking in the action it's returning the state which is updated with the token Editors received we say the error is now our null and we say loading is false remember because now we've actually been authenticated and so there's just two more so we'll just say constant or fail takes in the state takes in an action and you probably guessed it we return an updated object of the state and here we pass the error as the action error and we pass loading as false so again with the auth fail action it returns an object the object contains a message and the error that actually was being passed in from The Dispatch and that error is being passed in the action here which we grab and update the state with and then we will just add the both logout which takes in the state and in action we return an updated object which takes in the state and we updating the state to say that the token is not so hopefully that should make sense we've logged out so there's no more token when we login there is there is a token so I'm keeping it very simple or trying to so those are our reducers but now we need to define when these actually take place and so I'm going to define this inside a constant which we'll call the reducer and the reducer takes in also the state and an action but the state we set initially as the initial state and let's actually make sure that we spot that correctly so initial states update that is what we define as the initial state for our reducer and this is also a function and basically what we want to do is we want to return one of these methods here so the all start success fail and logout we want to call those methods when we've received a certain action type so essentially what we do is we say switch on the action type and we'll have four cases so we'll have action types dot auth start and if it is this case then we say return or start which is the method that we just defined above we pass in the state and we pass in the action and we just copy that a few times and we just cover all the cases so if it's all success then we will execute all success and if it's auth fail then we would execute or fail and if it was or logout then we would execute or logout and then very important the default so the default means that the action was not one of these four which is highly unlikely but we still need to include this we return the state so if it wasn't one of these then do not manipulate the state to not do anything basically just return it as it is and so we will export the default as that reducer so to quickly look over this again this should be kind of piecing itself together now we define the actions the actions are executed with the dispatch and they return an object which contains a type and maybe an extra field when that action is dispatched then it's received in the reducer as one of the parameters and here our reducers basically taking in all the actions its determining what the type of action it is so that's why we specify the type property on those objects it then looks at which method it needs to execute depending on the type of action that is being received so hopefully that makes sense now we're actually just going to take that reducer and bring it into our application so let's go into index jeaious and let's just close a bunch of these so what we want to do is import the react Redux package what we're going to need to install that so let's just close the serviette and we're going to say npm install tap - save react - Redux now because we're using react Redux we actually need to install Redux itself so we're going to say npm install - - save Redux and we're going to need to install one more package which is something that we need for middle way and so that middleware package that we need is redux thunk so just add that there that will install basically everything that we need so with that installed we can then run the server again come back in here and actually just import everything that we need so so the first thing we need is our reducer so we'll say import producer from the store and that comes from reducers both and so this reducer will be used inside our store so to create the store we need to import a method from redux so let's just import this from redux and this method is the create store method so to create the store we would just say let's call it constant store equals to create store and we pass in the reducer then you can see the second argument here is an enhancer now we need to use an enhancer to actually handle the middle way of this application and so the syntax may seem very weird but it's very short and quick so essentially we'll just create this composed enhancers constant and it's going to inherit from the window and we actually need to install a Chrome extension which we'll get to in a second but this compose property of the window is something that I'm just going to copy over and so it's this double underscore redux dev tools extension compose and otherwise if we don't have that then we're just going to use compotes and so this compose we also import from redux so it's basically checking if we have the extension installed if we don't then it's just going to use the compose method from redux and so then we can take our enhancer and pass that into our create store method and this actually takes in parameters and inside here's we we will then handle our middleware so we need to import this method which is apply middle-way and this is where redux thunk comes in redux thunk essentially has this thunk that we can import and that's going to handle the middle way so we'll say apply middle way and then just pass thunk into that so that is the store now we need to attach our store into our actual application so let's just take this react Dom and move this to the bottom and now we'll just have to create an application so we'll just say constant app and I'm just going to write this over in multiple lines so essentially we need to bring in the provider and the provider is what we use to wrap our app component and actually specify the store that we are using so we've defined the store which contains the reducer which handles all of the state manipulation and then we will specify that store as a property of the provider and the provider it actually comes from react redux so we have to say import provider from react redux and this is this thunk does not come from react to redux that comes from redux thunk there we go so the provider will create yeah so we just say provider and inside here we will cut out our app and put that there so we're wrapping our app component inside this provider and we specify the store equal to the store that we just created here then this app we can pass in to the reactant render and so that is that that is basically our reducer setup that's our reactor Redux setup so we can now actually get working on our components and actually passing the state into those components so we'll get to that in a second let's just clean up plus files we don't need that index CSS file so we'll delete that and I'm gonna delete the file it's solved and app dot CSS and in app dot J's we aren't importing it either so we can get rid of the class name and there we go so you can close that now let's actually go back into app dot J's and now here we're going to connect our app to our state and so the way we do this is by using the connect method which comes from react redux so here at the top I'm going to import connect which is from react Redux so essentially what this will do is it will grab the store that we created and it will allow us to access some of the state from the store so we come here to the bottom we call connect and we wrap our app component inside those curly braces or inside those brackets rather and inside the connect method we can pass in two functions the first is map state two props and the second one is map dispatch two props so mapping state two props basically converts state so from the store from from react Redux into properties that we can pass in to our application so essentially what this would mean is that instead of having to store state over here and then access it by saying the start states that whatever instead of having to do that you don't need to pass any of that we just have to define this method here so we'll say map state two props and we just have to take the state in as a parameter and we're going to return an object now in the object is what you actually want to map into a property and that property we will basically pass into the connect method the map state - props being passed in here and that will allow us to gain access to a property so we're going to add is authenticated as the property and it's going to come from the state and it's going to compare whether or not we have a token and check that with null so if our token is null then authenticated would be false whereas if the token is not null then authenticated is true and then this is authenticated because we are connecting our application to our store or to redux and we're passing this method in it allows us to have access to is authenticated as a property now what that means is that we can actually pass this property into our application simply by just bringing it in here but the way I'm going to do it is I'm going to pass it in is with this curly braces here so outputting it dynamically and I'm going to say dot dot this dot props so what that will do is it will pass is authenticated down into our custom layout component and allow us access to it in the layout component as well so that means if we open up layout jatis we still have access to that property and we don't need to connect that to redux we don't need to do map state to props because we passed it down in this component that means that it gains access to it as well so that means that over here with our menu items we can do a conditional check here and also this dot props dot is authenticated so if authenticated is true then we are going to show the logout menu item some copy that paste it here and I'm going to say logout but I'm actually just going to get rid of the link because we're not going to navigate somewhere so it's just gonna be a button and so that will display if we are authenticated otherwise we'll grab the login and paste that there and there we go so this check will work now we're passing the property is authenticated into our app component and then we can do the conditional check here in the layout but now I think probably the key component or key part of how to set all this up is by setting up an automatic authentication check on our app so essentially what that means is every time the app is rendered the app will check whether or not we are authenticated and so that's where map dispatch two props comes in so the first one is mapping the state so a value that is contained in the state the second one is mapping a method so here we would say map dispatch to props and this takes in a dispatch and with that dispatch it again it returns an object and in the object we specify in the same way that we do here the property that we want to reference so I'm going to call mine on try auto sign up and this is a dispatch so I'm gonna call an anonymous function like this and that function will call dispatch and what do I wanted to dispatch well I wanted to dispatch a method which will create in a second which will be the fourth check state so we'll say author check state and to have access to those actions we need to make sure that we've imported them here so we just say import star as actions from and then this comes from the store so we need to go one back let's check it in the right folder okay so store and then actions and so we're getting our actions and what we're going to do is dispatch the all check state method which all cleared in a second and we're going to reference it thanks to the map dispatch to props by tossing it into the connect function and that is the second argument if you didn't have a map state two props then you would just need to pass null so that's just something to note so we passed map dispatch two props in there and then that allows us to have access to that property in the same way as we did with the states so we can come in here and I'm going to say component dead mount so every time the component mounts we're going to call this dot props but on try auto sign up and remember these curly braces because this is a dispatch method so what that means is that every time the component is mounted it's going to call this dispatch which will call the actions dot or check State so that's actually open that up inside store actions auth and all the way at the bottom here we will define that method so we'll say export constant or check state and it's not going to take any parameters and again it will return a dispatch like the other ones and in the dispatch we're getting an object and essentially everything that we want to do inside here is to check if the token actually is stored in our local storage if it's not then we log out otherwise then we have to reevaluate the expiration date so what I'm going to do is just a constant token equals local storage get item of token and then we'll say if the token equals to undefined it's a meaning it's not there is no token in an in the local storage then we say dispatch log out just like that otherwise we're going to create an expiration date and it's going to be a new date and this we'll take in the current expiration date so we'll say local storage dot gets item and we will get the expiration dates that is currently there so that's just essentially creating the date object from that so this is the current debt expiration date that is defined in the local storage and we want to check if the expiration dates that we that it currently has is smaller than right now so we're doing a check we're seeing if the expiration date is before today meaning it's basically already happened then that means that yes because the expression that has happened we need to log out so we have to save this patch and we pass logout otherwise meaning the expiration date is in the future then we will say dispatch or success and we pass in the token and we will dispatch the auth wall check off time out as well so we say check what time out and this takes an expiration time so in order to convert our expiration date into a time we need to take the expiration date and say dot get time and then we have to subtract right now but also as a time so we say right now get time and then divide that by 1,000 as well but we just have to make sure that our brackets are in the right place yeah so we have to wrap our expiration get time and subtract the time right now wrap that in its own bracket so that takes place first then divide it by a thousand and then close off the other two things there so we'll see this in action in just a little bit what we need to do now is we need to get that Chrome extension so and see okay so here we're getting this map states props is undefined in twenty-nine and that's because I didn't define it as a constant so that should take care of that okay and we're getting this the stop props is authenticated is not is coming from undefined and that's inside our layout and that's because this is a constant it's not a class-based function so we don't need this keyword we just need props that is authenticated and there we go so now that's working so now that's going to get that Chrome extension so we're just going to say react redux from extension and here we see Redux dev tools and here is the github repository so let's go it's that first so here if you just scroll down a little bit you can see a little bit about it you can either for clear repository and then run NPM bold and then you can actually use the folder that's generated from that or get it from the Chrome Web Store so if you click on that link then it takes you to the Chrome Web Store and so here you can actually download it so mine says added to Chrome but if you don't have it installed you'll be able to install it and then once you've installed it you can go to your application and you'll get this icon here just a bunch of circles redux dev tools and if you click that then it brings this thing down here and already you can see this earth log art is being dispatched in our application and that's because we don't have a token so it's executing that dispatch method to make sure that we are logged out but now everything seems to be working fine so now we just need to add those methods to actually log in and log out so if we click on the login button that takes us to slash login but we see we're getting the same form which is basically the same as a post detail and if we take a look at euros or parts we'll see why that is so the reason for that is because we have this article ID there and we haven't specified a login component yet so I'll just copy that and we'll put log in as the URL and then I'll say the component here is login and I'll import it even though it doesn't exist yet but we'll import it and say it comes from containers slash login and now we need to actually go and create that so let's just close some of those files and inside containers I'll create login jeaious and immediately I'm going to import react from react but now we can go and get our ant design forms so we will need this we're probably going to just use this normal login form yes I'm just going to copy all that code there and we'll just bring it in here and paste everything and we don't need the react Dom render part though so let's just see what we've got we got this class normal login form extending react component the handle submit method and the render method which is returning this form and in the form we have let's see we've got the username the password and then remember so what I'm going to do is I'm gonna delete everything inside the last form item so we got an empty form at Sunday and I'm just gonna create some space so we can see what's going on so we don't need this checkbox either we'll keep the button because we're going to need that so I'll come inside the last form item I'll add this button and the type is primary and then the HTML type will say is submit and I'll add some style as well which I'll just say margin right you is 10 pixels and then inside button I'll just say login like that and right button beneath the button I'm going to say or and then add a navigation link so I'll say navigation link and inside the link is just going to be sign up so basically log in or sign up and inside the navigation link we can specify the style so I'll say style margin right in pixels as well and I'll specify two so the path to navigate to which will be slash sign up and we'll define that component in a second as well but so that's just there for us but what I'm going to do is just wrap the form inside a div so we'll just take that there and bring that to the end of the form and we want to just tab all of that in so we'll go back to here and just look for the spinner so we will basically display the spinner when we are busy logging in so we've got spin D so we just check that out and you can take whichever one you want I'm just gonna go for this custom one there so we will only me okay we'll need all of that so I'll just copy all of that and let's just bring it up top yeah so we need spin and icon so I'll put that in that same import the constant and icon I will leave there and then the rendering component I'll cut that out and we're going to use that here inside the dev so we're basically going to do a check now so we'll open the parentheses there and close them after the form and so we want to do a check so we'll say this dot props darkroom loading so if loading is true then we will display the spinner so we'll grab that spinner there and just paste that there otherwise we will show the form so remember when we click Submit it will log us in it'll exit it'll dispatch the auth login or auth start action and because we're dispatching all start that means that loading will be set to true the form will disappear and the spin would then be rendered so that's how the logic works and above this conditional statement we will output error message and this will define just here inside the render but above the return so we'll say let the error message equal to null initially and we'll say if this got props dot error so we'll pass the error into props as well but if if there is one then we will set the error message equal to a paragraph which will just output this dot prop stop error dart message just like that so either the error message is null or it is this paragraph tag and the error will only be rendered if the auth fail was dispatched because that method would assign the error property in the state to some kind of error code but now to actually get hold of the error message and this loading property we need to bring in our connect methods so we can connect our application so let's go up to the top here and I'm just going to say import from react and it's just to make sure you spell that correctly so from react redux will import connect bring this all the way down to the bottom and we'll say export to default connect and we'll leave some space for on the map states of props and we will take our wrapped normal login form pass that in there and now we need to define those maps they're two props and map dispatch so map state two props and this takes in the state and it's going to return an object which will have the loading field and that's just going to be State DOT loading and then it's going to be the error which will be state dot error so then we can take map state two props pass that into our connect as well and so let's just check if that is working so you see we get your can't resolve container login inside routes so it's supposed to be containers and now if we check this again it says nad link isn't defined in login and that's because we have an important yet so we'll import that from reactor rooted aam so this is nav link now if we check this again we see we get duplicate Declaration of icon so okay so that's already been imported and we've got no other warnings so now if we just let's go back to our normal actually go back to login or go back to login there and if we inspect this here let's see we've got some errors just telling us that the API is not found and that's okay for now but if you click on the react Redux part so you can see author logout was there and if you have react as one of your applications or Chrome extensions installed as well then if you just go to the custom layout you can see some of the properties that are being passed down so they is authenticated is false on try also sign up that's the dispatch method we defined earlier and as you start navigating down into the application you can go inside these adapters and let's see if we can go into the base Rooter and if you go all the way into the form which is this component here you can see the properties on form so you get dispatch the error so the error is coming from the actual set the map state to prop Xia so error and then history and loading so if we just toggle this loading is false or loading its true rather then you can see the spinner is displaying it and when you toggle it back then the form is displaying so that is all thanks to this map state two props method but what I'm going to do quickly is just change the roots here to be / articles / article ID so just like that so that we don't get this re-rendering of components so if we go to posts we can see posts if we go to login we can see login me but I can see that there's this little spacing here with the or signup so inside there I'm just going to take style and to bring that down and make sure there's a space there so that that space can show okay cool so that looks a lot better now let's actually handle the submitting of this form so if we just go a little bit up here we see we get handle submit and then this is entity really just handing everything for us so it says this lock pop start form but you can probably tell that you didn't actually specify the form property but that's coming from this form that creates method here so that's all being passed in for us and we can get the values which is just coming from the validated fields so yeah it's saying if there's no error console.log the received values so if we just come in here fit our console and just type whatever we want press login and you can see this received values of form username and is that password with that so also notice that username has a capital in so those are the values that we're going to grab from submission and then post into the server so what we'll do is just get rid of this console log there now what we want to do is basically define a method on our properties through react Redux that will authenticate us so what we'll do is we'll say this table props dot on earth and this will take in the username so say values the dot username and values dot password and then we'll just have to define that on earth here at the bottom but not through map States of props we have to do that through map dispatch so we say map dispatch to props the reason why this is a dispatch because we are getting the we are what we're calling this because we're passing in parameters there so that's why it's a dispatch so we have to say dispatch and we're just going to return an object and the key of the object is the property that we define so on earth and this takes in if it was an anonymous function we would we would do it like this and this means that there's no parameters but it's almost the same thing except now we pass username and password and we say dispatch actions dot both login so we'll need to import actions as well so we just go to the top and we'll import it here so that input star as actions from and then we need to go to store actions earth so now we can actually use that action to dispatch so we need to pass in those parameters as well which is just the username and the password and now we can take that map dispatch to props pass that in as the second argument to this connect method and so let's see username is not defined so that's because we've got this comma here and not a dot should just fix that to be a dot and now if we test this out we say login then it does show the spinner and it said request failed with status code for four because it's not found because the API is not working yet there were no errors on the client-side so that means that this method is working everything was working we just need the API to be up and running but after we do this on earth here what I'm going to do after the validating of the fields is I'm going to say this stuff props dot history push / so what that will do is it'll just navigate us to the /url so once it's it'll look like once you've logged in then it will it'll take you it'll redirect you instead of just showing up on the same page so let's just add that could login and there you go even though we're not logged in yet and so now we'll want to handle the snappa gating to sign up so if we just go back to login and click sign up it's taking us to sign up but we don't have a view for that yet so let's go into our routes add another one here and this will be sign up will specify sign up as the component and then in the same way as we did login will do containers slash login and now we'll need to go back to react and D and basically just find our form so that we can get the signup form working so we're going to need this confirm password email all the stuff here so let's just go and show the code they copy that code and then we're going to create our container which will be signup jas paste that all in here we don't need that wrapped render and there's a lot inside here but most of it we're going to delete so get rid of residency and we handle website change and get rid of that as well form item layout tail formats male kangaroo that this select we can get rid of that the website options we can get rid of the autocomplete result we can get a bit up as well we don't need that and so let's just make sure we only have what we need so everything from here down so all the captures all that so basically all we've got left here are the confirm password password and the email we're gonna change this a little bit so let's get rid of the labels and just bring that there so no layout no labels so just like that and then I'm going to take what we used in the login so let's see you got user name so we'll just grab user name from there come to the top here and it's just tab that back in yeah so we're going to use the same kind of style here of the input and then the prefix specified as an icon instead of using an actual label so what we'll do is just come and grab the rest of those parameters there inside the input and specify them they on the email one as well so there you've got icon type I'm going to says mail and placeholder will be email and then for the next one we've got password please input your password validator is already there so we can just come and add that on me as well but let's just check with the login so we need we need this we need that prefix so we'll just copy the one from login and replace it there so you are type password password that place all this password and the prefix there and then I'm going to do it for the second one as well but just keep the on blue as well so password place all this plus with the password and so that all seems to be good and so it looks like we won't need the option we won't need autocomplete which means you don't need that in the States either then we don't need tool tip we don't need any of those except for the ones that were using and then we need to import react from react as well and then lastly we need our button so that's actually just get some space yeah on these form items so we need our button the same one that we did here in the login so let's just grab that there and paste it there and just have that in there so we've got button except this time it says sign up everything is the same or and then it says all login and that link is to log in and then we'll need to connect the our component the same way we did the login so I'm actually just gonna copy all of that there and bring that to the bottom here actually we'll probably want to do that first so wrapt registration is formula create that then we've got map states of props map dispatch to props but now our on earth method takes an email the password one and the password too and over here we will dispatch or signup which means we need to import our actions so let's go to import star as actions from and this will come from store actions or so now we've got that there and actually we need to import connect as well so let's import from react redux we need connect so we bring that down and we say export default connect pass in map step 2 props and despatch the props and wrap our wrapped registration form in there and then just make sure that we're passing in those parameters into the auth signups username email password and password too and so basically doing the same thing as what we did in the login here where we said this dot prop start on earth so I'm going to copy that line and yeah in if no errors never say the stock props on earth and then you pass in username let's just make sure the orders practice our username and then email so values dot email then it will be values dot password and then it will be values dot confirm form item that we need to grab that confirm which is this one yeah so with that we are then authenticating then we need to re navigate after we've done that so you say props history dot push so let's see if this is working so we got button and a blank is not defined in sign up so there's button so let's just come to the top here and import it there and then nav link which will just import input that from reactor e to Dom this is nav link that should be good so there's our form user name email password password so just check if we enter some information here so you can see all of this here is validating a synchronously that's quite nice and there we go a click sign up and it just said that it was a 404 error because that's obviously not working as well but it redirected us so everything is working those methods are all 100% fine so this seems like everything is working we might just want to double-check in our layout if we go back to layout here so we'll want to just specify an on-click property here on this menu item so that when we click logout we actually do logout which means that we'll need to bring our connect method in here as well and that means that we need to convert this constant into a class so we'll say that this extends from the react component and then call render which then returns all this stuff so just cut that out put that in there and we'll just actually I'm going to take all of that then we'll just fix it now we won't need so we'll just take custom layouts put that in there so export that is the default and then we'll need our actions as well so let's get let's get connect at the top so connect there and our actions there and then we will just define we actually won't even need map States or props or just say logout is the method and it doesn't need any parameters to execute or dispatch so we say dispatch actions dot logout and this also doesn't take any parameters so now we can specify a logout as one of the properties here to the on click method so we'll just say this lot props dot logout and so that seems fine so assume you get props is not defined blind 23 of layout and that's because it's now a class-based component props is not fine without 48 so we come down and that's also because it's class-based now and then map states props is not defined so we just have to replace that with null that should all be good now so we won't be able to see if that works just yet but it should work it should be fine so now we can actually get started with the backend stuff after all this front-end stuff we can finally get the back in working so let's just close all of that and get the backend working so I'm going to start by opening our settings and I'm just going to give her that comment there and we need to install some applications so yeah I've got the terminal I'm going to need to close that though so let's just go into chrome and basically what we're looking for is the rest or registration so let's just search for that and let me see there's this package Django rest off so I'm going to click on that version 0 9.3 and so this basically takes your rest framework and makes it into an API and so this basically takes your login methods that are provided by Django or loss and converts it into a an API so to get started we just have to install Django arrest forth so let's install that now we see you get your insight installed apps we need to include rest framework auth token and rest auth so let's take all of that okay so we've got rest framework already so we'll cut that out so we've got auth token we've got rest or there and we need to include this URL so we'll just copy that coming to our URLs here and just paste this will create another path and include it to rest auth dot URLs so that all seems good then we need to migrate so we'll say passing manage migrate and series rest awesome articles okay so add a comma D migrate that call so those are migrated now but now because we want to actually sign up it says your registration which is optional if you want to enable standard registration processes you need to install Django all so let's do that so we'll step up install Django - all off we need to come and add all of this you know settings here so let's just paste that there so we've got Django concepts sites all off all of that account rest or registration so a whole bunch of stuff now and it's also get this site ID which I'll just put below the installed apps and then we need these URLs yes let's go ahead and put those in here so rest author we've already included but now we need rest or registration so let's just add that one there include resteth registration of urls so that all seems fine and I'm not going to do the social authentication but I am going to just add social account into the installed apps so that we have it there so we just make sure you got all our migration sorted so we migrate and all of that is migrated now as well and now let's actually just tidy that up a little bit so you got course headers I'm gonna bring just about rest auth so you've got Django all off course headers rest author interest raishin and rest framework or token so those are all the installed apps that we need now something that I think is pretty interesting is this demo project so if you just click on this link here then it brings up this demo project with jQuery so I recommend that you do this now so pause the video clone this repository to change into it do all the migrations and then just run that server and check I'm gonna do the same now and then we can take a look at that quickly so here I have it open that is the demo project and the reason why I think it's interesting is because if you go to this rest or directory here inside you've got all these files but if you go to URLs you can see the URLs are the same as what they are for Jango all off and so that is why if we go to our actual URL patterns it says part rest auth and then include rest off bug URLs well rest all URLs is this file it's these URL patterns so this is what's actually taking care of the authentication so you can actually go ahead and check this out so if you go into views and these are the views that actually authenticate it so I kiss the login view and it of course it's an API view because this is this is an API and so there's the whole process of logging them in so like Jango login is actually just the default login from Jango contrib so that's what's actually logging you in and it's using these tokens basically to authenticate you so it's pretty good to just go through this and just see how it's actually done it's it's pretty interesting and a pretty good example to look at so that's where that's where these URLs are coming from the rest or URLs that's for logging in but for registration its rest or slash registration so if you go to rest off slash registration URLs then here are the URLs for registering so that's why if you go to just slash or rest or like if you go to just rest or registration it's taking you to this register view and you can obviously then go and check that out so that's just a little bit more context to see how you are actually logging in and I think that's pretty interesting so with that let's actually just close this now and I'm going to run our survey and our project now so that's all working and let's just open this up so we've got rest auth and restore illustration so we'll go to rest or login and then here you can see you've got this check the credentials and return the rest token if the credentials are valid so so go to like the HTML form here the email would be required because that's the default setting but I'm going to go to this configuration I think it might actually be for Django Olaf so we'll see Django or both settings and advanced usage and if we go here to configuration then you get all these settings that you can define in your settings so like here account email verification that's an important one that we need to specify so let's go into the settings all the way down and just here we will set it to none because I'm not setting up an email client and account email required I'm also going to say and then here we've got this account authentication method so it says specify the login method to use whether the user logs in by entering their username email address or either one of both so I'm going to set it as the user name so we'll just come in here and say this is username and then I'm going to say email is not required so to say this equals to false so if we run the server now and just go back here log in let's test this test this log in so I'll say admin I'll leave the password or the email blank if I say post it logged me in as the admin user and it returned this key so that's the key that was talking about that is actually returned and you can see really how little we've done for the backend I mean that you just specified this and installed and migrated with some URLs that's it there was really no backend stuff so because this back-end is now running let's go to the front-end and if we go to slash login ok we see that this navigation isn't working now the reason for that is if we just go back to the front-end source containers layout is because of these links there's a bit of funny stuff that goes on with with the links and actually determining what path it's on so to actually fix this we need to import the with Rooter or component rather so we just say with Ruta which comes from react routed on so we go to the bottom here and just wrap the entire connect with this with root oh so now if we come back to this if you go to posts now it is working cool so that's sorted if we go to login now and let's try admin into the password click login and there we go 100% works you can see that logout is now it's actually showing and if we just say Redux dev tools and actually I'm gonna redo that right here you can see we yet auth logout which was the first thing but then we got author start or success the token changed from null to this token which is the same token here one 9 and 139 B so it's the same thing loading went from true to false and that's because of that spinner that just happened very very fast but that all is working and we can actually go to react and if we just navigate our way we can see is authenticated is true but now let's refresh the page see if it works and it does we are stolen enta cated if we go down to app is worth indicated it's still true logout is still showing so that is all working if I click logout now you can see is authenticated as false so let's go back to login click on sign up now and we'll create around the music so I'll just put in some dummy data here and let's just make sure the password is slightly different so you'd say sign up it signed us up logged us in so logout is now showing there is earth indicated is true if we go here we see we get all the success again and this time the token is different so if we go back to that's actually open up an incognito window and just let's go to the admin and just log in so if we go to tokens we can see that token there is now created and if we go to users then we can see math is created and that was the token for that user so all in all it is 100% working we've managed to set it up that you can actually log in and log out and persisted in the state so everything is working this was probably an extremely long video so if you stuck all the way to the end thank you for watching I hope it was beneficial to you the blog course is still on its way probably will be up by the end of the month but again how will I will alert you when it is ready all in all thank you for watching if you enjoyed this video don't forget to leave a comment down below let us what you thought don't forget to subscribe and we'll see you in the next one
Info
Channel: JustDjango
Views: 89,706
Rating: undefined out of 5
Keywords: django, django tutorial, python django, python, Django Web Framework (Software), django project, Python, python programming, development, django tutorial for beginners, python 3, python 3.5, django python, python tutorial, tutorial, how to python django, web development, django 2.0 tutorial, react, react tutorial, react 16 tutorial, vscode, visual studio code, user authentication, login react, signup react, django rest framework, django auth, django rest auth
Id: BxzO2M7QcZw
Channel Id: undefined
Length: 88min 12sec (5292 seconds)
Published: Thu Sep 13 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.