Completed
Pull Request — master (#161)
by
unknown
01:21
created

$(document).ready   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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