Completed
Push — master ( f66285...6c7ad9 )
by Sander
17s
created

$(document).ready   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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