In this article we will understand to empliment passport for local authentication using mysql and ejs template. Since we will discuss the main points of the topic, so for detail please download the zipped code from the site.
Node.js - Download and install node.js
Mysql - install mysql
To create the node app, we’ll use the following command:
npm init
You’ll be asked to provide some information for Node’s package.json and about basic detail of the application
. Just hit enter until the end to leave the default configuration.
Now for frontend part we have file with ejs extension, Since we are performing the required task with nodejs ejs template. In that file we have some data which are static and at the top we have default option login/Register which will replace by welcome message after login.
At first look at the the folder stucture:
server.js
DAO
userDAO.js
Models
User.js
node_modules
Routes
passport.js
web.js
Services
web.js
Utilities
config.js
cred.js
dbConfig.js
environment.js
isLoggedin.js
util.js
views
STATIC FILES
First we require Express and create our Express app by calling express().
We’ll need the body-parser middleware this time, in order for authentication to work correctly. Below that we setup the middlware of the application. Then we declared the routing for the app. And at the bottom of the application we created server.
for authentication related task we have a file passport.js under routes which does the actual task of authentication, in this file we have mainly two method. First one is names as local-signup which registers new user and saves user details into databases and second is local-login which authenticates credentials while login. Download the zipped code for detail.
That’s all are the major points we need for the app to work. We’re done!
In this article, we learned how to implement local authentication using Passport in a Node.js application. In the process, we also learned how to connect to Mysql with Node.js
Find complete source code over GitHub