YouTube Deep SummaryYouTube Deep Summary

Star Extract content that makes a tangible impact on your life

Video thumbnail

OAuth2 using Google, PocketBase, and SvelteKit

Consulting Ninja • 2023-05-25 • 26:56 minutes • YouTube

📝 Transcript (606 entries):

[Music] hello and welcome to my channel thanks for popping in if you're new please like And subscribe for me if you find this content helpful hit that notification Bell so that you don't miss out on the next video comment below with your thoughts or topics you'd like me to cover and check out my website consultingninja.tech with that out of the way let's do some oauth 2 with pocket base Google and smeltkit in this example we're going to have a sign up form a user can fill out the form or click the sign in with Google button if you click that button it will take you to the Google sign in page and if you're already signed into your account you can just select one otherwise you'd enter your name and password and then from there we'll send this information back to svelt kit and svelt kit will send it to pocket base where we'll create a new account if it doesn't exist if you want to see how to do this stick around that's what we're going to do right now so the very first thing that we need to do in order to make all of this work is we have to have Google set up correctly you will have to have a Google account and just type in Google developer console in the search bar and click the Google developer console link that comes up first inside of here you need to create a new project this is pretty straightforward there's no detailed information here just give it a name that you're going to remember the location doesn't matter once you have a project created and I'm just going to use the one I've already created here it'll take you inside of the project dashboard and this is what you'll be presented with now we need to go into the navigation menu and go to apis and services and the first thing that we need to do inside of our project is create an oauth consent screen now I already have one created you can only have one consent screen per project and so I'll just edit this and walk through the steps so you have to have an app name this is what will be presented to your users you have to have a user support email this would be the support email that users would send information requests to you don't have to give a logo that part is optional all of the app domain stuff is is optional and then the authorized domains you can enter in your authorized domain or in this example I just put localhost and leftyourdomain.com if you are using a production app it would be whatever your authorized domain is and then for developer contact information I just have the same email address as the support email address in the next step here is where we need to add or remove Scopes and Scopes are what information your app is going to be using from your users this will all be empty by default so you need to click add or remove and the basic three that you're going to need are the very first three so we need to be able to see the primary Google account email address personal information including personal information that has been made publicly available and then we also need to be able to associate someone with their personal information on Google if you need any other Scopes there's many of them here they're all listed you just select which Scopes your application needs the one thing I'll point out here is that the more detailed and specific and personal information that you need the more stringent they're going to be in their review of your application if you're choosing just the basic three and you're in testing you won't need to go through the review so after you've selected the Scopes that you need then we go to the next step you do have to have test users so in this case I just used myself you just click add users and add an email address in here and then the last step is just a review of everything that you've selected and then you just save it once you have your consent screen done now we need to create some credentials so click on the credentials tab and we want to create credentials and we want to create oauth client ID credentials so here we select web application this name is just a name for you this is not going to be shown to your users you can call this whatever you're going to remember for your JavaScript origins in this case you're going to want to enter a local host 5173 so it'll be slash slash localhost 51.73 authorized redirect Uris this is where Google is going to send a user after they sign into their account or select their account and so for us we'll need to enter we can copy this localhost 5173 oauth and then click create here it gives you your client ID and your client secret these are the two pieces of information that we need to enter into pocket base I'm not going to use these because as it pointed out in the previous screen creating a new client ID can take anywhere from five minutes to several hours and so for the sake of this video I want to make sure that things are going to work but what we need to do next is inside of your pocket base dashboard you need to go into settings down in the authentication area select auth providers we need to enable Google and then from that screen the client ID goes in here so you take the client ID from Google here and enter it in to the client ID section here in Pocket base and then we need to enter in the client secret from this screen into the client secret section here in the pocket-based dashboard and then you just click save changes so that's all the configuration that's needed in order to make this work with Google and with pocket base now the rest of the magic is going to happen in svelt kit which is going to create our UI and run all of the pocket-based commands so inside of our source code our spell kit source code the very first thing that we need to do is let's create a hooks.server.js file I already have one here it's empty we'll fill it in together and what we need to do is inside of our hooks file we're going to fire up a new instance of pocket base inside of our hook so import pocket base from pocket base and then we're going to export const handle and this is going to be async of course and we need to pull out event and resolve this is actually going to be a pretty basic hook here and what we're going to do is we're going to do event.locals.pb is assigned new pocket base and then I have pocket base running locally here at 127.0.0.1 Port 8090 and then we just need to resolve so response equals oh wait resolve events and then return the response so now we're going to have one instance of pocket base available in all of our other pages so give that a save next we need to have a sign up page so I'm not going to go into detail into the markup but I do want to show you inside of the markup for the sign up page we have two forms one is the regular sign up and down towards the middle of this file is a second form and what's important here is that we're sending this form to the oauth 2 action if they choose not to register using the regular form and they want to instead use Google then we're going to Ping a separate action that is what is important from the markup file the rest of the magic for this section is going to happen in our plus page.server so inside of our plus page dot server for our sign up page let's go ahead and import redirect we are going to need to be using redirect and not the type the lowercase R redirect the actual function and then we want to export an empty load function I'm not going to make use of this for the sake of this video but you probably would want to in a production application you probably would want to use this in a production application to get all of the authentication methods and pass those to your page and then only render out the ones that actually exist I'm not going to get into that I'm just going to return an empty object I did want to make this available for you guys though so there it is if you want to do that what we do need to do is export const actions and sign up this is the regular sign up uh we'll just leave this blank as well because we're not going to actually do anything with that in this video so we'll leave that one empty but we need an o auth2 action and this will be an async action and here we are going to get into the magic so we want to pull out cookies URL and locals so the very first thing that we're going to do inside of here is let's get our authentication methods these are the methods that pocket base is saying are available so auth methods equals oh wait locals.pb dot collection users and then do a DOT list uh methods just like that and if you want to see what comes back let's do a console.log and we'll just console those out so save that and in our application go to the sign up page and then click the sign in with Google button and this is what comes back from the list auth methods function we have the username and password and then here we have auth providers and this is a list of all of the providers that pocketbase has enabled with the name a state a verifier a challenge what method is going to be used and then an auth URL so that's what comes back in that function so what we need to do is now that we know what methods are there we need to double check in our action we need to make sure that this went through successfully so let's just do it if not off methods so if there are no auth providers what we'll do is we'll return an object that says auth providers empty and then outside of that if next here we get to where we're actually going to be doing some cool stuff the very first thing that we need to do here is set a redirect URL that we're going to send with this request to Google so const redirect URL and we're going to use the backticks this will be dollar sign URL dot origin and then outside of the brackets slash oauth so this is telling Google where we're going to redirect and Google is going to check that when it gets it and then we're going to do a const Google auth provider and this is going to be auth methods dot auth providers and we only have one here so we can just pull out the first but you could also go through them and find the name that you're looking for but for us it's just going to be one auth provider it's going to be Google and so we won't do that here but what you would want to do here if you have many of them is just go through and find the one that the user chose then we need to do a full redirect so auth provider redirect this is going to be another let's use the backticks again here this is going to be a couple of things put together so let's use the back ticks again and the first thing we need is dollar sign brackets Google auth provider.auth URL this is that giant string that we saw and then just after that dollar sign bracket their redirect URL which is what we just put together now the next two things that we need to do are when you first fire up this list all methods function what it does is it generates a state and a verifier for each auth provider we need to save both the state and in this case also the verifier to cookies and then we'll check the state later and we'll have to use that verifier later because every time you run list auth methods it generates a new one this actually stumped me for a little bit but I was able to figure out what was going on so we need to save the state and this will be Google auth provider.state and verifier this is going to be Google auth provider.code verifier just like that and then we're going to set both of those in cookies so cookies dot set to state and cookies dot set verifier to verifier and then the last thing that we do here is we throw redirect and this is going to be a 302 and then we send to the full auth provider redirect which is the specific URL for Google with the redirect URL that Google is going to check so let's go ahead and give that a save now the next thing that we need to do is we need to create a route for receiving this we told Google and we are sending to Google to send this back to a separate route that's going to be the oauth route so create a new route called oauth and inside of there just a plus server.js and this is going to be a git route so first we need to import the redirect again and then we're going to do an export const git is assigned async and we'll pull out locals again and URL and cookies now here we need to pull some stuff out of a few different places before we start pulling out information though we need to set up our redirect URL again because this gets checked redirect URL equals the same thing as before backticks dollar sign brackets url.origin slash oauth then we need to pull out the expected state this is what we saved in the cookies so cookies Dot get state and then here's the one that's thumped me for a while and this is the expected verifier and that's cookies.get we saved that to verifier now the reason why this stumped me is because you should be able in theory well we could have pulled out that instance of pocket base from here and ran the list auth methods function and pulled out the verifier from there but looking at the pocket-based documentation I realized that every time you run that function it's generating a new verifier and so I was getting to this step and the state was matching but authentication was failing and that was the reason why so I worked through the problems so that you guys don't have to make sure to save your verifier and send it through cookies to the receiving route so that you can use that one that was generated with that state all right so now we need to pull out the state that Google sends back so const State equals a weight URL dot search params.get so Google is going to send back a state in the URL params and then we need a code this is the code that Google is sending await URL Dot searchpraems.get code now if you wanted to this could be I'll add these in here for you guys these might be good places to do some console.logs if you're having issues so URL dot search params so that you can see what's coming back from Google and then we'll add one here a console.log of the expected expected state and that will be expected state and then here after this after we pull out those params let's do a console.log return State this is what's coming back from Google and then this is the returned code from Google that way you can see what's coming back if you run into any issues I want to make a comment here as a side effect of this next function so the next thing we're going to do is we're actually going to run to that list off methods again just to make sure that pocket base is recognizing this as a legitimate authentication method before we even attempt so as a side effect this will generate a new code verifier hence why we need to pass the verifier back in through a cookie all right and then we're going to run the list auth methods again so const auth methods equals await locals dot PB dot collection and we're selecting users dot list auth methods and we can just do some more error checking here so if not auth methods dot auth providers then we can do a console .log no ah providers and we'll just redirect back to sign up so row redirect 303 slash sign up and we probably should put a question mark there because if it doesn't come back we don't want to completely error out and then pull out the provider const provider equals auth methods Dot auth providers Subzero again if you were using a whole list you would check to see which one is coming back you'd probably put that in a cookie or a param and then if the provider is not there so if not provider then we'll do a console.log and say provider not found and then again we can redirect back to sign up so we can copy this now we need to check the state so if the expected state is not equal to the state that Google sent back well then that means somebody messed with the interaction and you should not accept it so we'll do a console.log and say returned state does not match expected and if you wanted to you could put the expected state and the state so you could see the difference and then again we'll just redirect back to sign up now here we're going to do the actual attempt to authenticate using pocket base so let's do a try we're going to do a weight locals.pb dot collection users and we're going to do Dot auth with oh to code this is the newest way of authenticating using oauth with pocketbase they have a version that you could run from the client I'm not a fan of doing things in the client these days I used to do everything possible from the client now I'm the opposite and try to do everything from the back end it just gives you more control and a little bit more Security in my opinion but that's just me so this is the way of doing it from the back end so what we need to pass this is we need to pass the provider dot name the code that we pulled out of the params the expected verifier that's the one that we sent back and the redirect URL this needs to match what was used in the beginning and optionally just after this also you could pass an object let's go ahead and do that let's add a name in here my awesome user and this is going to create that user if it doesn't exist and in the process you can pass in this information it'll set those properties on that user when you create it all right then let's catch errors and just do a console .log say error signing up with oauth2 and then we can just print that error out and then lastly outside of the try catch we're just going to redirect back to wherever you'd like uh for my sake I'll just redirect back to the home page just to make things easy all right to give that a save now in our application we can go to sign in with Google and we can select our account I'm already signed into my Google account so I can select that and it's going to send us back to the auth route the oauth route all of our functionality there is going to run we're going to take that expected State and compare it we're going to pull out the code and then we're going to Ping our pocket base with it and when pocket base gets it and sees that that user doesn't exist pocket base will add that user into your users collection so if you select users from your collections Tab and hit the refresh button there you can see our user has been added to our user collection with an ID we did not provide a username so pocketbase gave it one there's the email address from Google and the name that we added in that optional object when we did the authentication so there you have it there is oauth 2 authentication using pocket base Google and felt kit I hope that you found this video helpful this was really fun if you enjoyed this please like And subscribe comment below with your thoughts and as always have a great day