|
| 1 | +/** |
| 2 | + * @athenna/common |
| 3 | + * |
| 4 | + * (c) João Lenon <lenon@athenna.io> |
| 5 | + * |
| 6 | + * For the full copyright and license information, please view the LICENSE |
| 7 | + * file that was distributed with this source code. |
| 8 | + */ |
| 9 | + |
| 10 | +import otpGenerator from 'otp-generator' |
| 11 | + |
| 12 | +export class Otp { |
| 13 | + /** |
| 14 | + * Generate an OTP token. |
| 15 | + */ |
| 16 | + public static generate(prefix?: string) { |
| 17 | + if (prefix) { |
| 18 | + return `${prefix}::${otpGenerator.generate(6, { |
| 19 | + digits: true, |
| 20 | + specialChars: false, |
| 21 | + upperCaseAlphabets: true, |
| 22 | + lowerCaseAlphabets: false |
| 23 | + })}` |
| 24 | + } |
| 25 | + |
| 26 | + return otpGenerator.generate(6, { |
| 27 | + digits: true, |
| 28 | + specialChars: false, |
| 29 | + upperCaseAlphabets: true, |
| 30 | + lowerCaseAlphabets: false |
| 31 | + }) |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Return the token without his prefix. |
| 36 | + */ |
| 37 | + public static getToken(token: string): string { |
| 38 | + const prefix = Otp.getPrefix(token) |
| 39 | + |
| 40 | + if (!prefix) { |
| 41 | + return token |
| 42 | + } |
| 43 | + |
| 44 | + return token.split(`${prefix}::`)[1] |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Return the prefix without his token. |
| 49 | + */ |
| 50 | + public static getPrefix(token: string): string | null { |
| 51 | + const prefix = token.split('::')[0] |
| 52 | + |
| 53 | + /** |
| 54 | + * Means that the "::" char has not been |
| 55 | + * found. So there is no prefix in the token. |
| 56 | + */ |
| 57 | + if (prefix === token) { |
| 58 | + return null |
| 59 | + } |
| 60 | + |
| 61 | + return prefix |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Inject a prefix in the uuid token. |
| 66 | + */ |
| 67 | + public static injectPrefix(prefix: string, token: string): string { |
| 68 | + return `${prefix}::${token}` |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Change the prefix of an OTP token. |
| 73 | + */ |
| 74 | + public static changePrefix(newPrefix: string, token: string): string { |
| 75 | + const otp = this.getToken(token) |
| 76 | + |
| 77 | + return `${newPrefix}::${otp}` |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Change the token prefix or generate a new one. |
| 82 | + */ |
| 83 | + public static changeOrGenerate(prefix: string, token?: string): string { |
| 84 | + if (token) { |
| 85 | + return this.changePrefix(prefix, token) |
| 86 | + } |
| 87 | + |
| 88 | + return this.generate(prefix) |
| 89 | + } |
| 90 | +} |
0 commit comments