-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (84 loc) · 2.72 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const options = ['specials', 'lowercase', 'uppercase', 'numbers'];
const availableChars = {
specials: '!@#$%^&*()_+{}:"<>?\|[];\',./`~',
lowercase: 'abcdefghijklmnopqrstuvwxyz',
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
numbers: '0123456789'
}
function shuffle(string) {
const array = string.split('');
let tmp, current, top = array.length;
if (top) while (--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array.join('');
}
function randPickOne(avaiChars) {
const character = avaiChars.charAt(Math.floor(Math.random() * avaiChars.length));
return character;
}
function randPick(exclusions, avaiChars, min, max) {
const numChars = max !== undefined ? min + Math.floor(Math.random() * (max - min + 1)) : min;
let chars = '';
let i = 0;
while (i < numChars) {
const character = randPickOne(avaiChars);
if (exclusions.indexOf(character) < 0 && chars.indexOf(character) < 0) {
chars += character;
i++;
}
}
return chars;
}
function generatePassword(passwordLength, selectedOptions) {
let password = '', totalChars = '';
let firstRoundPick = 3;
if (passwordLength < 9) { // 6, 7, 8
firstRoundPick = selectedOptions.length < 3 ? 2 : 1;
} else if (passwordLength < 13) { // 9, 10, 11, 12
firstRoundPick = selectedOptions.length < 3 ? 3 : 2;
}
selectedOptions.forEach(i => {
totalChars += availableChars[i];
password += randPick(password, availableChars[i], 1, firstRoundPick);
})
const restLength = passwordLength - password.length;
for (let i=0;i<restLength;i++) password += randPickOne(totalChars);
return shuffle(password);
}
function showError(errorMessage) {
const $err = $('.spg-error');
$err.text(errorMessage);
$err.fadeIn(150);
}
function hideError() {
$('.spg-error').fadeOut(0);
}
$('#spg-btn-gen').click(() => {
const passwordLength = $('#spg-pwd-len').val();
const selectedOptions = options.filter(i => {
return $(`#spg-cb-${i}`).prop('checked');
})
if (selectedOptions.length == 0) {
return showError('Require at least one option selected')
}
hideError();
$('#spg-inp-pwd').val(generatePassword(passwordLength, selectedOptions));
})
$('#spg-inp-pwd').click((function () {
this.select();
}));
$('#spg-btn-copy').click(() => {
$('#spg-inp-pwd').select();
document.execCommand('copy');
$('.spg-copied').fadeIn(150);
setTimeout(() => {
$('.spg-copied').fadeOut(100);
}, 1000);
})
$('a[href]').click(function() {
chrome.tabs.create({active: true, url: this.href})
})