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..841d9e6d35 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,36 @@ describe('GeneratorUtils', () => { expect(hash).toBe(1112440527); }); }); + + describe('#generatePassword', () => { + const lowers = 'abcdefghijklmnopqrstuvwxyz'; + const uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + const numbers = '0123456789'; + const specials = '!@#$%&*()_+{}<>?[]./'; + + test.each` + name | charSet | passedPasswordLength | actualPasswordLength + ${'lower'} | ${lowers} | ${Infinity} | ${128} + ${'lower'} | ${lowers} | ${129} | ${128} + ${'lower'} | ${lowers} | ${10} | ${10} + ${'lower'} | ${lowers} | ${7} | ${7} + ${'upper'} | ${uppers} | ${6} | ${6} + ${'number'} | ${numbers} | ${5} | ${5} + ${'special'} | ${specials} | ${4} | ${4} + ${'special'} | ${specials} | ${2} | ${4} + ${'special'} | ${specials} | ${0} | ${4} + ${'special'} | ${specials} | ${undefined} | ${8} + `( + 'should have a $name in the password that length is $passwordLength', + ({ _, charSet, passedPasswordLength, actualPasswordLength }) => { + const password = generatePassword(passedPasswordLength); + expect(password).toHaveLength(actualPasswordLength); + expect(hasChar(charSet, password)).toBe(true); + }, + ); + }); }); + +function hasChar(charSet: string, password: string): boolean { + return charSet.split('').some(char => password.indexOf(char) > -1); +} 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..a5fd4c9c65 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,27 @@ export function generateHash(value: string): number { } return hashed; } + +export function generatePassword(length = 8) { + length = Math.min(Math.max(4, length), 128); + + 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)]; + + const password = Array({ length }); + password[0] = getRandom(lowers); + password[1] = getRandom(uppers); + password[2] = getRandom(numbers); + password[3] = getRandom(specials); + + for (let i = 4; i < length; i++) { + password[i] = getRandom(all); + } + + return password.sort(() => 0.5 - Math.random()).join(''); +}