Manage users in your Nuxt SSR app with Firebase 🔥

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in today's video we're gonna explore some of the things that I've been testing out on firebase and next and we're gonna look at how to authenticate and I guess authorize some of our users into the application the application that we will be doing this with is a server-side reynad application and with this setup there are a few things to think about mainly the fact that we have two environments that we're working with in one application in one instance we're actually on the server and in another instance we're on the client so some of the main things that we need to worry about is one we need to have a way to send some data from the client with each request and the thing that's perfect for this is cookies so we'll be using some cookies to send some data that we'll retrieve from firebase authentication on the client side and we'll initiate this or store this in the next or by checking the store value every time we can block users from visiting around on the server side and keep them from seeing content that they shouldn't or maybe just role based access control in some systems but enough talk and let's go look at what we are going to do so I'm in my or on my desktop here and I have a command line terminal command prompt open on Windows and there's a few things that we do need for this we need nodejs installed and preferably I would say a version 10 upwards I think the latest not the latest but the long-term support version is ten point fifteen point three so I would suggest you guys go install that and if my voice sounds a little bit weird today it's because I'm have a little bit of a cold but I still felt like making this video so just excuse that but to get started we have noches and you can test that by saying no - beyond your command line and I have ten point in point one so I could actually upgrade that but I won't for now and then what I'm gonna do is I'm gonna say MPX and then create - next - app what MPX is gonna do is just gonna download the necessary tool to install the next app so that we don't have to install it globally or anything it's just a once off use so what I want to call this is a next fire o'the application and press Enter the CLI tool will ask us for a few things like the project name and the description I'll just leave it as is I don't want to select the server framework but if you want to you could select like Express or whatever and then you can configure your server yourself but out of the box next server is pretty good so I'm just gonna say none we don't want to make any requests I have a link to I mean a prettier bolt into my via skirt so I'm not gonna select any of that and I don't want a framework because I'm going to use a CSS link from the internet just for some basic styling and then no testing and universal and I'll just change my name yeah do that and I'm gonna use MPM to install dependencies after the dependencies have installed I'm going to add a few of my own dependencies that we'll be using in this video and I'll add that through npm install the first one is cookie pasta let's start with firebase and then cookie pasta and we want J s cookie and we also want JWT key code these are the dependencies we'll use firebase is for the authentication online cookie parser is - as you as you can tell pause a cookie from the request J's cookie is to save or remove cookies from our browser and JWT D code is what we're gonna use to decode the J JSON web token that Google provides to us through a certain method that we'll use while that installs you guys would want to go to the console dot fire-based or google.com website so that you can log into your console and create an app your home page will have a few options here just click on web and then give it the name you want and then the important step is to go to authentication and then sign-in method and then enable this email password method because this is what we'll be using for our application and while you're at it we won't be doing sign up because it's a little bit redundant you can think about sign up by yourself I think the thing that we want to do is just create a test account here so that we don't need to sign up before using this and I'm just gonna make my post with something simple like boss with one two three and then add that user to the firebase authentication module this way we don't have to create the users our current application has a file structure laid out for us it has index page it has a layout default layout and it has some components what I'm gonna do actually is just delete this come the logo component completely out of the project I'm gonna go to index select everything and do template and then just an h1 for now hello and then on the layouts I'm gonna go to default select everything again and I'm gonna scaffold this one out with the view syntax and by the way I'm using vs code let me zoom in so you guys can see what's going on here and then in the default layout what we need is a first actually what I want to do is I want to import some CSS just some remote CSS I'm gonna get it from this this website here it's from boots watch they have CSS themes based on bootstrap I'm only going to input the CSS no JavaScript or anything like that and then save that and before I'm gonna create a section yeah and I'm gonna give the section a class of container and then inside this section I'm gonna do the max tag and what this Knox tag basically does is it just renders whichever route you visit into this container so next works with a file based router so you can either create a new page by name like about dot view and then if you go to slash about in your browser it will open up this page as an HTML page but you can also and the way I like to do it is you can create a folder with the name that you want and then in that you can do a new file index dot view and this will be on the slash about route as well but what this allows you to do is you can create sub you can create like sug sorry slug routes for it's a a dynamic ID or something like that that you want to render but I'm just gonna delete that for now and then let's just see what this looks like to run it I'm gonna do ctrl told her and do NPM run Dave Dave see just no motive and open this in the browser well this loads its it shows you a nice well update of what's going on and then you can see this is our home page so just quickly what I'm gonna do is I'm gonna create a a div with a call large six which means it's half of the container and this 2mx auto and then in here create a bootstrap form just for us to be able to send off our login details so with the form I'm gonna add an add submit prevent attribute because what that does is it whenever we click Submit then the form doesn't try to post it to some server because we're gonna handle it with JavaScript so we only need to filled I'm gonna create a dot form group and in this form group will have an input with the clause of form control and this is just basic bootstrap clauses and we want the type to be email and I'm gonna set an ID of Knox fire email and then just copy this to create a new one and this one will be a type of password and we'll make one more and we'll do a types of Mattia so type submit' just means basically it's a button and then we can give it a class of PN and BTN primary so I'm gonna close this down because it's a little bit distracting and now that we have those classes we should see a button on the page let's save that and open it's actually split the screen so we can see both on this group on the on the video so okay I think I'm gonna do it this way around what's going on this and this so okay so now we have that so we need to add a something that just says login to your account and this is on the home page typically you might want to have it on some sort of you know some sort of route like login or something like that but just because this is so simple I'll just keep it on that home page and then we need a placeholder for this for this input I'm just gonna add it here placeholder equals email address and on the password will do a placeholder of Pottsville and so that makes it a little bit more clear what's going on the next thing we want to do is we want to add a script tag to handle our data modeling so we're gonna add a data attribute and we're gonna say in the data attribute we're gonna have an account field and the account field will have an email which will be empty and the password which will also be empty for now and we can test I mean we can model this by doing a V model on the input and say account the email for email and on the password will V model a account don't password so all this is basically doing is it's just creating a bindable data attribute which is being modeled by these inputs so whenever this input changes it immediately sets this property on data so let's create a fake login I mean at some click what is it at I guess I'd click yeah I click what we want to do is login so under data we want to go to methods and we need to create that login method and we can do it like this so in our methods what we want to do with login for now is just we want to say console that log logging in and then do a account dot female and a account dot password so if we inspect this page now let me put this at the bottom so if we inspect this page with the console we can do this is clear this out we can do email test at test calm and we can do a pause with one two three year submit and it says account because whenever you use your data attributes you need to bind it with this because this is the global view object and this dot data in this thought account would be on that object so let's do this and in rebuild so now we can do we have to also set these IDs to unique because both of them are email right now so let's clear this out and then we can try that again we can do this password one two three and submit so we're logging in with tests that test or comment pause one two three so we know that the modeling is working and it's probably at this point where you would want to add some chicks so before logging you would might want to create some to do add what you call it like you sanitize your data make sure it looks the it looks like you wanted the shape and the type and length and everything there's a word for that but I can't remember let's just say parsing of data it's like validation or something yeah I think it's validation so you could add that if you want but now we have a basic login so what we actually want to do after this is we want to say this dot router which is views both in router dot push and then we want to go to slash admin so slash admin doesn't exist yet so we have to create it let's go to our folder structure and I'll actually create two I'll create admin and then inside admin or to an index dot view for the home admin and then inside admin I'll also do a profile dot view so this will profile would be slash admin / profile and the reason I'm doing that is just to show you how to block any routes within another route which we'll do in our middle way but for now this is fine so we'll just do a scaffold here and just say h1 profile and then we actually don't need to all scaffold we can just do this and in in admin we can do a same thing we'll do a scaffold we'll just do a template and it was just H one admin route say that if we test yeah we can go to slash admin and it'll say we have an admin route and we get to slash admin / profile and we'll be on the profile out so what we want to do now is sort of block the user from being able to visit these routes because nobody's logged in we don't know who's admin route this is and what they have to see so we can't let them visit this unless they're all logged in so before we create the login we'll we'll first block these routes and we can do that in our server middleware so first we have to go to middleware and create a new file and I'm gonna call it call it authenticated dot J's because this is a middle way it's not a component and then I'm going to close that down for a bit what you have to do in here is you have to export a default function and this function takes a few parameters I'm gonna D structure it it gives you context but the context has the store it has the route and it has redirect it has more than this but for now this is all well me so what we want to do is we want to first check if there is a user signed in so we have to create this user so we'll say Const user equals store dot state dot uses dot user doesn't exist yet we have to create this this store object the store user in our NOC store which comes out of the box and then for our what what else do we need we need our user and we need our route yeah so we have a route so what we want to do is yeah our block routes so I'm gonna create a thing called blocked route a variable called block route and I'm gonna set that equal to a regular expression so this regular expression will do slash afford slash atman and then escape forward slash store so anything anything after that so it can even be blank and then do that and do a g4 global so this this means that any anything that matches slash admin / anything globally has to be blocked but first we have to write the redirect if that happens so what we want to do is we want to say if there is no user and the route that we are visiting that that routes path matches so this is a Bolton JavaScript regular expression function or string function which checks if it matches a specific string or regular expression and we're using this block route regular expression if it doesn't match it will return null so this will be a false statement and this will never and this will happen so if we so what we're saying is if there's no user in the store and the route is one that we're blocking we have to redirect because they shouldn't be they shouldn't be on this page and we'll just go back home to make them login again so when we say that nothing happens because we have to go to our Knox config and below plugins I'm gonna add another comment and just say router settings and then add a property called router and then in this router I'm gonna do something called middle way and with middle way you pass it an array of names of the middle way so you don't have to give it a path you can just actually give it the name it knows to go look in the middle way folder so we can say authenticated and then save that and when this happens you your project will rebuild because it's it's a changing the config of the projects that will rebuild so how if we refresh then cannot read properly state of undefined because we haven't created our story so let's go to store and the way we do that is by creating an index J is file and all we have to do here is we have to say export a state so const or i mean--can state equals function that returns an object and we'll just give this user no so there's no user in the store when we start so let's just say that and now if we reload this we have declared in our function state store that stated users dot user so what i meant with that is that if you go to your store you can create a new folder and name it uses and this will sort of act as a module or a namespace and within users you can create an index that changes and then i'm just gonna move this store of the state out of this into the users module and save that and then we should try to read out our page and they you saw that quick redirect so if i go up here and i try to add slash admin enter just redirects and if i try to add slash admin / profile it redirects back to home because it knows that there's no user in our application so the next step is to add this user that we want to our application and we'll do that through firebase so first of all we installed the firebase dependency in our when we created the project it's ordered we know we didn't we need to install those dependencies so we have to say npm install firebase and cookie parser and J's cookie and we have to install JWT decode as well and i think why didn't install years because i wasn't in the right directory so it'll install yeah previously when i installed it i was in the the drive directory so before installing the dependencies please go into your application now that we have our Nancy's installed we can close this down I'm gonna close down all those editors and I'm gonna shrink this and go to create a new folder and I'm gonna call this services and in the services folder I'm gonna create a file called firebase thas and India I'm gonna import firebase from firebase slash app and what we need to do is set a config and this config you will find in your dashboard for your application so I'm gonna go to settings project settings scroll down and you'll see the script here and just use this object yeah I'm just gonna copy that and then paste it here and then what we want to do is first before we create our app we want to see if we haven't created an app yet because if there's an app already we don't need to create it so what we need to do is just say if not firebase dart app start length question mark then we want to firebase tour initialize app with the config otherwise we just want to do nothing so what this is doing its first of all it's checking if there is that this is a ternary operator so we don't need the if and the brackets and stuff we close this down so first if there's no if there's no apps or really defined then we create an app else we don't create an app and then what we want to do is we want to export a constant called called auth and we want to set that equal to firebase tours so this is just creating the firebase instance and allowing us to use this oath object we can close that down now and open a open the login page if we go to our home page what we want to do instead of instead of just console that logging we want to actually set a login action from our store so what we're going to do is going to say this dot store The Dispatch which is an action it's being dispatched and we're gonna call this users because we put it in the users namespace and login and then what we want to give it is the account save that but before that works we need to go to our store and go to users and create a export of an action so export const actions equals an object this can just be a normal object and we want to export the login method so the login method takes two arguments it takes a destructive context from store so we can say commit and we can give it to payload and i'm just gonna call this account two and then for this commit to work we need a mutation so mutations will change our state so what we need to do is to export const mutations and this is also an object and what i want to do is set this to set user and this takes a state and a account and you need to make this a function so what we want to do is just say state that user equals equals account and this store is available throughout the whole application so we can even change this from our next server or our another store so this will help us tremendously in the upcoming steps okay so we've covered creating the normal pages blocking the admin route and oh but we first have to start our application again let's clear this p.m. run dave and let that start up so we've we've done the blocking and we've done the login page and everything and the redirecting what we want to do now is on login we want to create this firebase login from that checks sort of if the details are correct and logs the user in and firebase handles everything for us you don't have to worry about setting your user from Google or whatever but what we need to do is we need to create a cookie in our browser so that we can use that cookie on the server so in order to be able to use a cookie we need to import cookie from jeaious - cookie the dependency we installed and then we also need to bring in that oath from firebase and we have to do we have to do this because we export it as a constant and then say from ad ford slash services which is just a shorthand for the project based directory and firebase and we can live off the TAS so what we want to do first is you can do some validation here if you want again check if the account as the actual staff or whatever but we're just gonna keep it simple for now and we're gonna say oath will actually make this a async function and we'll say a wait yeah a wait auth dot log in with email and pause but it's a very long method name but this is from Google so you have to enter it that way and we want to give it the account or email and the account don't password and next we want to if we have this because we were waiting this that means that it will be done with the login so there will be a new object available to us and we can and that's the user so what we want to do is we want to get the credentials from the user that's been logged in so a cool thing that firebase provides us is a method called auth dot let's just say const token equals and then this earth which is firebases auth dot current user dot get ID token and what this is gonna do is it's gonna get a JSON web token form of the users information so this is very useful because we can create a cookie with that JSON web token and we can parse it so what we're gonna do is we're gonna say wait that and then we want to do cookie dots it and this just creates a cookie in our browser and we want to call this access token and then save the token in that so basically what we're doing is we're logging in the user and once that's done we'll have this altered current user available to us and we can call this method to create a JSON web token so let's do this log in the user and what we want to do here is get JSON web token from firebase and then set JW set the JWT to token i mean to the cookie and then all of this we actually need to wrap within a try-catch block because this is how we'll end our errors I'm just gonna say for now that we need to if there's an error we can throw that error and then all of this logic needs to go within try so what what this is doing is just if any if anything occurs during this process of logging in getting a token if there's an error we're gonna throw this tool to our page so we'll have to do a dot catch on this one but we're not done yet what we need to do is set the user locally and we do that through the commit message and we want to commit the set user mutation and we want to give it an object and you can say that we could even do this and say Const email you ID equals auth dot current user as well so this will restructure the email and UID properties out of the current user and all we have to do now in here is to set the user we can just do email and UID because I don't want any of the other properties to be set so this will set the user locally and then we have a user now store so we can actually test this let's save and the way we'll test this is to yeah we'll just do the login we have to handle this area though so on the index page what I'm gonna do is instead of just dispatching I'm gonna say dot catch which allows us to get that error if there's an error and firebase gives quite good error messages and all we have to do to handle that is we can say we can create new properties is error false and your message is an empty string and then up here below the input we can do a alert div with danger Clause also from bootstrap and then just add a p with margin bottom of zero and this we can say yeah do an error message from the data property and we only want to show this if there is a error so we can do V if this error and then what we do in this catch block is we can do this dot is error equals true and then we'll set a this is quite dirty but for now we'll just set a timeout and just do the start error notice that is equals false so it's gonna make a true shelter and then after let's say three seconds or five seconds it's gonna show take it away but we also need to set the message we can say this dot error message equals error from firebase code let's say that and then we can actually test this by entering the email that we have but entering the wrong password just to see if this is actually working so let's submit and it says account is not defined so why is that because we're using this dot account and this reminds me of Daniel Schiffman from the coding training where he goes I always seem to forget that this died anyway so let's refresh and now we have imported module is not a function default is not a function something is breaking horrendously so let's go back to the store and we can say I took a bit of time to find the error but this is why it's important to read talks I just assume I know the stuff but it's called sign-in with email and password not log in with email and password so I also think we need to reset this see if we have any other mistakes commit okay oh I actually know what's wrong we have to go to the services fibers because we just imported the app module it's not importing anything everything from firebase so we have to explicitly say firebase slash orthia so that it actually knows what this author module is and if we refresh this should be good now let's try working with this error again the error message should show so let's go test that test and just enter the post with one submit it says all wrong password so you can I mean this isn't the best so you could probably do something better than that but 5/8 applies stuff out of the box so we can even do tests that t.com and then it should say account doesn't exist so that's some validation it's fine but now if we log in we should expect that okay well we do have a user in our system and we all logged in so this should redirect us to the admin page but the problem is we haven't handled it so it locks us in you won't see it but it kind of takes us to because we don't we don't get an error message it takes us away and then it sends us back because there's not push admin goes there and it comes back immediately because we are going to the server without the without checking if there is a store and the way we need to handle this is in our actual store there is a special action we can say export Const actions equals object and there's a special action called next server in it and this calls whenever the server initializes with a request or some page loads this this book be called on the server side takes two parameters it takes a store and it takes the the request object so I'm just gonna bring out commit and I'm gonna bring out Rick and save that for now and on top of this page we want to import some stuff we want to do a WT decode from JWT decode and we want to also import the cookie parcel module that we got so the first step is to see if there is actually a cookie on the request object so we can just say if there's no request that hitters don't cookie we can just return and this will this won't do anything it will just redirect us back here and then another thing we want to do is make sure that we aren't we actually want to do this first is make sure that this isn't a static aesthetic site so we can do resisted server and process not static we also want to return and then we can start playing with this cookie so we know that if we got to this point that there is a cookie on on the head so what we want to do is we're gonna we're gonna say Const access token cookie or we can just say post equals cookie parser dot parse and we want to pause that Rick thought headers dot cookie and then images to assist on one side and then the next step is we want to create the X we want to get the access token cookie so the access token cookie would be the post dot access underscore token and the reason its access token like that is because in users we save the cookie as access token so just to make sure we can say if there is access token cookie we want to say Oh what we can do is we can just say if there's no because we have to make sure that this exists if there's no access token cookie then we just want to return again and leave this function but then we can say that constic oded equals access to code JWT decode because now we actually we actually have this cookie in its form that we saved it so that's a JSON web token so we need to decode that with JWT decode and then what we can do now is we can say if decoded is the thing we can do a first of all we can do a commit to the store offset user and we want to set that to the decoded or we can do you ID is now decoded dot user underscore ID I don't know why they didn't call it UUID on this object as well but if it's if it's coming from a JSON web token it's not user ID and then email we can just do decoded that he male and save that so now every time a request is made we're checking for cookie if there's cookie we set it in the store and this is being sent from the server so by the time gets to our client the the stores are really populated and this is right when the server is initialized so before anything else happens the server's initialized we set that cookie from we set the user from the cookie so now this user will be available in our store and our middleware is now checking if there's no user Android but now if a truck matches the route and there's a user it's fine we don't have to redirect so this should be enough for us to actually use our application so let's do that let's first try a wrong password again wrong password okay so it's still working and then we can do boss world one two three submit this area to check for them let's first do a refresh unknown actually so this log is coming from the server unknown at mutation type set user and that's because we gave it a namespace of users so we needed users slash so let's try that again we can do taste at test calm and then we could do password one two three submit mutation type global set you know that took me like five minutes to realize but I didn't even see that I try to sit two users slash safe user from actually use the file so that's not necessary I should change it in the actual not serving that that should be users slash safe user so now finally let's try it one last time login we don't have an error but we don't have a redirect either so let's refresh the page maybe try again test that test calm password one two three and submit and there we go we are on our admin route if we go to profile we can visit our profile so what we can do to test this is we can go to pages not index we can go to pages admin index and then in here let's just add an a tag without an href and just say add click equals log out and then just say log out here and then below this is complaining about oh we need one element I hope you three and knocks allows us to use more than one root element but okay so in the script we want to set that method log out and I'm just gonna do it straight from you I'm not gonna do any stores things so I'm just gonna import that Earth module from firebase and that's add slash services slash firebase and then in the logout what I'm gonna do is say oath sign out we can do the async async' so first and we actually need to import our cookie module as well and put cookie from jeaious cookie and then the first thing we need to do is to sign out the user so we can do a wait or that sign out and then we can do a wait cookie dot remove the access token because we don't need that anymore and it's important that we don't send that in the request after the user has logged out and then we can do a hard refresh location dot href equals that so that we do a complete new request from the server save and then reload this oh it's on our admin admin page go to admin and if we do logout it goes back to you and if we try to go to admin it redirects us so only once we sign in you'll be able to actually oops I entered my own posture wrong and again let's try not doing that it's loading you could in this in this section way so this is reload this quickly in this section where the the app is doing the request to firebase you can do a submit and as you submit you could do a load instead so now we have our admin we can go back home and we can also do admin / profile and another thing you could do is if it's quite a bit redundant to make the homepage be the log in page once the users already auth so you know you know normal in a middle way serve another way we can do or route the middle way we can do a Home route and equals just an almost slash so we don't do a regex on this just slash and then we can say if there is a user and route dot path equals home route then we want to redirect to let's say admin because why login the user that's already logged in so you could play with these routes but so if I try to go to home now enter it should redirect me to admin immediately yeah and that works so if we log out it'll take us to home we'd rather go to admin we're safe so that'll be it for today sorry if the video was a bit boring or rushed or not informative let me know what I can improve I'm a bit sick so I just felt like I had to make a video it's been quite a while and I hope you guys have a wonderful day thanks for watching leave a like if you liked it and I'll see you next time [Music] you [Music]
Info
Channel: Kaizen Codes
Views: 15,209
Rating: 4.9702969 out of 5
Keywords: Web development, Software, Javascript, Coding, Manage users Nuxt Firebase, Nuxt Firebase, How to use firebase auth nuxt, Nuxt Authentication, Google Firebase, Firebase Auth, Nuxt tutorial, Nuxt Vue, Coding tutorial, user authentication javascript, nuxt, nuxtjs, vuejs
Id: _-_bz5lH_fI
Channel Id: undefined
Length: 47min 21sec (2841 seconds)
Published: Fri May 31 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.