Implementing OTP Generation and Validation with Redis in Node.js

Implementing OTP Generation and Validation with Redis in Node.js

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:

  1. Importing Dependencies:Import various Node.js modules and packages using require.
  2. Setting Up Redis Client:Create a Redis client and connects it to the Redis server running on port 6379.
  3. Middleware Function Definition:Export an asynchronous middleware function that takes three parameters: request, response, and next (common in Express.js middleware).The function extracts various parameters from the request body and the request headers.
  4. Connection to Redis:Connect to the Redis server using client.connect().
  5. Generating a Random OTP:A new OTP is generated as a random 6-digit number using Math.random().
  6. Database Interaction (Using MSSQL):Interact with the SQL Server database using the mssql package. Use a connection pool (poolPromise) to execute a stored procedure named Add_Customer_Website from the specified schema (schema obtained from the request headers).
  7. Checking if the Customer is Existing:If the result from the database indicates that the customer is not existing (existing_customer === 'no'), it sends an email containing the generated OTP using nodemailer. The email content is an HTML template with the OTP.Then update the Redis cache with the OTP associated with the customer's email.
  8. Sending Email:The email is sent using the Gmail SMTP server. The email subject is "Here Is Your Login OTP!".
  9. Handling Email Sending Results:Respond to the client with a JSON object indicating whether the email was sent (mailsent: "Yes") and includes information from the database result.
  10. Error Handling:Include error handling using try, catch, and catch blocks. If an error occurs during the execution of the middleware function or the database operations, it returns an error response.
  11. Final Response:If the customer is identified as an existing customer, it responds to the client with a JSON object indicating that the email was not sent (mailsent: "No").

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:

  1. Importing Dependencies:The code imports necessary modules, including mssql for SQL Server interaction and redis for connecting to the Redis server.
  2. Setting Up Redis Client:It creates a Redis client and connects it to the Redis server running on port 6379.
  3. Middleware Function Definition:Export an asynchronous middleware function, similar to the OTP generation code, taking request, response, and next as parameters.
  4. Extracting Request Parameters:Extract the email and otp parameters from the request body and the schema from the request headers.
  5. Connecting to Redis:Connect to the Redis server using await client.connect().
  6. Retrieving Stored OTP from Redis:Retrieve the stored OTP associated with the provided email from the Redis cache using await client.get(). The key used for retrieval is ${schema}otp${email}. This is used to make the key unique.
  7. OTP Validation:Compare the retrieved OTP with the OTP provided in the request. If the OTPs match, it sends a JSON response with a status of 200 and the message "otpverified: "Yes". If the OTPs do not match, it sends a JSON response with a status of 400 and the message "otpverified: "No".
  8. Error Handling:If any errors occur during the process (e.g., connection issues or Redis errors), it catches the errors and sends a response with a status of 500 along with the error message.

要查看或添加评论,请登录

Satish Chander的更多文章

社区洞察

其他会员也浏览了