SvelteKit Session Authentication Using Cookies

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're going to look at how to do authentication with sveltkit hello hello youtube my name is braden gerard and today we're going to look at how we can do session based authentication using cookies in sveltkit so we're going to go and take a look at how we can implement that both on the client side as well as the server side of sveltkit using pages and endpoints so that we can look at how we could set up pages in our application to only be accessible to users who are authenticated so we'll build a very simple login and register form and then we'll show how you can either access a page once logged in or have an access denied air if you're not logged in so let's jump into the code and take a look okay so we're going to start a news felt kit project so we'll make a directory for it let's call it felt kit auth and we'll go into that directory and we'll do an npm in it spelt at next and it's going to ask do you want to install the package yes do i want to use typescript no yes yes yes yes lent no pass prettier now we don't need okay so now we're going to do an npm install just to install all the defaults felt kit components that we need and we'll just open up our project over here so we will go to our sveltkit auth project open it up and the first thing we're going to do is we're going to go here and we're going to set our server side rendering to allow external dependencies we'll save that in our felt.config file and then we'll go to our package.json and there's a couple different modules that we need to add to this project we're going to be using redis as a database just because it's very straightforward and simple to use uh just a key value store so i don't want to focus too much on the database here so let's just install the uh npm module for that so we're going to use an npm module called tedis tedis so npm install tedis just a very simple redis client or module for node and then we will also install the cookie module so that we can deal with our cookies so npm install cookie and then we will also install a string hash module because we're going to be doing some hashing of our passwords because we don't want to save our passwords in plain text in the database we're going to install string hash and we'll also install one last module called uuid which will allow us to generate some unique ids for our users so with all those modules installed we should have everything that we need to set up our authentication here so let's just close this now we're going to start up a redis database here on our local host so i've already installed redis that's not going to be part of this tutorial but i'll just start up the database here so that we can access that redis database okay so let's go over to our project and start sort of setting things up here so in our routes folder we will not be using a layout so let's just get rid of the layout for now we don't need a layout for this project we will go into our index and we can pretty much clear everything out of here we don't need to really use any of this we could keep some of the css i guess we'll keep the text align center sure the h1 sure wait we can keep the css that's fine but we'll clear out all of the html this out we'll also clear out the component that we're importing and we'll just call this i don't know authentication with cookies in spelt kit okay and then we will scaffold out uh our components here that we're going to be using so in our lib folder we'll make a new uh component and we're going to call this component login.spelt and that'll handle our login and then we're going to make one another component called register.spelt which will handle our registration to create an account we'll get rid of the default counter component here and we'll go back and we'll just import those two components into our main app here so import login from dollar sign lib forward slash login and then we'll also import register from dollar sign lib forward slash register felt um and that should be it for now okay um now we will go down here and we'll just put these two components in the page so we're just gonna have them both showing at the same time on our homepage just a login box or a register box just for the purposes of this tutorial we're going to make an event listener on them so whenever we successfully log in or whenever we successfully register something happens so let's say that when we successfully log in we're going to redirect to them to the profile so they can see their profile information well a very basic profile so let's just do an on success event listener and we'll we'll create that in a minute on the login component that will redirect to profile and for registration we'll do the same thing so for register we'll say on success we're going to just redirect to profile because we're not going to be verifying emails or anything like that so once they've registered we'll just say that they're also authenticated so that they can go straight to the profile after they register okay so both the redirect to profile so let's create that function right now redirect to profile and inside of there we just want to send them a redirect to the profile route okay so let's first create the profile route so we'll make a new folder here called profile and inside of that folder we'll just create an index.felt and we'll just put an h1 in there for now that says profile just so we know that that's the profile page okay and if we go back to our index here now this is how you redirect on the client side you can import this go to method from the special app forward slash navigation file that comes with felt kit and from there we will import go to and we can use go to like this we say go to and then the path that we want to go to so we're gonna say forward slash profile okay so then whenever we call our redirect to profile method it will go to the profile on both of these when the on success event gets fired let's go into our components now and we'll create them quickly so for the login component we want to first we need to have an event so that when the login succeeds it actually calls that on success so let's import create event dispatcher from svelt and we will create a dispatch which is equal to the create event dispatcher method um and then we're gonna dispatch once they log in so we'll do an async function log in and somewhere in here we're gonna call dispatch so let's just keep that on the burner back burner for a minute and we'll initialize our email and password variables here okay uh so that we can use them in our template and get those and then inside of login we'll use the email password to register or to log in our user so inside of our actual html we need what we need a title so let's just call this login h1 login we need an two inputs right so we need an input with the type equal to email and we need to bind the value of that to our email and we'll say we'll just give it a placeholder so that we know what we're going to put in this input field uh placeholder of enter your email and then we'll close that input and then we'll do one more input with the type equal to a password and we'll bind that value to our password variable placeholder equals enter your password and we'll close that input and then we just need the button to log in so we'll say button and on click so we're going to bind the on click listener to that button to the method login and put login as the text for that button okay so now we've got our login component here we'll write this login logic in a second here so let's just save this and let's just copy most of this over because we're going to do very similar stuff on the register component so we'll paste this into the register component for now and the only thing we're going to add to the register component is we'll add a name so that they can when they register they also input their name we will change this to be register because we want to call register when they click the register button so we'll change this to say register that's going to call the register method and then we need a third input here that is the name input so enter your email we'll put that in the middle we'll say name here bind it to name enter your name and this is going to be a text input okay so we have the three inputs on our register and we bound it to the register button so so far the that's pretty much the same as our login just with that extra field um now where it's gonna differ is in our in our methods here register and login what we're gonna do so let's just save this and let's go check out our uh project really quick make sure it's looking how we want it to look so we have our index.felt here our main page with a login and a register component that both call this on success event listener which we haven't implemented yet but we will inside of these methods and they should have the login should have two fields and the register should have three fields down below so let's just run our project so npm run dev and let's go to localhost 3000 in our browser browser there we go localhost 3000 and what are we getting here failed to load source lib register.register.felt did i type something wrong there um yep double register here so let's save that and let's go back and there's our page uh very small let me zoom in a bit for you guys holy that title okay so let's just make that title a little smaller let's make our h1 uh let's go to rem and we'll save that and we don't need a four ram margin here let's do a one rem margin save that oh look at that now there we go that's a little better okay so we have a log in whenever i change the title for a register so it should be login and register perfect okay so we have these two forms one to log in one to register now we need to actually implement what they do when we click the login or click the register button so if we go first let's do the registration first so if we go to the register uh method here what we want to do is we want to send a request to our server to our server endpoint which we're going to implement in a minute and we'll call that server endpoint register maybe we'll put it under a directory called auth okay so in our routes folder we make a new folder called auth and in that folder we make a new file called register.js now this is how you make endpoints or server side routes for spell kit you make a js or ts if you're doing typescript file and you implement some special functions in there which we'll do in a minute um that will receive the request okay so that's going to be our path to our server route or our endpoint or api endpoint whatever you want to call it um so in our register here we'll say uh async function register we're going to do a const result is equal to a weight and fetch and then we want to fetch that route so auth forward slash register okay and then we will send it the method of post because we want to do a post request we will give it a body which is going to be the information that we're sending from the register page now we want to stringify that because we want to make sure that it's properly encoded to go over the wire to the server so we'll stringify that and we'll pass in the email the password and the name those are going to be the items we pass in the body of the request and then we also need to set the headers on the request to be of content type um application json because we're sending this as a body as json data we're not sending it as a form request so we'll say application forward slash json and that should do it for our authors register post request now when we get the result back from that we're going to say if the result is okay okay so if we get a 200 response back from our server then we want to dispatch a success message uh which will call our uh our success event listener here and redirect them to the profile okay so we dispatch success um otherwise if it's not okay then we would want to give an error right so we'd say else and then we're gonna actually let's set an error variable here so let air and then we will say air equals and air occurred we'll just have a generic air for now now we also want to surround this with a try catch to make sure that everything succeeds here on this await so we'll do a try and we'll tab all this in and then we'll have a catch and we'll catch an error here we'll just console.log if we get an error and we will set our air message equal to just in an error occurred again and then at the top here we also want to set our air equal to undefined just so that if we have an error but then we the next request exceeds the air doesn't stay there uh or it can reset it for whatever the next error is and then we're gonna go down here and under i guess above the registration button we'll put our air in so we'll say if there's an error so if it's not undefined and we'll just say print out the air here and close that if now we want to do the same thing for our login components i'm going to copy this over really quick to save time and we also want to have an error variable here and then we'll set it to undefined right away when we call login again we're gonna have a try catch and we'll console.log if we get an error in the try catch and we'll set air equal to air and also area equal to an air occurred now normally you'd put better error messages but just for the purposes of this i'm just going to have a generic error message um okay so login is or sorry register is done i believe for now until we implement the server side routes for it um so let's save that and go back over to register or sorry login mix them up we just finished register go back over to login and let's implement our fetch here so in our login we're going to implement a fetch method as well but this fetch will just have to send the email and password so we're going to say const result equals await fetch we're going to fetch forward auth forward slash login and we need to make that login route so over here under auth we'll make a new file login.js and in that fetch to login we want to send the method type of post because it's going to be a post request we want to send the body of a json.stringify the object with email and password and then we want to also send headers with our content type that to application json so that it knows that we are sending a json body and not a form uh that should be it for the login let's just close that and then let's again check if our result comes back as a 200 so res.ok then we are going to dispatch success and otherwise we are going to do a air equals an error occurred and that should do it for the login okay so we've implemented our login and register components that send our email and password for login and for register send our email password and name to the server and now we need to implement our server side routes so let's implement our login route as well as our register route so our login route will be uh i have to import a couple different modules here so we're going to import string hash okay because we need to uh hash their password when we compare it with the password in the database because we're going to be hashing it when we actually register the user we need to import oops import our cookie module because we're going to be creating a cookie for the user when they log in and sending that cookie back to the browser we need to import the uuid module so that we can generate the id for the user or generate a sort of generator unique id for the cookie that we're going to send to the user so that's the uuid and then we're going to also import import our tetus so that we can set up our database client oops hold on so learning this new keyboard it should be a little quieter for the recordings for you guys but to remember where all the keys are import tedis okay so let's initialize our database right away and then with the host of localhost and the port of 6379 which is the default port now i didn't set a password on my database so we don't have to have a password here but you could add the password property here as well if your database did have a password uh now we're going to do an export so this is the special function i was talking about that your server side route needs to implement export async function and if it's a post it'll accept post requests you can do a get function here to accept get requests you can also do a update and you can also do a delete so it's del for delete because the delete keywords reserved in javascript so del so we're going to do a post and inside of the post request we're going to put the body or we're going to destruct deconstruct the body that comes from the request object in the post and we want to use that body to get out our email and password okay now i'm going to stop here for login and we're going to register first just so that we can register user obviously before we log them in just makes more sense conceptually to me so we're going to copy all this over though because this is all going to be sort of identical code between login and register we need to do all this in register as well so let's go back over to register paste that in there and then we're going to inside of register we're going to go const user is equal to json dot okay so we're going to get that user from our redis database so db.get and we're going to look for the user by body dot email okay um now i'm doing json.parse on the response from the database because when we save out to redis we're going to be saving everything as a string okay so um we save our objects out as a string to write us because redis expects string as the value for a key value pair so we're gonna do a json.stringify when we save to redis and we're gonna do a json.parse when we get our result from redis so await db.get and we're gonna the key is gonna be the user's email for our uh for our users so we're gonna check to see if there's a key that exists with the email that's being sent for the login okay so that we can actually see if the user exists or not sorry for logging for the register so this is registered remember we're going to check to see if a user exists with that email or the register because if a user does exist we're not allowing them to create a duplicate user right so if the user exists with that email in our redis database then we're going to return a response so when you're doing an endpoint and felt kit you need to return well you don't need to but there's optional things you can return and one of them being the status so we're going to return a 409 because that's a conflict the user already exists and we're going to send in the body of the response we're going to send a message we'll just say and we'll say user with that email already exists okay now if the user if we don't get a user back that's good that means we can register with that email so we'll do an await db.set and we'll set a key of body.email with the value of json.stringify and inside of that object we're going to pass the email the body.email we're going to pass the password now we don't want to pass the password in plain text so that's where our string hash module gets used we're going to save it as a hashed version of the password just in case anybody ever got into our database and we're going to save out the body.name okay so the user's name and that's the object that we're going to save out as a string to our as the value in our regis database for the key of body.email okay now we're going to generate a cookie for them because the user just registered successfully so let's generate a cookie and send it back so they can be authenticated so we'll send a we'll create a cookie here const cookie id or make an id for our cookie story first and we'll make that equal to the uuid version four so that'll generate a unique id for us using that uuid plugin which is a long string of characters and then we're going to say await db.set so now we're going to save out again to our database we're going to say about the cookie id as the key okay and then the value that we're going to save out is going to be just something that we can identify that user with so we're going to save out their email so email body dot email okay so this is how we know if the user's cookie's valid because if they have a cookie with the same id that they that exists in our redis database then we can grab their email and pull the user's information from the email key so we have that set now we can actually send that cookie back in our response so let's just create a header for our response here first i'm going to separate that out since it's a little going to be a little longer and we're going to set the cookie in the header and we're going to use that cookie module now so cookie dot serialize okay and then we give the name of the cookie so we're going to call it we'll just call it the session id and then we're going to set the uh what is the actual id of the cookies we're gonna say cookie id okay and then what are the options on our cookie so we're gonna put some options in here or a cookie scroll down here sorry okay so the options for our cookie are going to be that is http only so we're going to set that to true it also should have a max age so how long do we want our cookie to be valid for we're going to say one week so that would be 60 times 60 times 24 times 7. so that's one week of time uh same site uh we'll just set that to lacks i don't need this to be super secure for those demo purposes and then the path that we want our cookie to be valid for is going to be root anything after root so that's how we set our cookie in our header that we're going to send back in our response so now we can send back our response so we're going to send back a response with a status of 200 because they successfully registered we're going to send back headers which is this object for our headers and then we're going to send back a body of a message and that message will just be success okay save that so our register route should be implemented now so let's just go and test that out really quick so if we go back to our browser and we uh let's inspect here for a minute i don't even have my developer tools on i just got a new mac and as you can see not much is set up yet so let's just turn on my developer tools turn on developer tools there we go okay now i can pull up our developer tools here so if we look in our browser if we go to the storage tab so this might be a little small for you guys if we look under cookies there's nothing here okay so let's do a login so we'll do a give an email so let's just give my email and then we will do a name and then we will do a password so i'm just going to do p-a-s-s-p-a-s-s-w-r-o-t password register okay and look at that we get redirected to the profile so it looks like everything worked if we look back in our cookies here we can see that we have um should have a cookie oh yeah here it is the cookie with the id okay so there's our cookie with that uuid that i generated okay um in our storage now so the cookie's there the cookie got saved in the browser and the profile came up um now we haven't checked yet we just redirected to profile so really profiles not actually blocking me from anything right now and we'll look at how we can we can send them to an unauthorized page if they're not authorized because technically right now even if i didn't have my cookies so let's just delete the cookie out of the browser here there's my cookie session id delete even if i had that gone i could just refresh and hit profile right it's not a protected route right now at all and we'll show you how we can protect that in a minute so we have register working good let's go back and quickly implement our login server side logic okay so on login we want to sorry this is the component we can close that we're done with that we're done with register profile we're also done with our index i believe we're done with our config let me just clean up a little here okay so our profile our login route and our register we just finished implementing okay so let's go to login so for a post request to our login route we are going to do similar stuff we're just not going to actually create the user um so we're going to so let's actually copy over some of this code so we'll copy over the cookie stuff and the response from my registered route just to save some time because we're going to be doing this once we successfully log in as well so let's copy that that'll be what we do after we successfully log and then we will also do a get to get the user because we want to check if the user exists when they log in if they don't then you know the email that they provided wasn't even valid but then we also want to check if the password matches and we'll do that in a second so let me just see here we do want to get the user by their email when we log in so perfect so we'll take this over to the login okay so we try and get the user by the email they provide for the login if the user doesn't exist in this case then we're going to want to return a 401 because they we couldn't find the user so user with that email does not exist now that's not really secure to tell the user that because if they're trying to brute force they know that it's the email that's wrong and not the password so we would be better to say a user with that email or password or sorry we just say incorrect email or password just so they don't know which one they actually got right or wrong just a little more secure for login now if the user does exist that means okay they exist but we don't want to authenticate them yet because we don't know if they actually got the password right obviously that would be very insecure so we're going to say if the user.password is equal to if the user.password hashed right so if the user oh no the user.password that we're getting so this user's password is going to already be hashed right because it's in the database so we hash it before put in so if the user password that we have in the database is not equal to uh then we're going to string hash the password that they sent us from the client because that one's not hashed yet so if we hash that password um then we're going to check if the hash matches the stored hashed password or doesn't match in this case and if it doesn't match then we're going to return right away and we'll return a status of 401 and a body of with a message of uh unauthorized okay so that handles if they're not logged in and then if i mean that handles the passwords not crack now if it is correct it will get passed here and it will generate the cookie for them it will again save that cookie to the database and it will send the cookie back so this is all the same pretty well and yeah so that should be it for login so let's save that and let's just go and test out our login really quick so if we go back here and let's just open up so since we don't actually we aren't actually checking if this is successfully well yeah if it's successful it should it should hit the 200 so actually we can test this it should redirect your profile so we've already registered bradenjard icloud.com so let's just put in the password of passwrd i'll save that in my password manager and log in and we got an ar password is not defined on routes off login line 20. okay so it looks like i made a typo somewhere um let's go back over and look at that auth login line 20 uh line 20 user.password eassw okay so we're looking for the user by the body dot email maybe we're not getting the user let's console.log out here what we're getting for user actually hold on did i delete i know that should be fine okay let me let's do this one more time okay the user is there uh the password that's the hash password um so password is not defined oh it looks like we're getting so we have the hash password p-a-s-s-w-r-d getting the user offlogging line 20 okay let's see did i miss something there oh it's probably this password and that's because it's not defined i need to say body.password so body.password there we go so we get the password from the request that should fix it up for me and then we're going to say and p-a-s-s-w-r-d log in and it looks like it succeeded because it redirected us to the profile okay so now let's actually check right now we're just showing the profile irregardless of whether they're logged in or not right um so let's log the user out now so we're not going to build a log out for this we'll we'll do it the developer way and we'll delete the cookie out of our storage here okay so if i refresh now nothing's going to change because currently we weren't even really checking the cookie we were just setting a cookie after we logged in right so if i go to forward slash profile right now it's still going to show me my profile so let's fix that first let's redirect to unauthorized if you shouldn't be allowed to access the profile okay so we'll go back over to our code and we're going to create this special file so this is the magic of session authentication in sveltkit there's this file called hooks.js okay and you just create that inside of your source folder so inside of the source folder we're going to make a new file called hooks dot js okay and inside of that hooks.js file there is a couple different methods you can implement and we're going to look at the get context method and the get session method okay so in here we're also going to need our cookie module our this cookie [Music] from cookie and we're going to need our database so that we can check the cookies in the database we're going to import teres from that is from tetus okay and then we're going to initialize a db and inside or initialize a db connection i should say and we're going to connect using the host of the localhost and the port of 6379 that default board again i have no password on my database and then we're going to export async function okay and get context so that's the first special function we're going to use now this function gets called every time a request gets sent to sveltkit and insi and this inside the the parameters that could pass to this function um in get context we have a headers that we can destruct from the request that comes in here so we get the headers from the request okay and then we are going to get the cookie out of that header because i've set cookie in my browser when i make a request from the browser it sends the cookie along with it so inside of here we're going to say const cookies equals and we'll say cookie dot parse so we're going to look for a cookie in the header so headers dot cookie and if we find it great and if we don't find it we'll just set this to the empty string okay so we've tried to pull our cookie out of the header now so using that cookie module so we should have something inside of cookies with the name of session id if it actually got our cookie back so we'll say if cookies the cookies will exist because i'm setting it to an empty string if it doesn't exist so we'll have a value here we'll say if cookies does not contain session underscore id okay then we're going to just return right away and we're going to return authenticated an object with authenticated in it set to false so this object that we're returning is the context that gets passed to our server uh to our server endpoints um it's also the context that gets passed to uh our get session method which we'll implement in a minute and this context is sort of like server side only so nothing can see this so you can put stuff in here that's okay to be a server side only and then when we get implement the get session method in here that is what's going to be sent back to the client so that's what we have to be careful of what we put in there so for now we're going to say authenticate as false if they don't have the cookie if they do have the cookie then what we'll do is we'll get the user session from our redis database okay so we'll do json.parse the await db.get and then we're going to get from the db so cookies dot session id okay so that's that uh uuid that we generated remember and we stored that as the key for our cookie that we stored in the database with the user's email inside of it so we'll get from our database that key and if the session id from the cookie exists in our redis database which it should if the cookie's set in the browser um then we will say so we'll just double check that it does exist and if we do get it back then we will return again a new context this time with authenticated set to true and an email which is the usersession.email so we'll store the user's email in this context as well because we have that from that session that we stored if the user session doesn't exist for some reason in the database and the cookie is set then for some reason their cookie is no longer valid so in that case we'll just return authenticated set to false okay so we either get an authenticated true here or authenticated false and if we get an authenticated true in the context then we know we'll have an email available so this gets passed along to our endpoints as well as the get session now the get session is what we set up to be sent back uh to our client inside of the session object on the client so we'll export the function get session okay and inside of there then we can basically return what we want back to the client so get session takes a parameter takes the request parameter we're going to pull out of that the context okay and from that context we can pull out any of this info that we just put into the context so we're going to say if context dot authenticated so this is where we only want to send back uh what we want to be seen on the client so if the context is not a context authenticated it doesn't is not so if it's not authenticated basically then we'll send back we'll just send back an object to the client so the session object that we're going to send back to the client will just be a return object of authenticated is that to false or not false i guess we could put false there or we could just say context authenticated send back the same value [Music] but if it does exist so if we get past this then we'll return a session object with authenticated set the context.authenticated again and a email of context.email so we'll just send the email back to uh the client um so we have the email and we have the these um we have that the session is authenticated to true so this is what comes back in the session object we'll save that okay so we're sending back the authenticated is true and we're sending back the email so now that we're sending back authenticated true and email we can actually decide what we want to do based on that session object okay so this should come back to the client now and we can make decisions based on that so if we go to our profile and in our profile we open up a script that runs before the page is loaded so that'll be context equals module and inside of there we're going to do the export the async function sorry so export async function and that's the load function okay and inside that load function we can get the session as uh that gets passed to it and that's that session that we just set returning from the get session method on the server so we can get this session now and we're going to say if the session dot authenticated okay so if the session is not authenticated then we want to return a status return an object with the status set to 302 which is a redirect and we're going to say we want the redirect to go to forward slash off forward slash let's say unauthorized okay so we'll make that route on the client side and basically in this load function if you return a status of 300 status code with a redirect it will automatically redirect the client when the page loads to wherever you send the redirect so let's go into our routes here make it or in our auth file in our routes and make a new folder and we'll just call that unauthorized and inside of there we'll make a new file called index.felt and we'll just say we'll just make an h1 in here saying unauthorized save that and if we go back over here and save this now if we're not logged in we should be redirected to an unauthorized page when we try and visit profile if we are logged in so i guess we don't need now so we can just go after the if here and if we are logged in we're going to return a props object okay which will get exposed to our page and in that props object we're going to return the email that we are authenticated with just so that we have the email on the client so that we can do some requests for the profile info by the based on that email and so we get the email here and then that means that we can set up a script that runs and on the page and we can say export let email so that we get that as a props and we can uh use that email to make a request now currently when you're making requests um there's a bit of a bug when you're making requests and your cookie doesn't get passed in the request but if we do it in the on mount on the client side it will work for now so we're going to make an on mount uh call here so when our page first mounts to the dom then we will make an async request here we're going to say const result is equal to so when our profile page loads we're going to fetch the user profile okay so we'll fetch forward slash user and that'll just be a get request so we don't need to send any data there and we will then store the user inside of we'll get the json body from the user and we'll store that inside of a user object and then we'll just set a name equal to user.name okay so let's make a variable in here called name and i'm just showing you how you can get some data back once you're actually authenticated from from routes that would normally you need to be authenticated for okay so we're going to get the name from the user profile on the server and then over here we'll just say in the page we'll say hello and then the person's name you are logged in with the email and then we'll just give their email there that we got from the session so you can get data in the session okay so you can store info in the session there's one way or you can make a request to the server and because you have your cookie and this and your the server will authenticate you you can send back uh that user data so let's create that user route okay this is the last route we have to make so let's go inside of our routes make a new folder called user and inside of user we will make an index.js so that we can just request forward slash user and in here we will just import our tetus from tetis so we can access our database and we'll do a const db equals new tetus and inside of there uh we will set the host i've done this three times now you think i'd remember what i'm doing to local host and we set the port to the default port of 6379 okay that opens up our database connection and then we'll export async function and this time we're going to do a get function because it's just a get request we pass in that context that we're setting up in our get context method inside of hooks.js and we're going to use that context to make sure they're authenticated right so we're going to say if context dot authenticated now remember this is server side only this context here so this can't be tampered with from the client so we know that if context dot authenticated is set to false in this case then they're not authenticated so then we're going to return a object with the status of 401 unauthorized and we're going to send in the body a message of unauthorized and we're going to set the uh that should be all we need to do for this yeah as we return a 401 if they are authorized then i'm sure we'll go to the database uh we'll do use json.parse and we will await db.get and we'll use the context.email so again that was that email was set on the context object in get context that was server site only based on the cookie so we know that's the proper email that we should be accessing and then we will check if there's something there and we'll parse it to a user object if it's there which it should be we could we could handle if it's not there so we'd say if the user doesn't exist so if there's not a user or there is not a well if there's not a user that's fine um then we will return a status of 404 not found and we'll just return a body of yeah body with a message inside of it saying user not found this should never happen but we'll put it there just in case and then otherwise we found the user so let's delete the user.password okay we're gonna take the password out even though it's hash we don't wanna send that back to the client um so we're gonna delete the user.password even if it is hash you don't want something back to the client right because then they could use that to check with the database i mean it wouldn't work but it's sort of insecure to send back the hash password so we don't really want to do that so we'll delete the user.password and then we'll return a status of 200 and we'll send back to the body which is the user object and that should be it for our forward slash user call to our server endpoint so when we get the user back we parse the user from the json and we get that user object we get the name out of that user so user.name and we show the name on the profile so if i go back now and test this out so we'll just clear out our cookies just so that we can start fresh and we'll delete out that session id and then we will log in log in and as you can see once we log in with our cookie uh we now have hello braid and you are logged in with the email brayden gerard icloud.com so now i'm getting my profile information now if i were to go back to that page and if i were to clear out my cookie again and let's just try and navigate to the profile page i'm going to be redirected to this unauthorized page now even if i was since its client even if i wasn't able to intercept the data on the profile page before it redirected me here it's not an issue because my request that i'm making to that profile page so if we go and look at our profile page here in the on mount when i'm requesting the user data here on our server side route for that we're checking if the context is authenticated using that cookie right so if they're not authenticated it's not going to send them back any data so they're just going to see an empty page so the only way that you actually get that data on that page is by logging in with your credentials okay so that's how you can do cookie based authentication or session authentication in spell kit now there does seem to be a little bug the odd time here where my authenticator comes back false the first time i hit the profile when i log in and then if i go to forward slash profile it's authenticated okay so i'm not sure if this is something specifically with uh felt kit at the moment because you can see here i get an authenticated fall straight away but then when i refresh profile i get authenticated true so there's a bit of a race condition here going on where sometimes my session's not set before the redirect happens or before the page loads um so i'm going to look into that and i'll drop it in the comments on if there's a solution to that or maybe i just did something wrong but this is how you would implement cookie-based session authentication in sveltkit thanks for sticking with me for another one of my youtube tutorial videos today we looked at authentication with sveltkit and if you enjoyed this video make sure to give it a thumbs up so that youtube knows that others should be watching this video as well and if you really liked my content make sure to subscribe to my channel because i'll be releasing all kinds of tutorial videos in the future and more content on felt kit for sure thanks have a great day [Music] you
Info
Channel: Brayden Girard
Views: 9,539
Rating: 4.9612904 out of 5
Keywords: web development, sveltekit, authentication
Id: bG7cxwBMVag
Channel Id: undefined
Length: 56min 3sec (3363 seconds)
Published: Fri Apr 02 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.