Build a Login System in Node.js with Express,Passport.js and MySQL
The objective of this article is to give you a clear understanding on how to setup a login system in Node.js with MySQL database.We will be using Express Framework’s EJS which would render the html pages.We will also be using Passport.js for authentication and Express-session for session management.The strategy we would be implementing in Passport.js would be the local strategy.
Note:Additionally, I shall not be putting the code in a text editor so as to encourage you guys to code along as you read. It would really help you a lot, trust me on this.
Step 1:Creating our project directory
First of all we have to create our project directory with any name you like here I have named mine as ‘LOGIN’ . This directory will contain the following files and folders that we’ll create in coming steps.
We have to open the terminal and navigate to the directory and run the command npm-init to initialize the project folder with node modules.After running the command the package.json and package-lock.json would be initialized.The package.json is the file where we can see all the packages that we have installed.The packages that we are going to use are:
- body-parser
- crypto,
- ejs
- express
- express-session
- express-mysql-session
- mysql
- nodemon
- passport
- passsport-local
Run the command bellow to install the above packages.
npm install body-parser crypto ejs express express-session express-mysql-session mysql nodemon passport passport-local
Step 2:Initialize the packages
Now we have to create a JavaScript file which would have the server side code.You can name it anything but I have named mine as index.js.
Add this code to the index.js .Here we are requiring all the packages that we had previously installed. The require method is used to load all the modules that come bundled with Node.js and also the third-party libraries.
Step 3:Define the middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers.
I am going to explain why we are using each of these middleware mentioned above.
1)app.use(session()) : You need a way to store user data between HTTP requests and sessions helps you to do so.When a user visits our site, it creates a new session for the user and assigns them a cookie. Next time the user comes to the site , the cookie is checked and the session id which is stored in the cookie is retrieved and searched in the session store .Session store is a place where you store all your data regarding your session.Here we are using MySQL as the place where we can store sessions.So we need to create database named as ‘cookie_user’ in MySQL.
The table will be automatically created when the server side code is run.(Note:I have not added password as I have configured my MySQL Workbench without a password.If you have a password just add it below the user )
2)app.use(passport.initialize()) :This is used to initialize the passport.js whenever a route request is called.
3)app.use(passport.session()) : This acts as a middleware to alter the request object and change the ‘user’ value that is currently the session id (from the client cookie).
4)app.use(bodyParser.json()) and app.use(bodyParser.urlencoded()): Body-parser middleware is responsible for parsing the incoming request bodies in a middleware before you handle it.
5)app.use(express.static(‘public’)):It is used to serve static files such as images, CSS files in Express.
6)app.set(“view engine”, “ejs”):This is to tell that we are using ejs as our view engine.You can use any other view engine but here we are using ejs.
Step 4:Set up the MySQL connection:
You have to create two databases in MySQL user and cookie_user in MySQL Workbench
Step 5:Set up the passport.js for authentication
genPassword(password) method is used to encrypt the password .It first uses the crypto package to generate a cryptographic salt. Then we use crypto to generate a hash for the password using the cryptographic salt.This method is called during the registration of the user.
verifyCallback() method is used by the passport.js to verify whether the user is valid or not .This method is called during the login phase of the user.It gets the parameters username and password which then we have to compare with the password present in the MySQL database if the user exists.For comparison purpose we use validPassword() method.
validPassword() method takes in parameters hash,salt,password which we have retrieved from the database .We use the salt and the password to create a new hash value which is created with the password entered by the user during login and the cryptographic salt we are using.It then compares it with the hash value present in the MySQL database(created during registration).If both matches then it returns true.
passport.serializeUser() is setting the user id as cookie in user’s browser and passport.deserializeUser() is getting the user id from the cookie.
isAuth() method:It verifies whether the user is authenticated.the request object would have isAuthenticated() method defined by the passport.js that will check whether he is authenticated or not.If it returns false it will redirect to /notAuthorized route.
isAdmin() method:It verifies whether the user is an admin.This is simply for role checking and can be improved by adding more logic.Here I am just checking whether the req.user.isAdmin==1 .I have stored the isAdmin property in my MySQL database which can take 0 or 1.If it returns false it will redirect to /notAuthorizedAdmin route.
userExists() method:It checks whether the username is already in the database.If the username exists it will redirect to /userAlreadyExists route or else it will successfully register the user and it will then redirect to the /login route
Step 6:Setting up the routes
Here we are setting up the routes that we need for our website
app.post(/register) route is used to register the user with the username and password entered by the user.Here we call genPassword() method to generate an hash for the password which would then be stored in our users table.
app.post(/login) It uses passport middleware to authenticate the user.The middleware calls the verifyCallback() method which returns whether the user is a registered user.If he is not he goes to the /login-failure route or else he goes to /login-success route.
app.post(/admin-route) we have created this route as to check the admin feature is working.It calls the isAdmin() method which then checks in the request.user object whether the property of isAdmin is true or not.
app.post(/protected-route) we have created this route as to check the user authentication feature is working.It calls the isAuth() method whenever the route is called which then checks in the request object whether he is an Authenticated or not .
Step 7:Creating the EJS files
Add login.ejs and register.ejs files under views folder in your project directory.
Also add the styles.css file which is displayed below ,under the public folder in the project directory.
Step 8:Run your application
We have to open the terminal and navigate to the directory and run the command below.
nodemon index.js
Then open your web browser and navigate to localhost:3000/register to register a new user and localhost:3000/login to login .
Summary
In this article, we have understood how to setup a login System using Node.js and MySQL as the back-end database.
The entire project is also available in my GitHub repository.
If you liked this article, kindly click on that clap button & drop a comment below.Keep coding!!
Special Thanks:
www.youtube.com/watch?v=z7872Nki5FY&list=PLYQSCk-qyTW2ewJ05f_GKHtTIzjynDgjK