Full Stack React & Django [6] - Auth State & Private Routes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on guys welcome back to react redux in django so in the last video we implemented token authentication on the back end so that we can actually register we can log-in we'll receive a token and then we can use that token to access protected routes all right such as the user route so in this video I at least want to get the login and register component created so that we can have it in our UI also install the react router and then we need to have a inside our state here you can see we have leads arrows messages all pertaining to our reducers we need to have off in here with some values such as the token if there is one is authenticated so we can check to see if we're authenticated or not and then I also want to create a private route component that we can use so that if we visit this dashboard and we're not logged in it redirects us to the login page or the login component okay so let's start off with installing react router because we're going to need to use that so I'm going to go to my terminal here that's running webpack and stop it and just do an NPM install react - router - Dom okay we're using version 4 of react router and then we'll go ahead and run NPM run dev again so in our App j/s file so front-end source components app J s we're gonna bring in some stuff from react router so I'm going to go let's go right here and we're going to import some stuff from react router daaamn now in a lot of cases you're going to use browser router however in this case where we have our back end we have our front end routes if we were to click a link to go to the login page it would load but if we reload the browser it's going to look to the server for a page called login and we don't want that so to prevent that from happening you could either you know if you deploy to a patchy or something you can mess with the config with the htaccess file but for now what we're going to do is just use the hash router okay so we're gonna say import hash router as router and then we also want to bring in route so we can create our routes switch and redirect all right and then let's go down below and in order to use the router we have to wrap our components so we're gonna go right above the fragment here and just put in router and wrap that so we'll take the ending tag and put that right here and then instead of just embedding dashboard here we're gonna put in our switch we want to surround all our routes with a switch and we're gonna get some issues when we use that when we create our private routes later but here we just want to put in a route we're gonna say exact path of slash which is the route and then we're gonna load the component of dashboard so if I save this in reloj we should get the same exact thing okay it's just loading a row but it's still giving us the dashboard component so the next thing I want to do is just create the register and login pages okay before we add any functionality let's at least just get get it so that we can have some links up here to go to the register and login page so over in components let's create a folder called accounts and inside accounts let's create a file called login j/s and let's also create a file called register dot j s alright well start with the register so this is going to be a class based component and we're gonna add a little bit of state here for each input this is commodious lis component level state it has nothing to do with Redux so we'll have a user name we'll have email password and password too because I want a confirmation and then for the render I'm actually just going to paste this in don't have to type all this JSX in here so if we go up top you can see that we have a just a six column div M Auto so that it's put in the middle or using a card to wrap our form we have an h2 and then we have our form and we have an on submit each input has a name attribute that matches the state name and then we have an on change and then the value is coming from the state now right here I just have user name and then I have email so we actually need to pull these from the state so let's use destructuring up here to do that so username email password and password too and we're gonna pull those from this dot state okay and then down at the bottom we just have a submit and then we have this paragraph with a link to the login okay now this link we need to pull in from react router Dom so let's go up here and let's say import what am i importing link from we act around a Dom alright now let's create the on submit and the on change so on submit and for now we of course need to do a dot prevent default but for now I'm just gonna do a console log and just say submit ultimately we're going to want to call a login action inside of an auth in an auth dot Jas file in the actions folder but we'll get to that later my goal right now is just to get the routes and to have some links to be able to go to these these pages so for the on change all we want to do is set state so set the component level state and we want to take whatever the input is which we can get from the name right here the name attribute so we need to put this in brackets since this is a key and then e dot prevent weight what am i doing prevent heed odds target dot name and then set that to e dot target's dot value and that's it so this should at least display the component now I'm gonna copy this whole thing and go to login J s cuz it's very similar so we'll paste that in let's change this to login for the state we only need username and password because it's a login form and let's see we'll keep these two methods the same we're pulling out just the username and password and then let's change the title to login and we'll keep the username form group let's get rid of the email and let's get rid of the confirm password alright and then the button we'll change that to login and then here we'll just say don't have an account and then we'll point to the register okay and then finally we'll change this down here to login okay so now at least we have our components now let's go to our app j/s and let's create routes for them so we have to bring them in so up here I'm just gonna bring in both components so from accounts slash login we're gonna import log in and let's import register from accounts slash register all right and then down here let's create the routes so I'm just going to copy this route down and we're gonna have one for register and login okay I'll save that now let's add some links so that we can point to these so we're gonna add them in the header or the nav bar so let's go to components layout header js' and let's bring in link from react router and down in the UL here which is self-closing right now so we're going to add an ending tag and inside here let's create an Li with a class of nav - item and we'll do times - and then in here we'll put our link - let's do slash register and then just add a class name for bootstrap which is gonna be nav - link all right and we'll just say register and then I'm just gonna copy this link put it inside here and this one is gonna be to login so let's go ahead and save that alright now we have our register and login links and they work they display the the components alright so let's go back to the root here I also want to just add a container to the navbar because if we stretch this out you can see how far the the heading and the links go so inside the nav right here let's just put a class of container and let's wrap everything so we'll put this div right here and save and now if we reload you can see they get pushed in so that this just just looks a little better alright so let's see the next thing we want to do is add an auth reducer because in Redux we want to have as part of our state we want to have off okay so let's go to let's go to reducers index j s and we're gonna have an author adieu sore so let's bring that in and then add that down here alright so save that and then let's create in reducers a new file called auth dot J s alright so for now I'm just I'm just going to add the initial State just so we can get it down and get it showing up in our state so let's say Const initial state and we'll set that to an object we're gonna have a token and that token is gonna we're gonna look in local storage for that that's where it's gonna get stored so we can say local storage dot get item and we want to look for token ok next thing we want is is authenticated which by default is going to be null and then what will happen is once we login or load the user this will get turn to true and the token will also get stored in local storage next we want is loading which is just gonna fire fire off we're gonna have an is loading action that will fire off in between trying to log are trying to load the user and then actually making the request and getting the response back then we'll change it back to false so let's put that to false for now and then user we're gonna get the user from the response but this is gonna be null to begin with all right and then let's create our function all right so let's see function is gonna take in state which is going to equal the initial state and then also in action and for right now I'm just gonna put in let's do our switch and we're checking the type and for right now let's just do a default and let's return state ok so just by doing this if I reload now we have auth in our state and you can see down here we have our token which is null is authenticated is loading in user now before I go and add any actions here I want to I want to create a prop private route because I don't want this dashboard to show unless we're logged in so with what we have here we should be able to do that so let's go to components let's see let's close that up let's go to components and I'm gonna create a new folder in components called common which is just gonna be anything that doesn't fit into these other categories so in common let's create a new file called private route Jas okay which is just gonna be kind of a proxy for just a regular route except we want to check to see if the users logged in so in our app J s I want to be able to for the dashboard say private route like that or for any route that we want to protect we want to be able to do that so inside private route this is going to be a functional component so we'll say r CF but I'm gonna make it a an arrow function so we can say cons private routes and we have our parameters and let's go down here and say sport default private route now let's see as far as parameters that go in here we're gonna put some curly braces and we want to define component which is going to be the component that's passed in meaning if we look at apps is whatever this is in this case it's dashboard but whatever that component that's passed in we need to render that okay so we're going to use render props to to render that out to those to the UI so we need that we also need auth which are going to bring in from Redux it's going to represent the auth state and then if there's any other props that that are added we'll use the rest operator for that so just three dots and then rest okay now let's let's bring in connect save that let's bring in actually before we bring in connect let's bring in route and redirect from the reactor outer and then we'll import connect because remember we have to get that off state we need to check to see if we're authenticated so bring this in from and that's going to be react Redux and then let's do our prop types all right now of course when we use connect we have to export it down here and then let's wrap private row and then let's add our map state to props takes in state okay and we will just want the off from the auth reducer so let's say state dot off all right and then of course you need to add mount state two props here and now we should have access to this dot props dot off now within here let's just get rid of these curly braces and let's directly return a route like this now this route we want to include any any of the rest props or parameters that are passed in so we're gonna just add rest and then we want to add a render prop so let's do render equals and then props and then we'll put an arrow and for now let's just go ahead and return the components okay so whatever the component that's passed in and of course we need to add its props like that so right now if I save this I should be able to bring this in so let's bring in from common want to bring in private route set that to private row and then anything we want to protect like dashboard we're just going to use private route instead of route okay now right now if I reload it should do the same exact thing because all we're doing is going through this private route component and simply loading the component just like it would normally so what we have to do now is check to make sure that we're logged in if we're not then we want to redirect so right above this return let's do an if okay and we're going to do else if and then else and we're just going to move this return up into this else and what we want to check first is if the you if it's loading so we're going to say if auth dot is loading then let's return and you could create like a spinner or something if you want to be fancy but I'm just going to do in h2 and just say loading dot okay so if it's basically between firing the event or the action and actually getting the response from the request it's going to be in this loading State so if this if that's the case we just want to return this else if not off dot is authenticated okay so if we're not logged in then we want to redirect so return redirect which we brought in from react router to and we want to go to login so it's saved that so what we're checking is in our state we're looking at this off we're first seeing if it's loading okay which is initially set to false but when we make the request it'll be true when it's not loading anymore then we're gonna check to see if this is false this is authenticated false or null and if it's null or false or anything but true then we're gonna redirect to the login page okay and then any route that we want to add this to we just use private route instead of route so let's go ahead and save this and let's reload and we get redirected to login all right so let's close all of these up except for App j/s and the next thing I want to do is I want to start to implement some actions specifically the load user action because we need to constantly check to see if we're authenticated or not because I mean we're dealing with a REST API and we're dealing with a front-end so it's I mean it's stateless we have to keep checking if the users logged in basically with every time the the main app component is loaded so what we'll do is we'll have a component did mount in our app component and then we'll call the load user action which is going to make a request to auth API auth user with a token if there is one and then basically return is authenticated true along with any other data filling the state filling the auth State so let's start with let's see let's go to our types actions types J s and there's quite a few types that we're going to be needing right now let's just do let's see I'm gonna copy this down three times and let's do user loading and user loaded and let's see let's do off error okay because like I said we want to check to see if the user is authenticated if there's a token so we'll fetch a token if not then or if it is then we'll call this user loaded if not we'll call off error so let's save this and let's go back into our reducer so reducers auth J s and let's go ahead and import some of these so same ports it's gonna be from dot dot slash action slash types and let's bring in user loaded user loading and off error and then let's go down here and we'll add a case for user loading and all user loading is gonna do is return the state but it's going to change the is loading value to true okay that's all that's going to do and then user loaded so case user loaded we're going to return the states and we're going to change is authenticated to true okay because it means that we made a successful request to API off the user with the token all right so is authenticated true and then let's do is loading set that back to false once the request is done or the response is sent and then as far as the the user that'll be in the payload so we'll say action dot payload all right now if it doesn't authenticate then let's do our case of auth error and for auth error we're going to remove any token from local storage if there is one so local storage dot remove item and we want to remove the token and then let's do return states and we're gonna set token to no we're gonna set user to null so basically just setting everything back to the default we're gonna set is authenticated to false and we're gonna set is loading make sure that's false as well okay so now that we have those let's create in our actions folder a new file called off dot J s and this is where we're going to create all of our action functions so let's start off with just bringing in Axio so we can make requests and then I'm also going to import from the messages action I want that returned errors because I'm going to use that so returned errors from dot slash messages and then let's import from our types and we want to bring in user loaded loading and auth error all right so let's create a method here an action called load users so what this is going to do is it's going to check the token and load the user okay and it'll it'll set is authenticated to true if if everything goes okay so let's do a export const load user ok we're using dispatch now I put parentheses here cuz I'm also gonna bring in get state which allows us to just fetch something from the state and I want to use that to get the token if there is one or two check if there is one and then the first thing we want to do is set the user loading okay so we can actually just dispatch its dispatch I don't want to do that dispatch an action with the type of user loading so what that'll do is it'll change that is loading value to true okay before we make our request now we're gonna have to do a couple things before we make our requests we need to first get the token from the state so we can say Const token and let's set that to get state which is a method and then we can say auth dot token so we're looking in our off state our auth reducer and we're looking at that token value which should come from local storage okay if it's there it's gonna be in local storage and then we need to send some headers with our request so let's say headers and the way that we do this with Axios is we set a config and then we set headers a headers object with any headers we want to send and one header we want to send definitely is content type just like we did with postman and we're gonna set that to application slash Jason alright now we want to check for the token okay so let's say if token add two headers our headers config okay so we'll check if token then let's take that config object and take that headers object inside of it and add authorization alright just like we did in postman in fact if we look at postman you can see right here we added an authorization in the header with the word token a space and then the actual token so that's what we want to set this to we want to set it to let's put some backticks and we'll say the word tokens space and then the actual token okay and then we're right now ready to create our our request to get the user or load the user so under that let's say Axios and this is actually a get request so we're going to do Axios get and the endpoint is slash API slash auth slash user and we want to send our config along with it okay and then that'll give us a promise back so dot then get a result and then that result we want to dispatch in action with the type of user loaded okay and then we want to send the payload which is going to be the response data now if something goes wrong well mean not something that goes wrong but if we're not authenticated there's no token that matches then let's do a dot catch and in here we're gonna say error and I want to do two things I want to dispatch our return errors that we brought in so return errors this just adds it to the errors in the state so remember it takes in a message and a status so we can get that with era dot response dot data that'll give us the message and then the status will say error dot response dot status all right now that just puts the error into the state we also want to call the auth error because we want to fire this off if we're not logged in just set everything to no is authenticated false and so on so let's go ahead and dispatch the type of off error and that's it so we'll save that now nothing is going to change because all we've done is created this load user we're not actually calling it now we want to call this pretty much all the time so we're going to go to app J s and let's bring in the action so we'll say import load user and that's gonna be from we want to go up one into actions and then off okay now in order to call this we're gonna create or add the lifecycle method component did mount which fires off whenever the component is mounted that the main app so basically when our app loads and in order to call this load user we can we can actually call dispatch directly from the store so we'll say store dot dispatch and then just pass in load user all right so let's save that and let's just pull this redux these redux tools up and let's reload and let's see it should be calling something i we must have something going on here dispatch is not defined at sea where are we here I spelled dispatch wrong all right so let's save that and reload okay let's look at our redux tool just to see exactly what's going on and you can see that auth error was called user loading was called right here and then it failed obviously because we haven't logged in we don't have a valid token so down here return errors was called which calls get errors and then we dispatched auth error here and if we look in our off state it's everything is null and false all right so that's exactly what should be happening now in the next video I want to act they add the login functionality so that we can change that we'll be able to log in get a token and it'll check the token here it'll run it up against this auth user and then if it's valid it will load the user all right so we'll get into that in the next video
Info
Channel: Traversy Media
Views: 53,265
Rating: undefined out of 5
Keywords: react, react redux, react private routes
Id: EmAc4wQikwY
Channel Id: undefined
Length: 33min 0sec (1980 seconds)
Published: Thu Jan 31 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.