Completed
Push — master ( 38220d...613c8b )
by Sander
15s
created

$(document).ready   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

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 3
rs 10
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('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
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) {
224
            makeTabActive(name);
225
        }
226
    });
227
228
    $('.tab.close').click(function () {
229
        removePasswordPicker();
230
    });
231
232
233
    API.runtime.sendMessage(API.runtime.id, {method: "getActiveTab", args: {returnFn: "returnActiveTab"}});
234
235
    function returnActiveTab(tab) {
236
        API.runtime.sendMessage(API.runtime.id, {
237
            method: "getCredentialsByUrl",
238
            args: [tab.url]
239
        }).then(function (logins) {
240
            if (logins.length === 0) {
241
                API.runtime.sendMessage(API.runtime.id, {
242
                    'method': 'getSetting',
243
                    args: 'no_results_found_tab'
244
                }).then(function (value) {
245
                    makeTabActive(value);
246
                });
247
                return;
248
            }
249
            if (logins.length !== 0) {
250
                picker.find('.tab-list-content').html('');
251
            }
252
            for (var i = 0; i < logins.length; i++) {
253
                var login = logins[i];
254
                var div = $('<div>', {class: 'account', text: login.label});
255
                $('<br>').appendTo(div);
256
                var username = (login.username !== '' ) ? login.username : login.email;
257
                $('<small>').text(username).appendTo(div);
258
                /* jshint ignore:start */
259
                div.click((function (login) {
260
                    return function () {
261
                        //enterLoginDetails(login);
262
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
263
                        fillLogin(login)
264
                    };
265
                })(login));
266
                /* jshint ignore:end*/
267
268
                picker.find('.tab-list-content').append(div);
269
            }
270
        });
271
    }
272
273
    _this.returnActiveTab = returnActiveTab;
274
275
276
    $('.no-credentials .save').on('click', function () {
277
        $('.tab.add').click();
278
    });
279
    $('.no-credentials .search').on('click', function () {
280
        $('.tab.search').click();
281
    });
282
    $('.no-credentials .gen').on('click', function () {
283
        $('.tab.generate').click();
284
    });
285
    setupAddCredentialFields();
286
    setupPasswordGenerator();
287
288
289
    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...
290
        if (_this[msg.method]) {
291
            _this[msg.method](msg.args, sender);
292
        }
293
    });
294
295
296
    $('#password_search').keypress(function (e) {
297
        if (e.which === 13) {
298
            searchCredentials();
299
        }
300
    });
301
302
    function url_domain(data) {
303
        var matches = data.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
304
        return matches && matches[1];  // domain will be null if no match is found
305
    }
306
307
308
    function searchCredentials() {
309
        $('#searchResults').html('');
310
        var searchText = $('#password_search').val();
311
        if (searchText === '') {
312
            return;
313
        }
314
        API.runtime.sendMessage(API.runtime.id, {
315
            'method': 'searchCredential',
316
            args: searchText
317
        }).then(function (result) {
318
            if (result.length === 0 || !result) {
319
                $('#searchResults').html(API.i18n.getMessage('no_credentials_found'));
320
            }
321
            for (var i = 0; i < result.length; i++) {
322
                var login = result[i];
323
                var div = $('<div>', {class: 'account', text: login.label});
324
                $('<br>').appendTo(div);
325
326
                var username = (login.username !== '' ) ? login.username : login.email;
327
                $('<small>').text(username).appendTo(div);
328
                $('<br>').appendTo(div);
329
                $('<small>').text(url_domain(login.url)).appendTo(div);
330
                /* jshint ignore:start */
331
                div.click((function (login) {
332
                    return function () {
333
                        //enterLoginDetails(login);
334
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
335
                        fillLogin(login);
336
                        //@TODO Ask to update the url of the login
337
                        API.runtime.sendMessage(API.runtime.id, {
338
                            'method': 'updateCredentialUrlDoorhanger',
339
                            args: login
340
                        })
341
                    };
342
                })(login));
343
                /* jshint ignore:end*/
344
345
                picker.find('#searchResults').append(div);
346
            }
347
        });
348
    }
349
350
    API.runtime.sendMessage(API.runtime.id, {'method': 'getRuntimeSettings'}).then(function (settings) {
351
        var accounts = settings.accounts;
352
        for(var i = 0; i < accounts.length; i++) {
353
            $('#savepw-vault').append('<option value=' + i + '>' + accounts[i].vault.name + '</option>');
354
        }
355
    });
356
});
357