diff --git a/npm/ng-packs/packages/core/src/lib/tests/generator-utils.spec.ts b/npm/ng-packs/packages/core/src/lib/tests/generator-utils.spec.ts index e09be3fb4f..b74e0f34f6 100644 --- a/npm/ng-packs/packages/core/src/lib/tests/generator-utils.spec.ts +++ b/npm/ng-packs/packages/core/src/lib/tests/generator-utils.spec.ts @@ -1,4 +1,4 @@ -import { generateHash } from '../utils'; +import { generateHash, generatePassword } from '../utils'; describe('GeneratorUtils', () => { describe('#generateHash', () => { @@ -7,4 +7,37 @@ describe('GeneratorUtils', () => { expect(hash).toBe(1112440527); }); }); + + describe('#generatePassword', () => { + const lowers = 'abcdefghijklmnopqrstuvwxyz'; + const uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + const numbers = '0123456789'; + const specials = '!@#$%&*()_+{}<>?[]./'; + + test.each` + name | charSet | passwordLength + ${'lower'} | ${lowers} | ${7} + ${'upper'} | ${uppers} | ${6} + ${'number'} | ${numbers} | ${5} + ${'special'} | ${specials} | ${4} + `( + 'should have a $name in the password that length is $passwordLength', + ({ _, charSet, passwordLength }) => { + const password = generatePassword(passwordLength); + expect(hasChar(charSet, password)).toBe(true); + }, + ); + }); }); + +function hasChar(charSet: string, password: string): boolean { + let matched = false; + charSet.split('').forEach(char => { + if (password.indexOf(char) > -1) { + matched = true; + return; + } + }); + + return matched; +} diff --git a/npm/ng-packs/packages/core/src/lib/utils/generator-utils.ts b/npm/ng-packs/packages/core/src/lib/utils/generator-utils.ts index cc88e216d6..2ce743038a 100644 --- a/npm/ng-packs/packages/core/src/lib/utils/generator-utils.ts +++ b/npm/ng-packs/packages/core/src/lib/utils/generator-utils.ts @@ -17,3 +17,31 @@ export function generateHash(value: string): number { } return hashed; } + +export function generatePassword(length = 8) { + length = length < 4 ? 4 : length; + + const lowers = 'abcdefghijklmnopqrstuvwxyz'; + const uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + const numbers = '0123456789'; + const specials = '!@#$%&*()_+{}<>?[]./'; + const all = lowers + uppers + numbers + specials; + + const getRandom = (chrSet: string) => chrSet[Math.floor(Math.random() * chrSet.length)]; + + let password = ''; + + password += getRandom(lowers); + password += getRandom(uppers); + password += getRandom(numbers); + password += getRandom(specials); + + for (let i = 1; i <= length - 4; i++) { + password = password.concat(getRandom(all)); + } + + return password + .split('') + .sort(() => 0.5 - Math.random()) + .join(''); +}