Last active
April 6, 2022 16:27
-
-
Save NuroDev/2149390ee1d508cd296514369f733311 to your computer and use it in GitHub Desktop.
π Generate OTP - A simple TypeScript function to generate a one-time passcode (OTP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { randomInt } from "crypto"; | |
interface GenerateOtpOptions { | |
/** | |
* Chars | |
* | |
* @description Whether to include A-Z characters in the generated passcode | |
* | |
* @default true | |
*/ | |
chars: boolean; | |
/** | |
* Digits | |
* | |
* @description Whether to include numbers 0-9 in the generated passcode | |
* | |
* @default true | |
*/ | |
digits: boolean; | |
/** | |
* Length | |
* | |
* @description The total length / size of the code to generate | |
* | |
* @default 6 | |
*/ | |
length: number; | |
} | |
const digits = "0123456789" as const; | |
const alphabet = "abcdefghijklmnopqrstuvwxyz" as const; | |
/** | |
* Generate OTP | |
* | |
* Generates a one-time passcode (OTP) from a provided provided | |
* length using chars and/or digits. | |
* | |
* @param {Object} [options] | |
* @param {boolean} [options.chars=true] - Include A-Z characters | |
* @param {boolean} [options.digits=true] - Include numbers 0-9 | |
* @param {boolean} [options.length=6] - Length of the generated string | |
*/ | |
export function generateOtp(options?: Partial<GenerateOtpOptions>): string { | |
const combinedOptions = Object.assign( | |
{ | |
chars: true, | |
digits: true, | |
length: 6, | |
}, | |
options | |
); | |
if (combinedOptions.length <= 0) | |
throw new Error("OTP length is too short. Please select a longer length."); | |
// Build an array of all possible character's to pick from | |
const allowedChars: string = [ | |
...(combinedOptions.chars ? [alphabet, alphabet.toUpperCase()] : []), | |
...(combinedOptions.digits ? [digits] : []), | |
].join(""); | |
let token: string = ""; | |
while (token.length < combinedOptions.length) { | |
token += allowedChars[randomInt(0, allowedChars.length)]; | |
} | |
return token; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment