OTP Utilities
Utility functions for handling one-time password (OTP) generation, delivery, and verification with built-in security features.generateOTP
Generates a cryptographically secure numeric OTP code.Parameters
The length of the OTP code to generate. Defaults to 6 digits.
Returns
Returns a string containing the numeric OTP code of the specified length.Examples
Uses
crypto.getRandomValues() for cryptographically secure random number generation, ensuring OTP codes cannot be predicted.sendOTP
Generates and sends an OTP code via SMS, storing the verification record in the database.Parameters
The phone number or email to send the OTP to
The type of verification: “phone-otp” or “email-otp”
Database adapter for storing verification records
SMS provider instance for sending SMS. Required when type is “phone-otp”.
Optional configuration for OTP length, expiration, and message template
Application name to include in the OTP message
Returns
Whether the OTP was sent successfully
Error message if sending failed
Behavior
- Generates a new OTP using
generateOTP() - Sets expiration time (default 5 minutes / 300 seconds)
- Deletes any existing verification for the identifier
- Creates new verification record with OTP and expiration
- Sends SMS if type is “phone-otp” and SMS provider is configured
- Initializes attempt counter at 0
Examples
The function automatically deletes any existing OTP for the identifier before creating a new one, preventing multiple active OTPs for the same user.
verifyOTP
Verifies an OTP code against the stored verification record with rate limiting.Parameters
The phone number or email the OTP was sent to
The OTP code to verify
The type of verification: “phone-otp” or “email-otp”
Database adapter for retrieving verification records
Maximum number of verification attempts allowed. Defaults to 5.
Returns
Whether the OTP is valid and verification succeeded
Error message if verification failed, with details about the failure reason
Behavior
- Retrieves verification record from database
- Checks if OTP exists, is not expired, and attempts not exceeded
- Increments attempt counter on invalid OTP
- Deletes verification record on success or when max attempts reached
- Provides user-friendly error messages with remaining attempts
Error Cases
- No OTP found: “No OTP found. Please request a new one.”
- Expired: “OTP expired. Please request a new one.”
- Max attempts: “Too many attempts. Please request a new OTP.”
- Invalid OTP: “Invalid OTP. X attempts remaining.”
Examples
The function includes automatic rate limiting by tracking attempts and locking out users after too many failed attempts. The verification record is automatically deleted after successful verification or when max attempts are exceeded.
Default OTP Message
The default OTP message template (bilingual Arabic/English):messageTemplate function in the OTPConfig.