Nodejs auth app using passport local and ejs template
Published: 2023-10-02 10:25:59

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.

### Prerequisites
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``````

### Setting up nodejs Application

``````let app = require('express')(),
        express = require('express'),
        server = require('http').Server(app),
        mustache = require('mustache')
        bodyParser = require('body-parser');
 
    require('./Utilities/dbConfig');
 
    let webRoute = require('./Routes/web'),
        util = require('./Utilities/util'),
        config = require("./Utilities/config").config;
    
    // code for extracting the entire body portion of an incoming request stream
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    app.use(express.static(__dirname + '/views'));
    app.set('view engine', 'ejs');
 
    // middleware of the application. This function is executed every time the app receives a request...
    app.use(function(err, req, res, next) {
        return res.send({ "errorCode": util.statusCode.FOUR_ZERO_ZERO, "errorMessage": util.statusMessage.SOMETHING_WENT_WRONG });
    });
    
    // routing
    app.use('/', webRoute);
 
    // code to create http server...
    server.listen(config.NODE_SERVER_PORT.port,function(){
        console.log('Server running on port '+config.NODE_SERVER_PORT.port);
    });``````

First we require Express and create our Express app by calling express(). We’ll need the [body-parser](https://jsonworld.com/demo/nodejs-auth-app-using-passport-local-and-ejs-template) 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.

 
### Connection Mysql to Node

``````var config = require("../Utilities/config").config;
 
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: config.DB_URL.host,
    user: config.DB_URL.user,
    password: config.DB_URL.password,
    database: config.DB_URL.database
});
 
connection.connect(() => {
    require('../Models/User').initialize();
});
 
let getDB = () => {
    return connection;
}
 
module.exports = {
    getDB: getDB
}``````

### Now come to the next important point, Implementing Local Authentication

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!

### Conclusion
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](https://jsonworld.com/demo/nodejs-auth-app-using-passport-local-and-ejs-template)

This article is originally posted over [jsonworld](jsonworld.com)