Authentication

How to manage login activity using JWT in NodeJs

Manage Login Activity of User

Divyansh Agarwal
Jun 20, 2020 · 7 min read
Image for post
Image for post

About JWT

Problem with using Redis for storing tokens

Problem with using Session authentication

Solution

Let’s Begin!

├───.env
├───.gitignore
├───app.js
├───package-lock.json
├───package.json
├───sequelize.js
├───middlewares
│ ├───authenticateToken.js
│ └───blacklistToken.js
├───models
│ ├───BlacklistToken.js
│ ├───User.js
│ └───User_Login.js
├───routes
│ ├───loginUser.js
│ ├───registerUser.js
│ └───user_logins.js
└───utils
└───token.utils.js

Install the following dependencies

npm i express bcrypt bcryptjs cors dotenv morgan jsonwebtoken sequelize sequelize-cli pg helmet

package.json

package.json

App.js

Models

User Model

User Logins Model

User Logins Model

Blacklist Token Model

Blacklist Token Model

Sequelize Connection file

Sequelize Connection File
dialectOptions: {
"ssl": {
"require": true,
"rejectUnauthorized": false
}
}
Image for post
Image for post
Environment File for setting Database

Routes

Register Route

Register Route

Token Utils

Token Utils
const token_id = await customId({
user_id : req.auth.id,
date : Date.now(),
randomLength: 4
});
var ip = (req.headers['x-forwarded-for'] || '')   
.split(',').pop().trim() ||
req.connection.remoteAddress||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
const user_logins=await User_Login.findAll({where:{ user_id:   
req.auth.id ,token_deleted:false, ip_address:ip, device:
req.headers["user-agent"]}});
user_logins.forEach(async(login) => {
if(login){
login.token_deleted=true;
await login.save()
}
});
const token = await User_Login.create({
user_id : req.auth.id,
token_id : token_id,
token_secret : token_secret ,
ip_address : ip ,
device : req.headers["user-agent"]
});
const token_user = { id:req.auth.id , token_id: token_id };
const accessToken = await jwt.sign(token_user,
process.env.ACCESS_TOKEN_SECRET);
sendToken: function(req, res) {          
const responseObject = { auth: true,
token: req.token,
message: 'user found & logged in'
};
return res.status(200).json(responseObject);
}
Image for post
Image for post
Final Environment File

Login Route

Login Route

Logout Route

Logout Route

Middlewares

AuthenticateToken Middleware

Authenticate Token Middleware
Blacklist.findOne({ where: {token: token } })     
.then((found) => {
if (found){
details={
"Status":"Failure",
"Details":'Token blacklisted. Cannot use this token.'
}
return res.status(401).json(details);
}
else {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET,
async (err, payload) => {
if (err)
return res.sendStatus(403);
if(payload){
const login = await User_Login.findOne({where:{
user_id : payload.id, token_id: payload.token_id}})
if(login.token_deleted==true){
const blacklist_token = Blacklist.create({
token:token
});
return res.sendStatus(401)
}
}
req.user = payload;
next();
});
}
});
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, 
async (err, payload) => {
if (err)
return res.sendStatus(403);
if(payload){
const login = await User_Login.findOne({where:{
user_id : payload.id, token_id: payload.token_id}})
if(login.token_deleted==true){
const blacklist_token = Blacklist.create({
token:token
});
return res.sendStatus(401)
}
}
req.user = payload;
next();
});

BlacklistToken Middleware

Blacklist Token Middleware

Manage Login Activity Routes

Manage Login Activity Routes
Image for post
Image for post
User Profile

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Divyansh Agarwal

Written by

I am an Innovator with lots of ideas in my mind to improve the world for better! Know more about me at https://divyansh.agarwal.work .

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Divyansh Agarwal

Written by

I am an Innovator with lots of ideas in my mind to improve the world for better! Know more about me at https://divyansh.agarwal.work .

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store