Browse Source

Merge pull request #3678 from abpframework/feat/generate-password

feat(core): add generatePassword utility function
pull/3702/head
Levent Arman Özak 6 years ago
committed by GitHub
parent
commit
2f706dec86
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 34
      npm/ng-packs/packages/core/src/lib/tests/generator-utils.spec.ts
  2. 24
      npm/ng-packs/packages/core/src/lib/utils/generator-utils.ts

34
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);
}

24
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('');
}

Loading…
Cancel
Save