mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
chore: relocate backend into apps/api ahead of monorepo merge
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user