Files
starr-philproperties/utils/otp.util.js
T
2026-05-05 23:18:47 +08:00

44 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/***********************************************************************************************************************************************************************
* File Name: otp.util.js
* Type of Program: Utility
* Description: One-Time Password (OTP) generation and validation helpers.
* - generateOTP() → 6-digit numeric string
* - getOTPExpiry() → Date object N minutes from now
* - isOTPExpired() → boolean check on the stored expiry
* Author: rgrgogu
* Date Created: Oct. 6, 2025
***********************************************************************************************************************************************************************
* HOW TO USE:
* const { generateOTP, getOTPExpiry, isOTPExpired } = require('../utils/otp.util');
* user.otp_code = generateOTP();
* user.otp_expires_at = getOTPExpiry();
***********************************************************************************************************************************************************************/
const crypto = require('crypto');
/**
* Generates a cryptographically secure 6-digit OTP.
* @returns {string} e.g. "048291"
*/
const generateOTP = () => {
const bytes = crypto.randomBytes(3); // 3 bytes = 0–16777215
const num = bytes.readUIntBE(0, 3) % 1_000_000; // force to 0–999999
return num.toString().padStart(6, '0');
};
/**
* Returns a Date object N minutes in the future.
* @param {number} [minutes=10]
* @returns {Date}
*/
const getOTPExpiry = (minutes = Number(process.env.OTP_EXPIRY_MINUTES) || 10) => {
return new Date(Date.now() + minutes * 60 * 1000);
};
/**
* Checks whether the stored OTP has expired.
* @param {Date|string} expiresAt
* @returns {boolean}
*/
const isOTPExpired = (expiresAt) => !expiresAt || new Date() > new Date(expiresAt);
module.exports = { generateOTP, getOTPExpiry, isOTPExpired };