Generate OTP/Token Helper Functions
The Generate OTP/Token Helper Functions component provides cryptographically secure utility functions for generating one-time passwords (OTPs), random tokens, and unique identifiers.
All functions use Node.js's built-in node:crypto module to ensure cryptographic randomness and security.
Installation Guide
Install the component using the servercn CLI:
npx servercn-cli add generate-otp-tokenFile Structure
MVC: src/helpers/token.helpers.ts
Feature: src/shared/helpers/token.helpers.ts
Core Functions
1. Generate OTP (One-Time Password)
Generate a cryptographically secure numeric OTP of any length (default: 6 digits).
Usage Examples:
2. Verify OTP
Verify an OTP code against its hash and expiration time.
Usage Example:
3. Generate Secure Random Token
Generate a cryptographically secure random token using hexadecimal encoding.
Usage Example:
4. Generate Hashed Token
Generate a hashed token using SHA-256.
Usage Example:
5. Generate Token and Hashed Token
Generate a token and hashed token using SHA-256.
Usage Example:
6. Verify Hashed Token
Verify a hashed token using SHA-256.
Usage Example:
7. Generate UUID (Universally Unique Identifier)
Generate a RFC 4122 version 4 UUID.
Usage Example:
8. Generate Alphanumeric Token
Generate a cryptographically secure alphanumeric token (letters + numbers).
Usage Example:
9. Generate URL-Safe Token
Generate a cryptographically secure URL-safe token (base64url encoding).
Usage Example:
10. Generate Numeric Code
Generate a cryptographically secure numeric code (alternative to OTP with better distribution).
Usage:
Complete Implementation
Here's a complete implementation file with all utility functions:
MVC Structure: src/helpers/token.helpers.ts
Feature Structure: src/shared/helpers/token.helpers.ts