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.
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.
|___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
{
"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
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.
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
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.
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();

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
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.
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();
