Completed
Push — master ( 26d227...b1490b )
by Sander
52s
created

$(document).ready   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
rs 9.4285
1
$(document).ready(function () {
2
    var _this = this;
3
    var storage = new API.Storage();
4
5
    $('[t]').each(function () {
6
        var string = $(this).attr('t');
7
        var startChar = string[0];
8
        var endChar = string[string.length - 1];
9
        var attribute;
10
        if (startChar === '[' && endChar === ']') {
11
            var data = string.replace('[', '').replace(']', '').split(',');
12
            attribute = data[1].trim();
13
            string = data[0].trim();
14
        }
15
        var translated = API.i18n.getMessage(string);
16
        if (attribute) {
17
            $(this).attr(attribute, translated);
18
        } else {
19
            $(this).text(translated);
20
        }
21
    });
22
23
    function fillLogin(login) {
24
        API.runtime.sendMessage(API.runtime.id, {
25
            method: 'passToParent',
26
            args: {
27
                injectMethod: 'enterLoginDetails',
28
                args: login
29
            }
30
        });
31
    }
32
33
    function removePasswordPicker(login) {
0 ignored issues
show
Unused Code introduced by
The parameter login is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
34
        API.runtime.sendMessage(API.runtime.id, {
35
            method: 'passToParent',
36
            args: {
37
                injectMethod: 'removePasswordPicker'
38
            }
39
        });
40
    }
41
42
    function copyTextToClipboard(text) {
43
        var copyFrom = document.createElement("textarea");
44
        copyFrom.textContent = text;
45
        var body = document.getElementsByTagName('body')[0];
46
        body.appendChild(copyFrom);
47
        copyFrom.select();
48
        document.execCommand('copy');
49
        body.removeChild(copyFrom);
50
    }
51
52
    _this.copyTextToClipboard = copyTextToClipboard;
53
54
55
    function setupAddCredentialFields() {
56
        var labelfield = $('#savepw-label');
57
        labelfield.val(document.title);
58
        var userfield = $('#savepw-username');
59
        var pwfield = $('#savepw-password');
60
        var vaultfield = $('#savepw-vault');
61
        $('.togglePw').click(function () {
62
            $('.togglePw').find('.fa').toggleClass('fa-eye').toggleClass('fa-eye-slash');
63
            if (pwfield.attr('type') === 'password') {
64
                pwfield.attr('type', 'text');
65
            } else {
66
                pwfield.attr('type', 'password');
67
            }
68
        });
69
70
        $('#savepw-save').click(function (e) {
71
            e.preventDefault();
72
            $(this).text('Saving...');
73
            $(this).attr('disabled', true);
74
            API.runtime.sendMessage(API.runtime.id, {
75
                method: "injectCreateCredential",
76
                args: {
77
                    label: labelfield.val(),
78
                    username: userfield.val(),
79
                    password: pwfield.val(),
80
                    vaultIndex: vaultfield.val()
81
                }
82
            });
83
        });
84
85
        $('#savepw-cancel').click(function () {
86
            labelfield.val(document.title);
87
            userfield.val('');
88
            pwfield.val('');
89
            removePasswordPicker();
90
        });
91
92
    }
93
94
    function toggleFieldType(field) {
95
        if ($(field).attr('type').toLowerCase() === 'text') {
96
            $(field).attr('type', 'password');
97
        } else {
98
            $(field).attr('type', 'text');
99
        }
100
    }
101
102
    function genPwd(settings) {
103
        /* jshint ignore:start */
104
        var password = generatePassword(settings['length'],
105
            settings.useUppercase,
106
            settings.useLowercase,
107
            settings.useDigits,
108
            settings.useSpecialChars,
109
            settings.minimumDigitCount,
110
            settings.avoidAmbiguousCharacters,
111
            settings.requireEveryCharType);
112
        /* jshint ignore:end */
113
        return password;
114
    }
115
116
    function getPasswordGenerationSettings(cb) {
117
        var default_settings = {
118
            'length': 12,
119
            'useUppercase': true,
120
            'useLowercase': true,
121
            'useDigits': true,
122
            'useSpecialChars': true,
123
            'minimumDigitCount': 3,
124
            'avoidAmbiguousCharacters': false,
125
            'requireEveryCharType': true
126
        };
127
        storage.get('password_generator_settings').then(function (_settings) {
128
            if (!_settings) {
129
                _settings = default_settings;
130
            }
131
132
            cb(_settings);
133
        }).error(function () {
134
            cb(default_settings);
135
        });
136
    }
137
138
    function setupPasswordGenerator() {
139
        //getPasswordGeneratorSettings
140
        getPasswordGenerationSettings(function (settings) {
141
            var round = 0;
142
143
            function generate_pass(inputId) {
144
                var new_password = genPwd(settings);
145
                $('#' + inputId).val(new_password);
146
                setTimeout(function () {
147
                    if (round < 10) {
148
                        generate_pass(inputId);
149
                        round++;
150
                    } else {
151
                        round = 0;
152
                    }
153
                }, 10);
154
            }
155
156
            $.each(settings, function (setting, val) {
157
                if (typeof(val) === "boolean") {
158
                    $('[name="' + setting + '"]').prop('checked', val);
159
                } else {
160
                    $('[name="' + setting + '"]').val(val);
161
                }
162
            });
163
164
            $('form[name="advancedSettings"]').change(function () {
165
                var pw_settings_form = $(this);
166
                settings = pw_settings_form.serializeObject();
167
                storage.set('password_generator_settings', settings);
168
            });
169
170
            $('.renewpw').click(function () {
171
                generate_pass('generated_password');
172
            });
173
            $('.renewpw_newac').click(function () {
174
                generate_pass('savepw-password');
175
176
            });
177
            $('.renewpw').click();
178
            $('.renewpw_newac').click();
179
180
            $('.usepwd').click(function () {
181
                $('#savepw-password').val($('#generated_password').val());
182
                $('.tab.add').click();
183
            });
184
185
            $('.togglePwVis').click(function () {
186
                toggleFieldType('#generated_password');
187
                $(this).find('.fa').toggleClass('fa-eye-slash').toggleClass('fa-eye');
188
            });
189
190
            $('.adv_opt').click(function () {
191
192
                var adv_settings = $('.pw-setting-advanced');
193
                $(this).find('i').toggleClass('fa-angle-right').toggleClass('fa-angle-down');
194
                if (adv_settings.is(':visible')) {
195
                    adv_settings.slideUp();
196
                } else {
197
                    adv_settings.slideDown();
198
                }
199
            });
200
        });
201
    }
202
203
    var picker = $('#password_picker');
204
    var makeTabActive = function (name) {
205
        picker.find('.tab').removeClass('active');
206
        picker.find('.tab-content').children().hide();
207
        picker.find('.tab-' + name + '-content').show();
208
        picker.find('.tab.' + name).addClass('active');
209
    };
210
211
    picker.find('.tab').click(function () {
212
        var name = $(this).attr('data-name');
213
        storage.set('activeTab', name).then(function (r) {
0 ignored issues
show
Unused Code introduced by
The parameter r is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
214
            makeTabActive(name);
215
        });
216
217
    });
218
    
219
    makeTabActive('list');
220
    storage.get('activeTab').then(function (name) {
221
        if (name) {
222
            makeTabActive(name);
223
        }
224
    });
225
226
    $('.tab.close').click(function () {
227
        removePasswordPicker();
228
    });
229
230
231
    API.runtime.sendMessage(API.runtime.id, {method: "getActiveTab", args: {returnFn: "returnActiveTab"}});
232
233
    function returnActiveTab(tab) {
234
        API.runtime.sendMessage(API.runtime.id, {
235
            method: "getCredentialsByUrl",
236
            args: [tab.url]
237
        }).then(function (logins) {
238
            if (logins.length === 0) {
239
                API.runtime.sendMessage(API.runtime.id, {
240
                    'method': 'getSetting',
241
                    args: 'no_results_found_tab'
242
                }).then(function (value) {
243
                    makeTabActive(value);
244
                });
245
                return;
246
            }
247
            if (logins.length !== 0) {
248
                picker.find('.tab-list-content').html('');
249
            }
250
            for (var i = 0; i < logins.length; i++) {
251
                var login = logins[i];
252
                var div = $('<div>', {class: 'account', text: login.label});
253
                $('<br>').appendTo(div);
254
                var username = (login.username !== '' ) ? login.username : login.email;
255
                $('<small>').text(username).appendTo(div);
256
                /* jshint ignore:start */
257
                div.click((function (login) {
258
                    return function () {
259
                        //enterLoginDetails(login);
260
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
261
                        fillLogin(login)
262
                    };
263
                })(login));
264
                /* jshint ignore:end*/
265
266
                picker.find('.tab-list-content').append(div);
267
            }
268
        });
269
    }
270
271
    _this.returnActiveTab = returnActiveTab;
272
273
274
    $('.no-credentials .save').on('click', function () {
275
        $('.tab.add').click();
276
    });
277
    $('.no-credentials .search').on('click', function () {
278
        $('.tab.search').click();
279
    });
280
    $('.no-credentials .gen').on('click', function () {
281
        $('.tab.generate').click();
282
    });
283
    setupAddCredentialFields();
284
    setupPasswordGenerator();
285
286
287
    API.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
0 ignored issues
show
Unused Code introduced by
The parameter sendResponse is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
288
        if (_this[msg.method]) {
289
            _this[msg.method](msg.args, sender);
290
        }
291
    });
292
293
294
    $('#password_search').keypress(function (e) {
295
        if (e.which === 13) {
296
            searchCredentials();
297
        }
298
    });
299
300
    function url_domain(data) {
301
        var matches = data.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
302
        return matches && matches[1];  // domain will be null if no match is found
303
    }
304
305
306
    function searchCredentials() {
307
        $('#searchResults').html('');
308
        var searchText = $('#password_search').val();
309
        if (searchText === '') {
310
            return;
311
        }
312
        API.runtime.sendMessage(API.runtime.id, {
313
            'method': 'searchCredential',
314
            args: searchText
315
        }).then(function (result) {
316
            if (result.length === 0 || !result) {
317
                $('#searchResults').html(API.i18n.getMessage('no_credentials_found'));
318
            }
319
            for (var i = 0; i < result.length; i++) {
320
                var login = result[i];
321
                var div = $('<div>', {class: 'account', text: login.label});
322
                $('<br>').appendTo(div);
323
324
                var username = (login.username !== '' ) ? login.username : login.email;
325
                $('<small>').text(username).appendTo(div);
326
                $('<br>').appendTo(div);
327
                $('<small>').text(url_domain(login.url)).appendTo(div);
328
                /* jshint ignore:start */
329
                div.click((function (login) {
330
                    return function () {
331
                        //enterLoginDetails(login);
332
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
333
                        fillLogin(login);
334
                        //@TODO Ask to update the url of the login
335
                        API.runtime.sendMessage(API.runtime.id, {
336
                            'method': 'updateCredentialUrlDoorhanger',
337
                            args: login
338
                        })
339
                    };
340
                })(login));
341
                /* jshint ignore:end*/
342
343
                picker.find('#searchResults').append(div);
344
            }
345
        });
346
    }
347
348
    API.runtime.sendMessage(API.runtime.id, {'method': 'getRuntimeSettings'}).then(function (settings) {
349
        var accounts = settings.accounts;
350
        for(var i = 0; i < accounts.length; i++) {
351
            $('#savepw-vault').append('<option value=' + i + '>' + accounts[i].vault.name + '</option>');
352
        }
353
    });
354
});
355