Implementing OTP Generation and Validation with Redis in Node.js
Satish Chander
For 10 years, I've led Pustak Foundation, providing books and educational materials to children. Passionate about education and community, I aim for lasting impact. Committed to excellence, I empower communities daily.
One-Time Passwords (OTPs) are widely used for user authentication and security purposes. In this blog post, we'll explore how to generate and validate OTPs using Node.js and Redis. We'll break down the process into two parts: OTP generation and OTP validation.
Here's a sample Node.js code snippet for generating OTPs and sending them via email:
// Importing dependencies
const sql = require(`${process.env.REACT_NODE_PATH}/node_modules/mssql/index`);
const { poolPromise } = require("../config/db");
const nodemailer = require(`${process.env.REACT_NODE_PATH}/node_modules/nodemailer`);
const redis = require(`${process.env.REACT_NODE_PATH}/node_modules/redis/dist/index`);
const redisPort = 6379
const client = redis.createClient(redisPort);
module.exports = async (request, response, next) => {
let { name, email, mobile, password, dob, gender, otp, signupguest, cartid } =
request.body;
let schema = request.headers["schema"];
try {
// Connect to Redis
await client.connect();
// Generate a random OTP
var newotp = Math.floor(100000 + Math.random() * 900000);
// Database interaction (MSSQL)
poolPromise
.then((pool) => {
return pool
.request()
.input("name", sql.NVarChar(100), name)
// ... (other input parameters)
.execute(`${schema}.[Add_Customer_Website]`);
})
.then((result) => {
// Check if the customer is new
if (result.recordset[0].existing_customer === 'no') {
// Send an email with the OTP
const mailOptions = {
// ... (email options)
};
var transporter = nodemailer.createTransport({
// ... (SMTP configuration)
});
// Send the email and update Redis with the OTP
transporter.sendMail(mailOptions, function (err, info) {
client.setEx(`${schema}otp${email}`, 300, newotp.toString());
response.status(200).json({
mailsent: "Yes",
message: result.recordset,
});
// ... (error handling and response)
});
} else {
response.status(200).json({
mailsent: "No",
message: result.recordset,
});
}
})
.catch((err) => {
return next(
// ... (error handling)
);
})
} catch (err) {
response.status(500);
response.send(err.message);
};
};
Let's break down the code step by step:
领英推荐
OTP Validation
Now, let's take a look at the code for validating the OTP:
// Importing dependencies
const sql = require(`${process.env.REACT_NODE_PATH}/node_modules/mssql/index`);
const { poolPromise } = require("../config/db");
const redis = require(`${process.env.REACT_NODE_PATH}/node_modules/redis/dist/index`);
const redisPort = 6379
const client = redis.createClient(redisPort);
module.exports = async (request, response, next) => {
let { email, otp } = request.body;
let schema = request.headers["schema"];
try {
// Connect to Redis
await client.connect();
// Retrieve the stored OTP from Redis
const result = await client.get(`${schema}otp${email}`);
// Validate the OTP
if (result === otp) {
response.status(200).json({
otpverified: "Yes",
});
} else {
response.status(400).json({
otpverified: "No",
});
}
} catch (err) {
response.status(500);
response.send(err.message);
};
};
Now, let's go through the code step by step: