This commit is contained in:
rgrgogu
2026-05-05 23:18:47 +08:00
parent 5aeb959e92
commit a8f10a25d7
38 changed files with 5992 additions and 2 deletions
+44
View File
@@ -0,0 +1,44 @@
/***********************************************************************************************************************************************************************
* 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 };