Implementing User Authentication With Node JS and PostgreSQL

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome back to the channel so today we're going to be building a no login app it's basically a mode app which is connected to a PostgreSQL database the database is used to store user details it's their names email addresses and passwords users can log on to our app and if they're authenticated they'll be redirected to the dashboard they can also register and then anything on this form will be added to the database it goes through many validation checks as well just to show you the database tables we have in Postgres see the application area currently has four users so you can see it stores the name email and the hash password you can see here so it's nice and secure we use be quick to hash these passwords just to show you the app so if we register a new user just like Charlie and then we'll say charlie no calm and then password okay possible that match so that's an example of the form validation to go again okay can see we're now registered please log in and then if we check our table just to make sure he's been added you can see we have a new user Charlie edit there so if we tried some logon and you can see we get rid of register dashboard where it says hello and the user again in for offense kated and we try to go to the login bar we get redirect to the dashboard same with the register art we get taken straight that's the dashboard as we're already offense kated and vice versa if we try to go into the dashboard when we're not in skate anymore we've logged out you can see we get redirected to the login page okay so it's nice little project I think is a good skill to know how to know interact with PostgreSQL databases and hash passwords and just create offense ocation input implement authentication for your app so I hope you enjoy and let's get going okay so to start this project the first thing we need to do is download PostgreSQL okay so if you go to the website PostgreSQL org follow the download instructions relevant to your system I'm not going to walk through that process it should be pretty self-explanatory really but if you just install that once that is installed then will open up that terminal and some logins PostgreSQL from our terminal we just simply type p SQL and then - capital u for user and where the initial default user setup for us is called post press safe loved ones post press and then we'll do a dash D for database and we have a default database called post press setup as well when we install PostgreSQL stay Postgres again so just enter the password you created when you setup PostgreSQL and then once you're logged in you should see Postgres equals and a hash sign here okay so if you want to display all the users within our current PostgreSQL setup just type in backslash d you for display users you can see here we have two users in our database up or PostgreSQL setup we have a one which I've previously created called Conner and I actually use here he can create a database and we also have tissues are here Postgres which is the user we logged in as now you can see that tributes is there this users got super user access can create roles users databases everything really so the first thing you're gonna need to do when you've installed Postgres and logged in to this is say we're going to create a new user okay so just say to do that say create user and add your username so for this example I'm going to say con Bailey and then we'll save with password actually give us some really simple password of password for now make sure it's in single quotes and then we're just gonna give this user access to create a database so just say Craig DB okay end that with a semicolon and press ENTER and you'll see here it's created the role okay so if we do it backslash T you again we can see the conbini users been added with access rights to create databases okay so now we're going to come out of this backslash cue for quit and we're going to log in as a new user in the terminal so we do psql - capital u for user again or stake on Bailey and then we say - D and we're going to reconnect to that Postgres database okay so thirsty Postgres Center into the password which was just password for me just see now we locates the Postgres database again as Conn Bailey the new user we've just created now the first thing we'll do once we've logged in is create an actual new database okay so we're going to say create capitals doesn't have to be capitals but just to highlight the P SQL syntax say create database we're going to call this state space for this project node login okay canvas semicolon see there we get our create database now in order to list all the database is stored within your PostgreSQL setup just type a backslash ill for list and then you can see we get our list of databases one we just created here is no login because ii do now is combine li okay now we want to connect this database so to connect we just say backslash c and then we're going to say node login and you'll get a message there saying you're a data to the database node login as user icon Bailey that's great okay now we want to create I users table now so this is going to be a table where they're gonna log all of that app users name emails passwords that kind of things they can log on now if indicate to our system we're gonna build okay so to create a table we just say create table I'm gonna call this table users and then the first column so if you do an open bracket we're gonna say the first column is ID and this ID is going to be a type of big cereal now a big cereal is a type in PostgreSQL it's just basically a number and also increments in number so any new entries we add the first entry will be to have an idea of one and you'll go up got one number each time a new entry is added okay so post post manages that for us we don't have to worry about completing the ID column this is going to have an attribute of primary key as well so this is just a unique value in the table all the IDS will be unique to the relevant user and then just want to make this not null as well so this cannot be no it can't be left blank when we enter this into the into our database okay it's the next column we're gonna say name and this is going to have a type of bar chart 205 char just basically means any characters and 200 is just a memory can the last so 200 should be enough for most names anyway and we're going to say not null comma then the next column we want is the email address for the user so say email I'll make this far char will say 200 again should be enough not null and then finally we want to store the users password okay so that will be password and then we'll just say that b VAR char again 200 again and we'll just say knocked a lot okay so now these columns can be left blank the last thing we want to do on this is just enter I can right okay so in order to do that we're going to say unique and then open bracket email okay so this means basically they're going to be one all emails have to be unique on our database so we can't have two of the same email registered for a user okay well close yeah or close the column inputs off with a bracket and then that should be a semicolon you can see we've got a great table okay so now if we do a select all users obvious isn't gonna have any records at the moment we can see we get a table there a variety column name column email column and password column okay if you just want to see the constraints on a table if you do it backs SD say users you can see we have our constraints listed here just old details for the table really so you can see it gives us the column names gives us a type they refer which should be entered the type of data they should contain and then we have had constraints down the bottom here as you can see we've got a primary key constraint on the ID column here and we also added that unique constraint for the email column so we can't have two at the same email in our database okay so that's basically it for our post rescue I'll set up next we're going to set up our Express server okay guys so next we go and set up our node application with Express you can see here i'm in vs code and i've created a new folder you just saw that my desktop called node login there's no files in there at the moment the first one he's dude is I've just opened up the term an old wooden vs code you can do that by pressing terminal new terminal come to the terminal and we're going to initialize NPMs we're just gonna say npm in it - wire okay and that's why i just basically gives us all the default values when we set up our or initialize download app okay so you can see now we've got this package JSON file first thing we want to do in this file just adjust the scripts okay so I'm going to change this test we're gonna say start and when we do so if we if we type NPM run starts in a terminal it will trigger the script to run okay so when we trigger start we want it to basically run this script I'm just going to say it node server Jas we're going to create this server Jas app in a second but we also want to just create a dev script as well okay so if we do a double quote dev and this is going to use a package called or a Larry called node mod which are going to be installed in a second as well server Jas I'll explain what node money is in it in a sec but for now that's just installed it dependencies so we'll say NPM I have install and we'll just say from that Express okay and then after this we're going to install node one as a dev dependency and I'm sure for those of you that have never used node 1 this basically just liable we can use and it refreshes the server or the application for us whenever we make any changes 20 files it just saves us from coming into the terminal shutting down our serve and rebooting it manually so just say there's a lot of time it's very good library to use so we're going to say npm pi - capital d node 1 that install ok so just close this down here okay you can see we've got our dependencies now so Express and load Mon I didn't save my script so guys t6 start say no yes Dave je s okay that's it for now so let's start to start this crate this server dot J's file where reference in here okay so I'm gonna come into our directory and just hi at the server create a new file server je s okay now the first we want to do here is bring in Express so we'll say Const Express equals require Express okay so it just brings in the Express library so we can use it next we're going to say constant app equals Express and it's just basically know whenever we type app we have access to all the Express library features functions that kind of thing and then gonna stay a port number so we're going to say Const polt then capital letters equals process env pulled or will say 4,000 okay so this process DMV it's just referencing the environment variable this is going to be the port used in a production when the apps when the we make is shifted to production mode otherwise it's going to use port 4000 in development mode which is for this case okay and then we're going to say underneath here we'll say we'll just start off of a get request so I say apt-get and when we go to the root directory so we'll place that here to read directory of our app that's the first parameter and then the second is a function that takes in the request and response and then here which grants through read send and which give us a little message of hello just just to get everything working okay and then at the bottom we want to say app listen and then we give it a poll to listen on as the first argument and then we can say just a call back in here just to say console.log do in equals console dot log server running on holt and we just say bet dollar this is a templated to revive these back ticks here and we just put a port number in there okay so now I should be blog as well so now let's start this fight a server up so then we can type in node 1 and we went to run server I know it sorry not know we want the NPM run dev ok and that is just going to run this script here this node 1 server KS so if you run that you can see we got our made one booted up and it's the server running on port 4000 so now if we visit port 4000 say localhost 4000 and we get our message of hello rendered to the screen ok ok next thing I want to do with this project is create our views we're going to be using within the app ok so I'm going to actually first thing I'm going to do is install a new library so if we come to another terminal you can say npm install ejs now what ejs is it's it's going to be our template view engine for this project ok so it allows us to basically render ejs files which can be coded as HTML and it allows us to power variables food cities file so we can use them in our front-end like the user names that kind of thing okay this one CJ s is installed we're going to create a new folder and it's gonna be called views all the J's files have to be stunning this folder called views for our projects will access them and the first view we want to add is just a home view so we'll say index ejs okay and I'll just do a hastily boilerplate for now we'll just say h1 of home let's add another file will say login dot AJ F that's where I use it will log in if I log in there as well we also want to use fill out some register so we'll say register dot ejs okay h1 of register and then we also want the user dashboard so this is where the user will be redirected to once they've logged into the app so say dashboard ejs and then if there's just a Hello that's what do a h1 will say hello and show you how ajs works we're gonna just do some ejs - syntax here so in order to insert variable in turn a J's file for just a less than sign % equals and then we get a parse and a user variable to this this page okay and then we'll close off with a non % and a greater than symbol okay so if we go back to our server like J s farm now we're going to create our routes to to render these pages okay so for this app get we want this to render the index for ejs file okay let's do that we'll just say res render in here we'll just type index and as we're using ej s it will nice-lookin the views folder so I'll show you we need to add a bit middleware in a second as well and then let's do an app get we'll do forward slash users forward slash register okay now we're taking it request and a response and here we're just gonna do a response render that login ejs file let's copy this down did the same for login here as well that should be register sorry and then we'll do finding the dashboard ok and speed - Bob okay and then above all these we just need to add some middleware here so we're going to say app set and we're gonna save you engine and then this is going to be ejs this will - that app to use the ejs view engine it's got to render these ejs files okay and remember in our dashboard be passed in this user variable so just to show you what that does if we come back to our dashboard we can add an object as a second parameter here you can stay let use a variable and for now I'll just state a user as Conner okay so now if we go back to our server check that still running for 4,000 see we get the AJ as far rendered if I go to I think it was user / - bald she'd been restaurant render sorry guys these should all be traced not render okay you can see we get hello and it takes that user variable and converts it to the actual name there okay so that's our routes completed for now okay next we're going to add our forms to our login and register ajs files I did a register file first so first we want to do here is we're going to say I'm going to have a form underneath this and this is going to post to our users forward slash register route okay so we're going to create this route this post route and our server soon but we'll just do the form first off that needs to include the method of post like so and then another new face let's just do it div so just contain our first input and it's going to be a text input this is where the users going to insert their name when they register in we'll just give us an ID and name we'll say a name of name and also we'll say two placeholder of name and we also want this to be a required field okay and then if we come underneath this we the same again at this time we won't use the insert their email so make this a type of email just change the IDs name to be the same as that so all email and placeholder of email as well okay so I for men okay next if we copy that underneath and this next input will be a password idea of password placeholder password and we also want users to confirm their password so we just do the same thing here underneath just give us an idea of password to a name of password T and placeholder of confirm password okay okay and finally underneath this another div and we'll have an input type of submit for submit button and this is going to have a value of register okay and then underneath this we just write anchor tag just to force slash users forward slash login and here we'll just say already registered login a back side okay let's just check that quickly if we go to slash register you can see we get our form now want to make it look a bit better so let's just say let's just do the skeleton CD and just to give it a little bit of styling because you know that raw HTML just looks ugly so I do a link and head up I'm just gonna link to the skillet and CDN so now if we refresh see we get the skillet and CD and style in there okay so I'm gonna copy this and then just paste it into our login and then with the login let's just change that back to the login page one it's how to log in as well and we just need to change the form action right here this will be four slash login like so and we want to remove this name input here because the users are gonna log in with their email addresses for this app and we also can remove the confirm password input as well okay and then this should be this submit button so now you have login and then it should be neat to the register you say register okay let's just quickly check that okay back to our app we press already registered and you can see we get our login page there so we can go back and forth between the two okay we then just gonna quickly update our dashboard and index ejs files so if you come to the dashboard ojs here we don't really need much here really I'm just gonna do a logout button okay so I'm just gonna say just do an anchor tag it's gonna be four sets users for session log out and then I just put log out here XO I also want to click that skillet and CD and I'm here as well let's grab that from here okay and then for the index page I'm just gonna have to say log on there'll be four sessions what's a login again want to scale it and CD in there as well so now just check everything okay cool yep so we're all working so next we're going to do is connect our app to our PostgreSQL database okay so to set up our database let's go back to our BS code and back to our terminal it's going to need to install two more packages here okay so first when we go in to install is npm env and this is going to be used to store or create our environment variables we're going to use and then we also want to install PG which is the mode Postgres library which we use to connect our load up to our PostgreSQL database just install those now okay cool so now the first thing we need to do is create our environment variables to store our database details okay so we're gonna come to our directory here I'm just going to say create a new file I'm going to call it dot e NV back side okay and then here we're going to store PostgreSQL database credentials we made earlier so the first one was our user can say DB user and that equals we have a user name of Con Bailey this would be your username and then we're going to say DB password and I gave this as simple issues a simple password of password what's that changed okay and then the next variable we want is the DB host and this is just going to be localhost for now next for me one is DB Pulte next variable and that's going to equal five four three two which is a default port for PostgreSQL and then finally we want the DB database going to be the name of the database and remember we called this node login what we called it yeah no plugin up here cool ok so now we can save that and then now that's done we can use these variables in our database config file which you're going to make now so we create another new file in our directory let's close all this down we're going to call this file DB config dot J yes okay so the first thing we need to do in this DB config file is say we want to require our environment variables we've stored here ok so we're going to say require dot env and then the end of this we're gonna say dot confit ok this will bring in all of our environment variables from this file here and then underneath this we're going say Const pull the capital P that's going to require the PG module we just install it opposed node Postgres library ok at an underneath this we're going to say I'm going to create a boolean variable called is production that's going to equal process dot e NV dot node env or equal so it equals production ok so this is going to look to see if our apps hosted in production and if it is if it is in production this will be true otherwise in development this will be set to folks ok and underneath this we're going to say Const connection string and this is quite a long string so give me on this one and this is going to equal so you guys the back tips here and we're going say Postgres ql : t ports shoes and then we're going to use our first environment variable here so if we do a dollar sign and open the code races we're gonna say process dot E and V dot DB underscore user corresponds that user variable we started out got a MV file and then we're going to do a another : and then another template literal here gonna say process a and B dot and this next one will be DB password like so and then we want to do after this one and at and then we go into at to another template this relative dollar sign so we process env dot and if is going to be a DB host DB underscore host and then after that another codon template this rule process env and the next one is the DB polt okay and then finally we don't forward slash last template it's real weird this week process dot P and V dot DB underscore a database for the database name restored okay so that's that's it for a connection string as I said it's quite long and then kind under this we just want to initialize a new pool variable to say Const whole equals new pole so yeah library we pull it up here and then this is going to be an object and the first variable in this object is going to be the connection string and we're basically I say here if if the apps in production if that's true we're going to say process dottie NV dot database at URL at a production database otherwise we're going to use our connection string we stated above okay and then underneath there all we need to do is say Const maybe state export list nuts and module exports equals so that should be that's it for a database config file okay so now I'm going to bring this DB config file into our server so we can use that pole method so you've come to the top I'm going to say Const and we're going to say here once we call it was just a poor poor equals require dot /dp config ok so that'll bring that pool librarian from this file here we created a DP config ok and now we're just going to install another package this is going to be called bcrypt so what be quick does it allows us to hash passwords so basically it's bad practice whenever I use a registers to an app that their passwords should not be stored in a database and they reward text format in case the database gets compromised so we're going to use be quick to hash our passwords so I'll show you what it does shortly just read that is installed see you click there that's great and also just for testing purposes I'm gonna go back to our PostgreSQL I'm going to add a user to our table so if we say insert just for testing purposes insert into users and we want to insert the name email and password and then under the affair going say values and I'm gonna say like honor for now give it an email of pawn Bailey that's gmail.com just keep my password of password again for now okay so that's been inserted we did a select all users entry there okay so the next step is I'm going to create a register post right now so if we go back to our server today s file and then underneath this middleware here I'm going say app use Express doc URL encoded this is taken option of extended folks okay and what is piece of middleware allows us today it's just send details from our front end so feel and Paul that's register it asked to send name details email details and password details to our server from the front end okay that's what that piece of middleware does and then gonna come to the bottom here underneath if I get requests when I'm going to do an app dot post so as I said we'll do our register out first be users that register and this takes in a request and a response okay so the first thing we need to do is take the commoner it we need to get the name get the variable from that form okay so we're going to say let we're doing object here we'll say name email password and password to equal request body okay and then if we for now we'll just say console.log make sure that works okay so if we come back to our app should see now so if we go here just a Connor okay so our friends from that we should have you can see we get the variables or the input passed back to us over here as that's consul logged in the serve and asked that's working okay so underneath this we're going to say let errors equal an empty array okay and this is what we're gonna use for our form validation so showing I mean so if we get any errors when we're completing our form they'll be pushed to this errors array here okay so we got to work on that now so underneath that will say first validation check order those want to make sure all forms are entered okay so there's no blank feels left on the phone so say if not name or not email or not password or not password not password to the wants to do here and errors dot push and here we're going to say in objects a message and the message will be please enter all fields okay the next foundation check we want to do is we're going to look out for the password length okay so we'll say if the password got length is less than six characters long again we're just doing arrows dot push here and we'll just say the password should be at least six characters okay the next validation check we want to do here is we want to make sure that the passwords match a case the confirm password is the same as the first password so we'll just say if password is not equal to password - and we'll just say again passwords do not match black site okay and then under the effect so basically if any of these validation checks result in an error we're going to say if it's a get a push so if you guys say if this errors array here has some items in we're going to need to return the login page and get an error so I'm going to say if errors dot length is greater than zero and here we're going to say res render we want to rerender the register page and we want to pass in the errors array okay like so and so this just CFS working and that if we just come back to our errors sorry our register ejs file come up here do an album list I'm going to say we're gonna do the ejs JavaScript template symbols here so the if statement and we're gonna say if type of I'm going to say errors is not equal to undefined and it means close each line here so 2 percent greater than and then so it basically is a saying if if there's errors been passed through to the render to this register ejs render render we're going to say list and wait to miss the errors dot message and we need studio template engine output here so great less then science and equals close that off send equals and then we'll just close it off down here as well okay so let's see if that works so if now we go back to our app go to register let's just try and do something wrong here so I say I put it on passwords in register so why is that not worked see how better one passwords in bad me a second guys see I know I've done wrong I've not done a 4h because we got multiple errors we still a 4h there okay so what kinda devious will say percent and we'll say errors dot for each cuz we had here so we had a password which was less than six characters long and also they didn't match so there would be two errors pushed to the errors array errors array so that's got a for each here era and there'll be a function and then let's close that down in there and then we can place this in here tell us off that just referring to this error here and then that should be now if we close that off okay let's give that a go again I'll refresh that okay hmm should be a bracket here okay fair time lucky sorry guys we have me a second so i shouldn't've at the bracket okay should work okay and yeah you can see we get our error messages there let's just try one more thing we'll do a password of five letters and you can see we part which should be at least six characters okay great that'll work in our form validations complete okay so next once the form validation is complete we can move on to check in our database to see if the user already exists okay so let's just go back to our register poster method here so we're going to come underneath this so if if there are formulation errors will we render the page else and this means form validation has passed and then come underneath this we're going to now we're going to bring in bcrypt okay so we're going to say let's hash password equal and we're going to say here it has to be a way actually so this is a a synchronous function here so we're going to need to await that so I'm going to make this request function here a synchronous I'll just put a sink up here like so as soon as I let how to password equals or wait and we're going to say bcrypt will be pricked in so we end up here Const bcrypt equals require secret okay this is going to be bcrypt dot hash we're going to take in our password which to use app riders with and then we're going the second argument here is the amount of rounds of encryption we want to hurt our password we have tens a default value and I find it's perfect for this type of project we're doing really if you go larger the algorithm gets more complex but it takes longer to generate the hash password it's already there ten for now okay it's just console.log the hash password so just to show you what the hashing does if I just come in here just do a password a password for now you can see here this is our password and this is what it crashes that password into so we can store that securely in our database okay so it's nice and safe and secure and it'll be very hard for a haircut to kind of encrypt that password and take a lot of time okay so kind underneath this next we want to query our database to see if the users already exists before registering okay so to do that we're going to use the pool which we bought it at the top here from our DB config we're going to say doc query and the first thing it does it takes in an SQL statement so here we're going to say select all from users which is our table name we're email equals dollar one okay and it's donal one will be it will be replaced by the variable we pass in the list after okay it's gonna pass an email so this third one we've replaced with this email which is inputting the form and part that's the server up here okay and then once that's done we do a callback function so we'll say either there's going to be an error or return some results from the database and then here we're going to say if there is an error actually a function a function if error right error or else what we're going to do here will say console dot log results right and that will return a list of all a list content objects of our user details if they're actually in our database just to show you if it's our database now I can see we've got these shoes it here of Konnor agent registered email is con baby at gmail.com so if we do that about to register page we search for Conner I said con Bailey at gmail.com this email here press ENTER there if we go back to our on that he just got an empty list back okay okay it's because it was Connor Bailey at gmail.com that's why and its go again sorry about that guys should just be con Bailey I try that again and you can see now we get our one-week onslaught the results don't rose we get a list containing the objects of the use of our database with the idea of one name of Connor come Bayliss that's working that's great say that consult out okay so next underneath this we're going to say if results yeah Rose don't link it's greater than 0 that means the users already owe to a database we're going to say errors don't push again let's put some message message use are already in that already registered okay and then we want to do a res don't render when the email render their register page again forward slash and we just want to pass in that errors objects again Oh errors variable in an object okay so let's try that out you can see now we get the email already registered okayed grapes that's working okay before we move on to the next part of that post method we're just going to install another cup of libraries here in our terminal so if you go to our install terminal here we're going to install NPM I express session and also Express flash okay so this is just clearly used to store our user details in the user session and also to display flash messages when we get redirected to other pages of the website okay so we need to put those in middleware up here so first we need to bring them up bring them in at the top as well as libraries so we're going to say Const session equals require session Express session and we also want to bring in the flash as well so they will say Const flash equal and require Express flesh X I and then we also need to put these in the middleware section as well okay so we're going to say comes our middleware section underneath here say app dot use and we're going to say session and what this does back in an object and the first variable is taken to the secret and this can just be anything you want really longer is them around and the more secure it is we're just going to say secret for now you use one of these place an environment variable but we're to leave it as is for now and what this does this is a key we want to keep secret and it's just going to encrypt all of our information we store in the session the next variable we want to include is resave and this is going to be false and what resave does is should we it's saying should we save our session variables if nothing has changed if none of our informations change which we don't want to do that's what I say well that's what I'm saying is false and then finally once save initialized that's also has to be false what it's basically does this means we want to save session details if there's been no value placed in the session which is obviously false and I'm going to do that okay and then we also want to use app don't use flash underneath this as well just display our flash messages okay so now if you come back down to our register function we're nearly done here with this with this step we just want to say if results that rose so if there's easily registered will redirect or will ruin that register page say else so else that means there is no using database and we can register the user we're going to say pull query and this time we're going to insert into users the name email and password remember we don't need to worry about the ID as SQL some set up for us and then we're going to do values and the values we insert so we're going to do dollar one dollar two and then dollar free okay and then we can also say underneath here returning ID and password so this will just return for our reference the idea of user the password okay and then after the SQL statement we'll just need to replace these variables here with the ones in this list so we're going to say name email remember we want to store the hash the password in this database with a hash password will indeed a function after so if there's an error or results okay it should be a function doing that next we're going to say so if error frye era where we'll say console.log results rose just for our reference again and then here we're going to say request we're going to use the flashlight we now it's going to be used to pass a flash message into our redirect page so we're going to give this gonna say this is a success message and then the second parameter is the actual message content so we'll just say you are now registered please log in and then we're going to do a red dot redirect and we're going to redirect to the login for set users forward slash login page now we just need to amend a [Music] login page to display that flash message okay so if we come here I'm just going to say if messages da we call this success message there and we're going to say I make this another list actually I'll put this in a list format we're going to say a liar and then we output the message or side messages got success message backside and close that off and then we also want to close this off here as well so I'll say okay so now if we go back to register if we will just do a new you email I just say deter shuffle now I can say NAT at gmail.com password you see we now get redirected to the login page saying you are now registered please login and then if we query our database now you can see we get the touches added to our database with the hash password there that's great that's all working okay it's the next one me to do it is still two more packages they're going to be it's going to be compassed fault so do npm install passport and passport local this is going to be used to store logged in users session details into a browser cookie so they can use app as an authenticated user some once they're installed we need to create a new file we're gonna call this passport config j/s firstly what's doing here we're going to say Const local capital well strategy equals require local passport local and then top strategy and underneath this we're going to bring in our poll to create our database again so can't pull equals require dashdb config and then we also want to bring in be clips as well because we're going to want to compare our users password to the hash password is stored in the database source they be crit so okay and then underneath here we go its initial size of function so say function initialize this will initialize the local strategy we're going to do now initialize go spell it right do and this takes in passport passport variable and here we're going say passport use local new local strategy and it takes an object the email sorry user name field this is just going to be said to email in this case as the users grants logging with their email you can also add password in as well password field and this will just be password we'd only see this in our case because we already called our fill the password field password in our ajs file and then this also takes in this use method also takes in a handle there as well so we're just gonna say offense Kate user which is a function we're going to create now so we'll say up here Const authenticate user equals and this will take in an email password and also a done function which I'll see what that does in a second so in here we're going to say I'm just going to query our database to see if this email and password exists if this user exists in our database so we're gonna say pull dot query let's say select Oh users where email equals dollar one and that will be email function error salts say console era right error else we're going to say just console.log the result stop rose our reference and then we're going to say underneath that if results rose Ling its greater than zero so that means its founder user than that database we're going to say Const user sell you as user variable to the results stop rose got 0 so it will pass in the user object to the shoes up from the database okay using this 0 here because the results on Rose returns a list we want the first element of that list okay so now we need to compare the password that our users place in the input form of the register login page to the one which we have held in the database all still Emily bcrypt which has a compare function and it takes in the user's password and that compares it with the user up here dot password okay and then after that it'll even be an error or is match okay and this is much more competitive passwords and this this will be rendered true if they do match or false if I don't match so we'll say again if it's a function say if era right era helps if is match I can save return done and this done function takes in a few parameters arguments for say no that means the first parameter is the error so there's no errors and as this is a match we can return the user okay so what this will do this done function will store will return the user and store it in the session cookie object for us to use in our app okay else we'll say if the password is incorrect we'll save the turn done and this time there'll be no error on the application error but we can't any users so we'll say false as the passwords didn't match and then we're just passing a message to say password is not correct so so that's it there or we can say now so if we come if we do an else to this if thing up here so else if there are no users come down here we'll say else so if there are no users found in the database we can just save return done and there's to be no application errors convert any user because he used doesn't exist in the database we're just passing a message to say email registered okay that's it for our authenticate user function next we need to do is just come underneath his passport use here just needs to do two more functions we say password dot serialize user and that takes in the user object as well as done function and this will what we're going to do as well this will be here we can say done [Music] I'll be no fairer and I'll be user we want to store the user ID in the session okay that's what we're doing here this passport takes the user and it stores user ID in the session and then we're going to do passport the serialize user and that takes a user ID but it's done and here just go do another poll query and here we're going to select o from users where ID equals dollar sign one again you want to pass in that ID we passed in here and then error results again if error throw error else we want to return done and that will be now I want to store the results top rows 0 so the user object in the session ok so the password of serialize user stores the user ID in the session cookie and then the password of these two eyes user uses that ID user details from the database and sort of full object into the session when we navigate our pages on their application okay so now if we go back into our server and on our server we just need to set up our passport so what we're going to do here we can say Const passport equals require passport and then underneath here is we're going to bring in that function we just we just created there with passport config source a Const initialize passport equals require the passport config file sort of taking that function I don't think I exported that at the bottom I didn't so the bottom here which is a module exports equals initialize okay so we're just basically exporting this function we've created here this large function here back in our server bringing that function here with this line and then we want to call that straightaway in this last pass ball and we want to pass in the passport variable which we we've bought in here this library up here okay and then if we come down to our middleware we're just gonna anywhere up to use this so we're going to say app don't use I'm gonna say passport dot session and we're also going to say above this app use passport dot initialize okay and so now if we come down here so what initialize does it just sets up hold up our passport to use of in our app now we want to do is if we come down underneath our register so we're gonna say app post say for such users /login so it's gonna post I'll log in and here what you want to do is we're going to say instead of doing the usual request res we're just going to say passport that's authentic eight okay and this is going to we're going to use the local strategy which we defined in that passport config and then this will take in just an object after the second parameter and we're going to say here success redirect and we're going to redirect a four slash users forceps dashboard if the login successful okay and then another one we want to do we want to also say failure redirect and that will redirect us to the login page again so we say for sesh users for session login and then also we want failure flash this is just a failure first message we want to set out to true so basically if we can't authenticate Express will render one of these failure messages we have stated here passwords not correct or emails not registered okay so now I'm going to go back to our login ejs file and here I'm gonna create another list I'm just going to say if message is don't and we'll do a list here set another percent just say messages dot error and what a closed-off down there as well with ejs template symbols okay so this message is what happens here is passport will store any error messages in this messages object here in the session and then this error is what these messages are here we restated in our in our config file these are stored as error messages by Passport okay that's how I read which even those from the login ejs file ok so this should be hopefully working that ask this give us a go see what's going on here okay I need to be a careful you alright okay we're running now let's try again okay side Tudor sorry guys bad me a second I think that might be in my middle we're good bad guy ok I got a few errors here so just try and get this sorted just it's sorry yeah yes that out as well find that again just needed to do that just make sure they're in this slide properly ok so if we go try this ok one more thing we need to do here is on our server we just need to say so if we go back to our dashboard this needs to be request user name and that will take the name from our database so passport will take this user and it will display the name from our database ok so we try that again we go back to our roots we try logging in there's that nut again and see we get the name Palin entire because it's taking for one database now that's working so we need be there guys I just want to make this a capital let off because it doesn't it very professional so you can always do that we're going to go back to our dashboard ejs yes and then in here we will just say a user dot and then we can take the first letter of the string so we'll say char at and then we'll say zero for the first letter it'll put to upper case then we'll do a class to do the rest of the name and then we'll just say use our dot slash from the fear from the first index of that string okay so now if we reckon then refresh we should get yet the capital when that looks better okay so let's finish this off now if we go back to our server Jas and then I'm just gonna add a logout route to this so if we go underneath here and we're going to I get requests actually so under this get requests here we'll do app don't get for such users forward slash logout function and then here we're just going to say request stop log log out this is a function we get with passport and then we going through a request dot flash and we'll just do another success message and this will be you have logged out oxide and then also we just don't get a resident redirects back to the login page now okay so we just do read don't redirect - what's that users what's - login just quickly test that out if we go back to our app we need to make this if we go back to my dashboard they set to users that log out so I just beat log out okay start again so certain reset at home login setting that okay and if we log out and see there we get the message that we have logged out it's about our login page that's working so next we're going to add just two more pieces of middleware basically just we're going to want to check if the users authenticated if they are logged in and authenticated then if they visit the login page or register page they'll be redirected to the dashboard and there's also Khalid we're gonna write an authenticated piece of middleware so if the user tries to visit the dashboard we're not logged in they'll be redirected to the login page okay so come back to our server is irani is two piece of middleware functions down the bottom or just a function we first wanted to see if the user is authenticated so record is check authenticated spell it Brad and this will take in the request response and next okay and then to be a function so we're gonna say here if the request dot is authenticated it's a function that comes with passport we're going to say return res dot and redirect forward slash users forward slash dashboard okay so if the user is authenticated that we redirected to them to the dashboard otherwise we just gotta say next I mean on to the next piece of middleware okay and then we're gonna commander this as well we're gonna do a function called check not authenticated again request response next and here we're going to say if request dot is authenticated again in parentheses we're going to say next because they are authenticated and should be returned next otherwise we're going to say res don't redirect and here if users not authenticated we're going to want to go to the login page so we just say for sex users what's that login okay so now we're going to place these middleware in our routes up here so basically in our if we want to in our register page we want to see check authenticated place that in there put in for the login as well so basically a 20 years ago is these routes it will first check if these ores authenticated first before moving on to this response section here okay and in the dashboard we want to do the check not authenticated it's basically if a user tries to access the dashboard the first glance this piece of middleware it will look to see if the user is authenticated if they are they'll continue to the response if not the user will be directed to the login page again okay let's try it out so now if we try to go into our dashboard we're not logged in at the moment let's see we get redirected to the login page and so if we log in there and we try to go to the register page and see we just directed back to the dashboard just login and the same things that's working right so that's pretty much it guys let's just add another user so if we say how did i Donald Trump and then we'll say Donald at gmail.com password password register it's been registered just check our database I'll log in again sorry guys setup from users you can see we have our Donald Trump there done all that to email and there's his hash password so now if we try to log in will say Donald at gmail.com you can see we get hello Donald Trump there and we can log out and that's it so that concludes the tutorial guys I hope you got something out of it obviously it's a quite involved to get this authentication implemented into your app but I think it's worthwhile it's a good skill to know how to you know interact with databases store hash passwords and use your own local strategy for users to log in to your app but yeah I hope you enjoyed again and see you in the next video Cheers
Info
Channel: Conor Bailey
Views: 39,893
Rating: 4.9591837 out of 5
Keywords:
Id: vxu1RrR0vbw
Channel Id: undefined
Length: 89min 32sec (5372 seconds)
Published: Wed Apr 01 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.