Laravel & Nuxt 3 Authentication Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Okay so we've managed to get the authenticated user but um what do we do with it this video is mostly about what to do after you successfully made the login request from your front-end app to your larva lab we'll start by setting up a larval API with Breeze we'll install nox3 create a login form extract a custom usage composable throw the authenticated user in a Pina store and that creates a middleware to protect auth and guest only routes let's get started the first thing we're going to do is create a new laravel application so I'll sit into projects and then do larville new Sanctum and this will create us a new larval project named Sanctum I'll see the intercenter and then composer require larval Breeze once prese is installed we can run PHP Artisan Breeze install API to scaffold a new larville API application let's open this in vs code open the NV file and as you can see as part of the breeze API scaffolding we already have a front-end URL that points to localhost 3000 which coincidentally happens to be the exact same URL or nox3 application we'll use I'll go ahead and change the DB connection to SK light and then remove all the other connection details then I'll open the database Cedar file and uncomment the test user this way we have a user we can log in with let's go ahead and run the migration so I'll do PHP Artisan migrate fresh and then seed we have an error saying database sqli doesn't exist so let's create that file here under database we'll do database Dot sqlite let's run the migration again here we go and now we'll serve the application and go ahead and create our next application I'll go inside the terminal we'll do MPX noxi init and then the name of the application which will be sanctum Dash next I'll open up the project in my code editor go in the terminal and run npm install to install all the dependencies then I'll do npm run Dev open up the browser go to localhost 3000 and here we have nox3 up and running now back to the project the first thing I'll do is delete the app file and create a new layout by going in the terminal and typing in next add layout default I'll open up the layout and here I basically want to add different links to pages of our application so we'll have next link this will point to home we'll add one for register another one for login one for auth only this will be an auth protect page and another one for guest only next up let's go ahead and create these Pages I'll open up the terminal and we'll do next add page and for home we'll do index then we'll have register log in off only and guest only let's restart the server go in the browser here we have home register log in off only and guest only let's go ahead and add that login form inside script setup we'll have a form which will be a reactive object with email and password and we'll set these to be our test user so we have test at example.com as the email and if we open the user Factory we'll see that the password is set to password moving on with the template we'll have a form on submit will do prevent and then handle login let's define this function and then inside the form we'll have two Fields one for the email which will be input of type email we'll set the model to form.email and then of course we'll have password which will be of type password and the V model will be set to form that password finally we also need a button let's now go to our handle login function and the first thing we need to do before even attempting to log in is acquire a csrf token we do that by making an initial get request to sanctum csrf cookie so back to our function next comes with a use fetch composable so let's use that to make the request we'll do a weight use fetch HTTP localhost Port 8000 so this is our laravel API endpoint slash sanctum slash csrf cookie let's turn this function into an async one go in the browser refresh go to the login page open up the dev tools go to the network tab we already have the credentials built in we'll click login we have the request let's go to the cookies we receive the cookies but if we go to application and then cookies we see that there are no cookies being set that's because we also need to specify that we want the browser to store and exchange cookies with the laravel API to do that we can go back to our use fetch function pass a second parameter which will be an object and set credentials to include now if we go in the browser refresh hit log in inspect the response we receive the cookies if we go to application cookies we see the cookies being stored in the browser so we are good to go let's go ahead and try making our login request we'll go here and we can basically duplicate this instead of sanctum csrf cookie we'll have log in the method will be post because we are making a post request and then we'll send body as form.value let's try this out I'll refresh go to the network tab hit log in and we get back a 409 response this means something is wrong with our csrf token specifically we are getting a csrf token cookie but then we also need to pass it as a header on subsequent requests so let's do that back to our use fetch call we need to add headers and then let's grab the exact header name and here we need the token from our cookies so we'll go here and say close token equals and to get the cookies we can use nutsta's use cookie composable and let's grab the exact name paste it here and then here we'll do token.value as drink let's go in the browser refresh hit log in and all our requests are successful which probably means we managed to log in but we won't know that for sure until we get our authenticated user but before we do that there's one small thing we need to change right now after making the initial login request if any of the parameters change the request is resubmitted for example if I change the email a request is being made with each keystroke to fix that we need to go back to our request and set watch to false now if we go back here clear out the application data refresh hit log in change the email no other requests are being made which is what we wanted let's go ahead and grab our authenticated user I'll duplicate this and use the structuring to get the response data we'll call the API slash user endpoint which is a default laravel endpoint so if we go to API we have this user route right here the method will be get we don't need to send in the body and let's just console log this I'll go in the browser clear out the site data refresh hit log in and here is our user now as you can see this whole login thing is quite verbose it would be nice to have like a composable that does all this stuff for us so let's create it I'll open up the terminal and run next add composable and let's call it use API fetch let's open it up and then I will go ahead and grab a custom fetch composable example I found in the next examples repository so let's grab this paste it in and we'll only keep the parameters and the type definitions let's go ahead and grab the token and the login request paste them here return the use fetch call and basically we need to customize this instead of the full URL we'll receive the path this means we can just append it here the method will not always be posed the body will not always be formed at value and then we can unpack options here the placement of this is very important because we don't want to do it here because that will overwrite our headers and we don't want that speaking of headers let's extract the headers variable we'll do let headers of type any and then we'll check for the token value so if token dot value then set headers of X excess RF token equals to token dot value string now we can go here and unpack the headers so we'll take everything that's here and put it here and then if options also include headers unpack them here let's go ahead and test this out I'll grab this go here instead of fuse fetch we'll use use API fetch remove this remove this actually I'll keep the slash so I will need to remove it from here and then we can remove this we can use this remove this and this and this this and this here we'll do the same thing foreign and I think we're good to go let's test it out I'll go in the browser clear out the site data refresh go to the network tab hit log in and I think it worked there we go much much shorter and nicer to work with Okay so we've managed to get the authenticated user but um what do we do with it ideally we need to store it in a globally available place so we can access it anywhere in our application my preferred way of doing this is by using a Pina store so let's quickly set up Pina I'll go here and search for next we'll grab the install command open the terminal paste it in we get an error so that it could not resolve this is fixed by overwriting The View version so I'll go to package.json paste that here and try again okay let's move on we need to update our nox configuration file to add the Pina module and I think we are good to go that's it let's create our first store we'll search for setup store and we have a nice counter example here let's grab it go to our project create a stores directory and it will create a file called use auth store paste that in rename this to use off store import the Define store function from Pina set the store Key to off remove all this count will be a user which is a ref of type user or null let's define the user type will have ID which is a number name which is a string and email which is also a string we can now go back to our login component and grab the entire handle login function paste it inside our store rename it to log in we'll now receive the credentials as a parameter of type credentials let's quickly add the type we'll have email as a string and password as a string inside the form.value we'll have credentials and then once we get the user we'll want to set it to user.value so we'll do user.value equals data.value as user another thing we want to do is return the response of the login request just in case the login fails due to incorrect credentials for example so we'll do const log in and then we'll return it here finally we'll want to add this function to our returned object let's go ahead and test this out I'll go to the login component do const off equals use auth store and then here let's try to grab the error if there is one from a weight of log in and pass it form dot value let's console log the error quickly restart the server go in the browser clear out the application data hit refresh try out some incorrect credentials we have an error here with the validation messages from the server we could use this object to display the messages inside our form but we won't do that today I leave that up to you let's refresh again we now have correct credentials hit login go to view Pina and we have the auth store with the logged in user which is what we wanted that means we can now go to for example our default layout and display the authenticated user we could do cost of equals use author and then here we could have a pre-tag and display of dot user if we go in the browser we can see the user being outputted on the screen we can navigate through the pages and the user is still there but once we do a full page reload the user is gone so we need a place to check if the user is logged in and if not try fetching it from the server we can do all that inside the nox plugin so let's create it I'll open the terminal type in next add plugin load user let's open it up and here we'll do cons auth equals use of store and ideally we would have a method called is logged in and if the user is not logged in we would do a weight of fetch user let's add a Sync here and of course none of these exist yet so let's add them I'll open the auth store is logged in will be a computed value and this will basically check for the user value we need to return it here and then fetch user will basically be this right here so we'll do a sync function fetch user copy all this this is the part that gets and sets the user we can now reuse that here using a weight and then return it from our store okay let's go ahead and test it out I'll refresh hit log in go through the pages do a full page refresh and it doesn't work let's check out whatever error we get back so I'll do error here and then console.log error refresh open this up and we get a 405 method not allowed this is because when we are doing a full page reload the use API fetch composable is no longer executed in the browser but on the server and the server at least right now does not send some important information required by larville which is the cookies and the referrer so to fix this 405 we must forward that information when the use API fetch composable is executed on the server so let's go inside our use API fetch composable and to check if this runs on the server we can do if process server then we'll set headers to a new object that has everything inside headers plus some headers from the incoming request to get those headers we can use knox's use request headers composable that takes in an array with the headers we want which are referrer and cookie let's go ahead and test this out I'll clear the application data refresh go to the login page Log in here we have the user do a full page refresh and the user is still there which is what we wanted let's go ahead and add some logout functionality I'll close all this go to the default layout add a button this will only be visible if the user is logged in so if auth is logged in log out on click will call handle logout let's add this function and this will basically call a weight Earth dot logout of course this needs to be in a sync function and this logout function doesn't exist yet so let's add it we'll go here we'll do function logout we'll make a post request to slash logout so I'll grab this and do slash log out method will be post and then of course this function will be in a sync one once we do the logout requests we'll set user.value to null and navigate to slash log in of course we also need to include include this logout function to our return then we can go in the browser refresh clear out the site data hit login navigate through the pages do a full page refresh and then log out and we are successfully logged out our user let's go ahead and do the register page so I'll close all this open up the login page and then the register page I'll grab everything from login paste it here and now for this form we'll have email password and password confirmation let's set these to empty values and we also need to add the name and then here we will have handle register this will be register here we'll have another input for the name of type text and another input for the password confirmation this is just password instead of login we'll have register and then here if there is no error we'll just navigate to the home page let's go ahead and add the register method on the author it will basically be the same as the login method but we will receive info instead of credentials so this will be registration info instead of calling the login endpoint we'll call the register endpoint and instead of posting the credentials we'll be posting the information let's add the type foreign email list ring password and password confirmation one final thing we need to do is include this in the return okay let's try it out but first let's restart the server and then wait for it refresh go to register foreign hit register and we are logged in as our new user isn't that nice finally let's create some middleware specifically an auth and guess middleware I'll open up the terminal and say next add middleware off and then guest let's start with the oath middleware here we'll basically grab the Oster and if the user is not logged in so auth is logged in then navigate to slash login and let's make sure we replace this in the browser's history now for the guest middleware we'll do the exact opposite so if the user is logged in we'll redirect them to the home page let's go ahead and apply these so I'll open the auth only page and inside setup we'll do Define page meta we'll pass middleware and we'll set it to off then for the guest only we'll do the same thing but we'll set guest let's go ahead and restart the server go in the browser we are now logged in so we shouldn't be able to access the guest only page and we are not we are redirected to the home page but if we go to the auth only page we can certainly visit it now if we log out and try to access the auth only again we cannot do it but we can access the guest only page so there's our middleware up and running I know this video as long as and probably super hard to follow but it is what it is this stuff is sometimes hard to explain at least for me if you somehow enjoyed it and found it useful though don't forget to like it share it subscribe click the Bell button all that good stuff bye
Info
Channel: cdruc
Views: 25,763
Rating: undefined out of 5
Keywords: laravel, nuxt, vue3, vue, nuxtjs, authentication
Id: NY9yoqoN72w
Channel Id: undefined
Length: 27min 38sec (1658 seconds)
Published: Tue Jun 27 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.