Completed
Push — master ( 255913...eeecda )
by Sander
14s
created

$(document).ready   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
c 0
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
    var runtimeSettings = {};
5
6
    API.runtime.sendMessage(API.runtime.id, {'method': 'getRuntimeSettings'}).then(function (settings) {
7
        var accounts = settings.accounts;
8
        runtimeSettings = settings;
9
        for(var i = 0; i < accounts.length; i++) {
10
            $('#savepw-vault').append('<option value=' + i + '>' + accounts[i].vault.name + '</option>');
11
        }
12
        storage.get('activeTab').then(function (name) {
13
            if (name && name !== '') {
14
                makeTabActive(name);
15
                API.runtime.sendMessage(API.runtime.id, {method: "getActiveTab", args: {returnFn: "returnActiveTab"}});
16
            }
17
        });
18
19
    });
20
21
    $('[t]').each(function () {
22
        var string = $(this).attr('t');
23
        var startChar = string[0];
24
        var endChar = string[string.length - 1];
25
        var attribute;
26
        if (startChar === '[' && endChar === ']') {
27
            var data = string.replace('[', '').replace(']', '').split(',');
28
            attribute = data[1].trim();
29
            string = data[0].trim();
30
        }
31
        var translated = API.i18n.getMessage(string);
32
        if (attribute) {
33
            $(this).attr(attribute, translated);
34
        } else {
35
            $(this).text(translated);
36
        }
37
    });
38
39
    function fillLogin(login) {
40
        API.runtime.sendMessage(API.runtime.id, {
41
            method: 'passToParent',
42
            args: {
43
                injectMethod: 'enterLoginDetails',
44
                args: login
45
            }
46
        }).then(function () {
47
            removePasswordPicker();
48
        });
49
    }
50
51
    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...
52
        API.runtime.sendMessage(API.runtime.id, {
53
            method: 'passToParent',
54
            args: {
55
                injectMethod: 'removePasswordPicker'
56
            }
57
        });
58
    }
59
60
    function copyTextToClipboard(text) {
61
        var copyFrom = document.createElement("textarea");
62
        copyFrom.textContent = text;
63
        var body = document.getElementsByTagName('body')[0];
64
        body.appendChild(copyFrom);
65
        copyFrom.select();
66
        document.execCommand('copy');
67
        body.removeChild(copyFrom);
68
    }
69
70
    _this.copyTextToClipboard = copyTextToClipboard;
71
72
73
    function setupAddCredentialFields() {
74
        var labelfield = $('#savepw-label');
75
        labelfield.val(document.title);
76
        var userfield = $('#savepw-username');
77
        var pwfield = $('#savepw-password');
78
        var vaultfield = $('#savepw-vault');
79
        $('.togglePw').click(function () {
80
            $('.togglePw').find('.fa').toggleClass('fa-eye').toggleClass('fa-eye-slash');
81
            if (pwfield.attr('type') === 'password') {
82
                pwfield.attr('type', 'text');
83
            } else {
84
                pwfield.attr('type', 'password');
85
            }
86
        });
87
88
        $('#savepw-save').click(function (e) {
89
            e.preventDefault();
90
            $(this).text(API.i18n.getMessage("saving"));
91
            $(this).attr('disabled', true);
92
            API.runtime.sendMessage(API.runtime.id, {
93
                method: "injectCreateCredential",
94
                args: {
95
                    label: labelfield.val(),
96
                    username: userfield.val(),
97
                    password: pwfield.val(),
98
                    vaultIndex: vaultfield.val()
99
                }
100
            }).then(removePasswordPicker);
101
        });
102
103
        $('#savepw-cancel').click(function () {
104
            labelfield.val(document.title);
105
            userfield.val('');
106
            pwfield.val('');
107
            removePasswordPicker();
108
        });
109
110
    }
111
112
    function toggleFieldType(field) {
113
        if ($(field).attr('type').toLowerCase() === 'text') {
114
            $(field).attr('type', 'password');
115
        } else {
116
            $(field).attr('type', 'text');
117
        }
118
    }
119
120
    function genPwd(settings) {
121
        /* jshint ignore:start */
122
        var password = generatePassword(settings['length'],
123
            settings.useUppercase,
124
            settings.useLowercase,
125
            settings.useDigits,
126
            settings.useSpecialChars,
127
            settings.minimumDigitCount,
128
            settings.avoidAmbiguousCharacters,
129
            settings.requireEveryCharType);
130
        /* jshint ignore:end */
131
        return password;
132
    }
133
134
    function getPasswordGenerationSettings(cb) {
135
        var default_settings = {
136
            'length': 12,
137
            'useUppercase': true,
138
            'useLowercase': true,
139
            'useDigits': true,
140
            'useSpecialChars': true,
141
            'minimumDigitCount': 3,
142
            'avoidAmbiguousCharacters': false,
143
            'requireEveryCharType': true
144
        };
145
        storage.get('password_generator_settings').then(function (_settings) {
146
            if (!_settings) {
147
                _settings = default_settings;
148
            }
149
150
            cb(_settings);
151
        }).error(function () {
152
            cb(default_settings);
153
        });
154
    }
155
156
    function setupPasswordGenerator() {
157
        //getPasswordGeneratorSettings
158
        getPasswordGenerationSettings(function (settings) {
159
            var round = 0;
160
161
            function generate_pass(inputId) {
162
                var new_password = genPwd(settings);
163
                $('#' + inputId).val(new_password);
164
                setTimeout(function () {
165
                    if (round < 10) {
166
                        generate_pass(inputId);
167
                        round++;
168
                    } else {
169
                        round = 0;
170
                    }
171
                }, 10);
172
            }
173
174
            $.each(settings, function (setting, val) {
175
                if (typeof(val) === "boolean") {
176
                    $('[name="' + setting + '"]').prop('checked', val);
177
                } else {
178
                    $('[name="' + setting + '"]').val(val);
179
                }
180
            });
181
182
            $('form[name="advancedSettings"]').change(function () {
183
                var pw_settings_form = $(this);
184
                settings = pw_settings_form.serializeObject();
185
                storage.set('password_generator_settings', settings);
186
            });
187
188
            $('.renewpw').click(function () {
189
                generate_pass('generated_password');
190
            });
191
            $('.renewpw_newac').click(function () {
192
                generate_pass('savepw-password');
193
194
            });
195
            $('.renewpw').click();
196
            $('.renewpw_newac').click();
197
198
            $('.usepwd').click(function () {
199
                $('#savepw-password').val($('#generated_password').val());
200
                $('.tab.add').click();
201
            });
202
203
            $('.togglePwVis').click(function () {
204
                toggleFieldType('#generated_password');
205
                $(this).find('.fa').toggleClass('fa-eye-slash').toggleClass('fa-eye');
206
            });
207
208
            $('.adv_opt').click(function () {
209
210
                var adv_settings = $('.pw-setting-advanced');
211
                $(this).find('i').toggleClass('fa-angle-right').toggleClass('fa-angle-down');
212
                if (adv_settings.is(':visible')) {
213
                    adv_settings.slideUp();
214
                } else {
215
                    adv_settings.slideDown();
216
                }
217
            });
218
        });
219
    }
220
221
    var picker = $('#password_picker');
222
    var makeTabActive = function (name) {
223
        picker.find('.tab').removeClass('active');
224
        picker.find('.tab-content').children().hide();
225
        picker.find('.tab-' + name + '-content').show();
226
        picker.find('.tab.' + name).addClass('active');
227
    };
228
229
    picker.find('.tab').click(function () {
230
        var name = $(this).attr('data-name');
231
        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...
232
            makeTabActive(name);
233
        });
234
    });
235
    
236
237
238
    $('.tab.close').click(function () {
239
        removePasswordPicker();
240
    });
241
242
243
    function disablePassman(where, url){
244
        var whereFn = (where === 'site') ? 'Site' : 'URL';
245
        API.runtime.sendMessage(API.runtime.id, {
246
            method: "ignore"+ whereFn,
247
            args: url
248
        }).then(function () {
249
            var text = (where === 'site') ? 'site_ignored' : 'url_ignored';
250
            $('.tab-ignore-content').find('.text').text(API.i18n.getMessage(text));
251
            setTimeout(function () {
252
                removePasswordPicker();
253
            }, 2500);
254
        });
255
    }
256
257
258
259
    function returnActiveTab(tab) {
260
261
        $('.disable-site').on('click', function () {
262
            disablePassman('site', tab.url);
263
        });
264
265
        $('.disable-page').on('click', function () {
266
            disablePassman('url', tab.url);
267
        });
268
269
        API.runtime.sendMessage(API.runtime.id, {
270
            method: "getCredentialsByUrl",
271
            args: [tab.url]
272
        }).then(function (logins) {
273
            if (logins.length === 0) {
274
                API.runtime.sendMessage(API.runtime.id, {
275
                    'method': 'getSetting',
276
                    args: 'no_results_found_tab'
277
                }).then(function (value) {
278
                    makeTabActive(value);
279
                });
280
                return;
281
            }
282
            if (logins.length !== 0) {
283
                picker.find('.tab-list-content').html('');
284
                if(runtimeSettings.passwordPickerGotoList){
285
                    makeTabActive('list');
286
                }
287
            }
288
            for (var i = 0; i < logins.length; i++) {
289
                var login = logins[i];
290
                var div = $('<div>', {class: 'account', text: login.label});
291
                $('<br>').appendTo(div);
292
                var username = (login.username !== '' ) ? login.username : login.email;
293
                $('<small>').text(username).appendTo(div);
294
                /* jshint ignore:start */
295
                div.click((function (login) {
296
                    return function () {
297
                        //enterLoginDetails(login);
298
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
299
                        fillLogin(login)
300
                    };
301
                })(login));
302
                /* jshint ignore:end*/
303
304
                picker.find('.tab-list-content').append(div);
305
            }
306
        });
307
    }
308
309
    _this.returnActiveTab = returnActiveTab;
310
311
312
    $('.no-credentials .save').on('click', function () {
313
        $('.tab.add').click();
314
    });
315
    $('.no-credentials .search').on('click', function () {
316
        $('.tab.search').click();
317
    });
318
    $('.no-credentials .gen').on('click', function () {
319
        $('.tab.generate').click();
320
    });
321
    setupAddCredentialFields();
322
    setupPasswordGenerator();
323
324
325
    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...
326
        if (_this[msg.method]) {
327
            _this[msg.method](msg.args, sender);
328
        }
329
    });
330
331
332
    $('#password_search').keypress(function (e) {
333
        if (e.which === 13) {
334
            searchCredentials();
335
        }
336
    });
337
338
    function url_domain(data) {
339
        if(!data){
340
            return '';
341
        }
342
        var matches = data.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
343
        return matches && matches[1];  // domain will be null if no match is found
344
    }
345
346
347
    function searchCredentials() {
348
        $('#searchResults').html('');
349
        var searchText = $('#password_search').val();
350
        if (searchText === '') {
351
            return;
352
        }
353
        API.runtime.sendMessage(API.runtime.id, {
354
            'method': 'searchCredential',
355
            args: searchText
356
        }).then(function (result) {
357
            if (result.length === 0 || !result) {
358
                $('#searchResults').html(API.i18n.getMessage('no_credentials_found'));
359
            }
360
            for (var i = 0; i < result.length; i++) {
361
                var login = result[i];
362
                var div = $('<div>', {class: 'account', text: login.label});
363
                $('<br>').appendTo(div);
364
365
                var username = (login.username !== '' ) ? login.username : login.email;
366
                $('<small>').text(username).appendTo(div);
367
                $('<br>').appendTo(div);
368
                $('<small>').text(url_domain(login.url)).appendTo(div);
369
                /* jshint ignore:start */
370
                div.click((function (login) {
371
                    return function () {
372
                        //enterLoginDetails(login);
373
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
374
                        fillLogin(login);
375
                        //@TODO Ask to update the url of the login
376
                        API.runtime.sendMessage(API.runtime.id, {
377
                            'method': 'updateCredentialUrlDoorhanger',
378
                            args: login
379
                        })
380
                    };
381
                })(login));
382
                /* jshint ignore:end*/
383
384
                picker.find('#searchResults').append(div);
385
            }
386
        });
387
    }
388
389
});
390