Browse Source

feat(core): add generatePassword utility function

#3677
pull/3678/head
mehmet-erim 7 years ago
parent
commit
56f272df7c
  1. 35
      npm/ng-packs/packages/core/src/lib/tests/generator-utils.spec.ts
  2. 28
      npm/ng-packs/packages/core/src/lib/utils/generator-utils.ts

35
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;
}

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

Loading…
Cancel
Save