Mastering Node.js: Seamless User Authentication with MongoDB (Mangoose) and index creation along with API request validation

Rajesh Kumar Kanumetta
3 min readOct 29, 2023

--

Welcome to our comprehensive vlog series, “Mastering Node.js: Seamless User Authentication with MongoDB.” In this series, we delve deep into the world of web development, focusing on one of the most critical aspects of modern applications: user authentication.

Join us on this journey as we demystify the complexities of user authentication using Node.js, a powerful runtime built on Chrome’s V8 JavaScript engine, and MongoDB, the renowned NoSQL database. Whether you’re a beginner looking to grasp the fundamentals or an experienced developer aiming to enhance your skills, this series has something for everyone.

Throughout these episodes, we’ll cover everything you need to know about creating secure and efficient authentication systems. From setting up robust user authentication mechanisms to integrating MongoDB for seamless data storage and retrieval, we’ll guide you step-by-step. You’ll learn the best practices, security measures, and advanced techniques that professionals use to build reliable authentication systems for their applications.

Get ready to explore the core concepts of user authentication, including password hashing, token-based authentication, and session management. We’ll also tackle common challenges faced by developers and provide practical solutions to ensure your applications are secure and user-friendly.

By the end of this series, you’ll have the expertise to implement user authentication with confidence, enabling you to create dynamic and secure web applications. So, don’t miss out — hit that subscribe button, stay tuned, and let’s embark on this exciting journey of mastering Node.js and MongoDB for seamless user authentication!

We can quickly start with the application building

The first step is to start with the software setup like Node.js setup and MongoDB setup with the help of MongoDB Atlas (Here is the link to get the Atlas setup)

MongoDb Config File

const db = {
"development": {
"url": "mongodb://username:password@test137643.mlab.com:37643/test"
}
}
module.exports = {db: db.development}

app.js main file

var express = require('express');

const mongoose = require('mongoose');
url = require('./conf').db.url;
var app = express();


//Mongo Db Connection
mongoose.connect(url,{ useNewUrlParser: true },function(err,db){
if(err){
console.log(err);
}else {
console.log('connected to the Test db');
}
});

// before Mongo 6.8 we need to use this flag
mongoose.set('useCreateIndex', true);

var db = mongoose.connection;

User Schema (Model)

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

var userSchema = mongoose.Schema({
username: String,
password: String
});

// here we are hash the password before storing into db
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// here we are checking if password is valid or not
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};

// we can create index based on user name
userSchema.index({ username: "username"});

var UserModel = mongoose.model('user', userSchema);
module.exports = UserModel;

API Request validation with JOI userRequestSchema.js



const Joi = require('joi');

var userLogin = {
body:{
'emailId' : Joi.string().required(),
'password' : Joi.string().required()
}
}

module.exports = {userLogin : userLogin}

we can use the below code in app.js or we can maintain it in a separate file



var User = require('/path/to/user/model');
const userSchema = require('../schemas/userRequestSchema');

app.post('/register', ExpressJoi(userSchema.userLogin), function(req, res) {
var new_user = new User({
username: req.body.username
});

new_user.password = new_user.generateHash(req.body.password);
new_user.save();
});

app.post('/login',ExpressJoi(userSchema.userLogin), function(req, res) {
User.findOne({username: req.body.username}, function(err, user) {

if (!user.validPassword(req.body.password)) {
// password did not match with the user input
res.send({status:401, data: user})
} else {
// password has been matched with the user input. proceed to move forward
res.send({status:200, data: user})
}
});
});

That’it, I hope it will be useful for reference, Will come back with more concepts in the future😊,

Thank you,

— Kanumetta Rajesh Kumar

--

--