\

User Login Logout RESTful API Using Nodejs And Express 4

User Login Logout RESTful API Using Nodejs And Express 4

In this tutorial we will see how to build User Login Logout RESTful API Using Nodejs And Express 4. We will be using Node Express App Structure.


Check out the related post on Node Express App Structure.



Check how to connect MySql database using Node Express.



So first, let’s start with building app structure.

 

Build Up The Node App Structure

Following the node express folder architecture to build the RESTful API.

Directories

|___package.json
|
|___app.js
|
|___controller
|        |__index.js
|        |__users.js
|
|___models
|        |__users
|        |      |__login.js
|        |      |__logout.js
|        |__db.js

# Node Express 4

For the login and logout api, We will be using the POST method of the RESTful Api . As it posts request to the server. Login api will fetch the data from database.

 

Install Dependencies

So let’s start with installing the dependencies.
We will going to use following node modules for handling session :

  • Node Express 4
  • Body parser
  • MySql

Install dependencies through the following command.

$ npm install
package.json

   {
  "name": "expapp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
"dependencies": {
    "async": "^1.5.2",
    "body-parser": "^1.14.1",
    "express": "^4.13.3",
    "express-session": "^1.12.1",
    "http-proxy": "^1.12.0",
    "mysql": "^2.9.0",
    "node-mysql": "^0.4.2",
  }
}

Initialization And Require

First will include require node modules.

Do database connection of MySql using NodeJS express 4.
SEE : Connect Mysql database in NodeJS here

app.js

var express = require('express'); 
var app = express();
var bodyParser = require('body-parser'); 
var session = require('express-session');
var db = require('./models/db.js');

app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({
  extended: true
}));// Body parser use JSON data

if(GLOBAL.SQLpool === undefined){
	GLOBAL.SQLpool = db.createPool(); //create a global sql pool connection
} 
app.use(require('./controllers'));
app.listen('3000', function(){
	console.log("Connected on port 3000.");
});

 

Controller Directory

The controller defines your app routes and their logic. Controllers will handle web requests, serve your templates to the user and interact with your models to process and retrieve data. It’s the glue which connects and controls your web application.

Controller index file control all the files in the current directory and export to the models.

/controller/index.js

var express = require('express')
  , router = express.Router();
router.use('/api/users', require('./users'));
module.exports = router;

The Login Api

First we will build the login api for the registered user. lets start with the /controller/users.js

/controller/users.js

var express = require('express'),
    router = express.Router(),
    signup = require('../models/users/login.js');

router.post('/login', function(req, res) {
  login.loginUser(req, res, function(err, data) {
    if (err) {
      res.json({ 'error': true, 'message': 'Error logged in' });
    } else {
      res.json({ 'success': true, 'data': data });
    }
  });
});

module.exports = router;

Where the /controller/users.js control the the session of login.

 

Login Models Directory

Models are the files where you interact with your database. They contain all the methods and functions which will handle your data. This will create a login session for the users.

/models/users/login.js

var mysql =	require("../db.js"),
	mysqlPool = mysql.createPool();
/**
 * Defines login operations.
 * @class
 */
var login = function(){};

/**
 * Authenticate user.
 * @Function
 * @param callback
 */
login.prototype.loginUser = function(req, res, callback){
    var nowDate = new Date().toISOString().slice(0, 19).replace('T', ' '),
        params = [req.body.email, req.body.password,1],
        detailParams = [],
        updateParams = [],
	    loginUserQuery = 'SELECT * FROM users WHERE email = ? AND password = ?',
        getDetailQuery = 'SELECT id, email, gender, lastLogin, name, role, state FROM users WHERE id = ?',
        updateLastloginTime = 'UPDATE users SET lastLogin = ? WHERE id = ?'; //updates the date of lastlogin field
	mysqlPool.getConnection(function(err, connection){
		connection.query(loginUserQuery, params, function(err, rows, fields) {
           if(rows.length <= 0){
                connection.release();
                callback(true, null);
            }else{
                updateParams = [nowDate, rows[0].id];
                detailParams = [rows[0].id];
                req.session.user = rows[0];
                connection.query(updateLastloginTime, updateParams, function(err, rows, fields) {
                    connection.query(getDetailQuery, detailParams, function(err, rows, fields) {
                        connection.release();
                        callback(null, rows[0]);
                    });
                });
            }
		});
	});
}

module.exports = new login();
Demo On Postman API App For Login Api
User login RESTful API Using Nodejs And Express 4

The Logout Api

The logout API will close the logged in session. The request made by logout API will clear the saved data in server and put back to its origin state.
So start with controller Again!

 

Controller Directory

/controller/users.js

var express = require('express'),
    router = express.Router(),
    signup = require('../models/users/logout.js');

router.post('/logout', function(req, res) {
  logout.logoutUser(req, res, function(err, data) {
    if (err) {
      res.json({ 'error': data.error, 'message': data.message });
    } else {
      res.json({ 'success': data.success, 'message': data.message });
    }
  });
});

module.exports = router;

 

Models Directory

And now the /models/users/logout.js will clear the logged in session from the server and bring back to null state.

/models/users/logout.js

var mysql =	require("../db.js"),
	mysqlPool = mysql.createPool();
/**
 * Defines logout operations.
 * @class
 */
var logout = function(){};

/**
 * logging out user.
 * @Function
 * @param req
 * @param res
 * @param callback
 */
logout.prototype.logoutUser = function(req, res, callback){
    var sess = req.session.user;
    if(sess){
        req.session.user = null;
        return callback(null, {'success': true, "message": "user logout successfully"});
    }
    callback(null, {'success': true, "message": "user logout successfully"});
}

module.exports = new logout();
Demo On Postman API App For Logout Api
User logout RESTful API Using Nodejs And Express 4
About This Author

Hi This Is Rehmaanali. Blogging Is Just A Hobby. Graduate In Bsc Computer Science

11 Comments

You can post comments in this post.


  • Great article! This is the kind of information that should be shared across the internet. Shame on Google for no longer positioning this post upper! Come on over and talk over with my site . Thanks =)

    adelaidacutts20 1 month ago Reply


  • Spot on with this write-up, I seriously believe this amazing site needs a lot more attention. I’ll probably be returning to read more, thanks for the advice!

    leta518738374 1 month ago Reply


  • I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet smart so I’m not 100% positive. Any recommendations or advice would be greatly appreciated. Appreciate it

    bertiebranco861 1 month ago Reply


  • I got this site from my pal who told me concerning this web page and at the moment this time I am visiting this website and reading very informative posts here.

    taylorw85136634 1 month ago Reply


  • Hi there, just wanted to mention, I liked this blog post. It was practical. Keep on posting!

    vitodexter4833 2 months ago Reply


  • Because the admin of this site is working, no hesitation very soon it will be famous, due to its quality contents.

    piperfairweather 2 months ago Reply


  • What’s up, every time i used to check blog posts here early in the break of day, since i enjoy to find out more and more.

    andreawine1299 2 months ago Reply


  • pls put me through

    victor 2 months ago Reply


    • Hi
      Victor,

      I didn’t get your point….!
      Can you elaborate what you didn’t understand?

      Rehmaanali 2 months ago Reply


  • It’s hard to find well-informed people in this particular subject, however, you sound like you know what you’re talking about! Thanks

    henriettapayton 2 months ago Reply


    • Hi,
      Henriettapayton

      Thanks For Your Boost !

      : )

      Rehmaanali 2 months ago Reply


Post A Reply