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.
These utilities are essential for authentication workflows including email verification, password resets, two-factor authentication, and session management.
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:
Use Cases:
- Email verification codes
- SMS verification codes
- Two-factor authentication (2FA)
- Password reset codes
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:
Use Cases:
- Password reset tokens
- Email verification tokens
- API keys
- Session tokens
- CSRF tokens
4. Generate Hashed Token
Generate a hashed token using SHA-256.
Usage Example:
Use Cases:
- Password reset tokens
- Email verification tokens
- API keys
- Session tokens
- CSRF tokens
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:
Use Cases:
- Unique identifiers for database records
- Request/transaction IDs
- Session IDs
- File upload identifiers
8. Generate Alphanumeric Token
Generate a cryptographically secure alphanumeric token (letters + numbers).
Usage Example:
Use Cases:
- User-friendly verification codes
- Invite codes
- Referral codes
- Promo codes
9. Generate URL-Safe Token
Generate a cryptographically secure URL-safe token (base64url encoding).
Usage Example:
Use Cases:
- Email verification links
- Password reset links
- Magic link authentication
- Share links
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
Usage Examples
Email Verification Flow
Password Reset Flow
API Key Generation
Session Token Generation
Invite Code Generation
Related Components
- Password Hashing - Secure password hashing utilities
- JWT Utils - JSON Web Token generation and verification
- Auth OTP Schema - OTP database schema and management