Completed
Push — master ( b362d9...2b4a65 )
by Sander
50s
created

$(document).ready   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 7
rs 9.4285
c 1
b 0
f 0
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
        $('.togglePw').click(function () {
61
            $('.togglePw').find('.fa').toggleClass('fa-eye').toggleClass('fa-eye-slash');
62
            if (pwfield.attr('type') === 'password') {
63
                pwfield.attr('type', 'text');
64
            } else {
65
                pwfield.attr('type', 'password');
66
            }
67
        });
68
69
        $('#savepw-save').click(function (e) {
70
            e.preventDefault();
71
            $(this).val('Saving...');
72
            $(this).attr('disabled', true);
73
            API.runtime.sendMessage(API.runtime.id, {
74
                method: "injectCreateCredential", args: {
75
                    label: labelfield.val(),
76
                    username: userfield.val(),
77
                    password: pwfield.val()
78
                }
79
            });
80
        });
81
82
        $('#savepw-cancel').click(function () {
83
            labelfield.val(document.title);
84
            userfield.val('');
85
            pwfield.val('');
86
            removePasswordPicker();
87
            //removePasswordPicker();
88
        });
89
90
    }
91
92
    function toggleFieldType(field) {
93
        if ($(field).attr('type').toLowerCase() === 'text') {
94
            $(field).attr('type', 'password');
95
        } else {
96
            $(field).attr('type', 'text');
97
        }
98
    }
99
100
    function genPwd(settings) {
101
        /* jshint ignore:start */
102
        var password = generatePassword(settings['length'],
103
            settings.useUppercase,
104
            settings.useLowercase,
105
            settings.useDigits,
106
            settings.useSpecialChars,
107
            settings.minimumDigitCount,
108
            settings.avoidAmbiguousCharacters,
109
            settings.requireEveryCharType);
110
        /* jshint ignore:end */
111
        return password;
112
    }
113
114
    function getPasswordGenerationSettings(cb) {
115
        var default_settings = {
116
            'length': 12,
117
            'useUppercase': true,
118
            'useLowercase': true,
119
            'useDigits': true,
120
            'useSpecialChars': true,
121
            'minimumDigitCount': 3,
122
            'avoidAmbiguousCharacters': false,
123
            'requireEveryCharType': true
124
        };
125
        storage.get('password_generator_settings').then(function (_settings) {
126
            if (!_settings) {
127
                _settings = default_settings;
128
            }
129
130
            cb(_settings);
131
        }).error(function () {
132
            cb(default_settings);
133
        });
134
    }
135
136
    function setupPasswordGenerator() {
137
        //getPasswordGeneratorSettings
138
        getPasswordGenerationSettings(function (settings) {
139
            var round = 0;
140
141
            function generate_pass(inputId) {
142
                var new_password = genPwd(settings);
143
                $('#' + inputId).val(new_password);
144
                setTimeout(function () {
145
                    if (round < 10) {
146
                        generate_pass(inputId);
147
                        round++;
148
                    } else {
149
                        round = 0;
150
                    }
151
                }, 10);
152
            }
153
154
            $.each(settings, function (setting, val) {
155
                if (typeof(val) === "boolean") {
156
                    $('[name="' + setting + '"]').prop('checked', val);
157
                } else {
158
                    $('[name="' + setting + '"]').val(val);
159
                }
160
            });
161
162
            $('form[name="advancedSettings"]').change(function () {
163
                var pw_settings_form = $(this);
164
                settings = pw_settings_form.serializeObject();
165
                storage.set('password_generator_settings', settings);
166
            });
167
168
            $('.renewpw').click(function () {
169
                generate_pass('generated_password');
170
            });
171
            $('.renewpw_newac').click(function () {
172
                generate_pass('savepw-password');
173
174
            });
175
            $('.renewpw').click();
176
            $('.renewpw_newac').click();
177
178
            $('.usepwd').click(function () {
179
                $('#savepw-password').val($('#generated_password').val());
180
                $('.tab.add').click();
181
            });
182
183
            $('.togglePwVis').click(function () {
184
                toggleFieldType('#generated_password');
185
                $(this).find('.fa').toggleClass('fa-eye-slash').toggleClass('fa-eye');
186
            });
187
188
            $('.adv_opt').click(function () {
189
190
                var adv_settings = $('.pw-setting-advanced');
191
                $(this).find('i').toggleClass('fa-angle-right').toggleClass('fa-angle-down');
192
                if (adv_settings.is(':visible')) {
193
                    adv_settings.slideUp();
194
                } else {
195
                    adv_settings.slideDown();
196
                }
197
            });
198
        });
199
    }
200
201
    var picker = $('#password_picker');
202
    var makeTabActive = function (name) {
203
        picker.find('.tab').removeClass('active');
204
        picker.find('.tab-content').children().hide();
205
        picker.find('.tab-' + name + '-content').show();
206
        picker.find('.tab.' + name).addClass('active');
207
    };
208
209
    picker.find('.tab').click(function () {
210
        var name = $(this).attr('data-name');
211
        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...
212
            makeTabActive(name)
213
        });
214
215
    });
216
217
    storage.get('activeTab').then(function (name) {
218
        if(name) {
219
            makeTabActive(name);
220
        } else {
221
            makeTabActive('list');
222
        }
223
    });
224
225
    $('.tab.close').click(function () {
226
        removePasswordPicker();
227
    });
228
229
230
    API.runtime.sendMessage(API.runtime.id, {method: "getActiveTab", args: {returnFn: "returnActiveTab"}});
231
232
    function returnActiveTab(tab) {
233
        API.runtime.sendMessage(API.runtime.id, {
234
            method: "getCredentialsByUrl",
235
            args: [tab.url]
236
        }).then(function (logins) {
237
            if(logins.length === 0){
238
                API.runtime.sendMessage(API.runtime.id, {
239
                    'method': 'getSetting',
240
                    args: 'no_results_found_tab'
241
                }).then(function (value) {
242
                    makeTabActive(value);
243
                });
244
                return;
245
            }
246
            if (logins.length !== 0) {
247
                picker.find('.tab-list-content').html('');
248
            }
249
            for (var i = 0; i < logins.length; i++) {
250
                var login = logins[i];
251
                var div = $('<div>', {class: 'account', text: login.label});
252
                $('<br>').appendTo(div);
253
                var username = (login.username.trim() !== '' ) ? login.username : login.email;
254
                $('<small>').text(username).appendTo(div);
255
                /* jshint ignore:start */
256
                div.click((function (login) {
257
                    return function () {
258
                        //enterLoginDetails(login);
259
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
260
                        fillLogin(login)
261
                    };
262
                })(login));
263
                /* jshint ignore:end*/
264
265
                picker.find('.tab-list-content').append(div);
266
            }
267
        });
268
    }
269
270
    _this.returnActiveTab = returnActiveTab;
271
272
273
    $('.no-credentials .save').on('click', function () {
274
        $('.tab.add').click();
275
    });
276
    $('.no-credentials .search').on('click', function () {
277
        $('.tab.search').click();
278
    });
279
    $('.no-credentials .gen').on('click', function () {
280
        $('.tab.generate').click();
281
    });
282
    setupAddCredentialFields();
283
    setupPasswordGenerator();
284
285
286
    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...
287
        if (_this[msg.method]) {
288
            _this[msg.method](msg.args, sender);
289
        }
290
    });
291
292
293
    $('#password_search').keypress(function (e) {
294
        if (e.which === 13) {
295
            searchCredentials();
296
        }
297
    });
298
299
    function url_domain(data) {
300
        var matches = data.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
301
        return matches && matches[1];  // domain will be null if no match is found
302
    }
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
                var username = (login.username.trim() !== '' ) ? login.username : login.email;
324
                $('<small>').text(username).appendTo(div);
325
                $('<br>').appendTo(div);
326
                $('<small>').text(url_domain(login.url)).appendTo(div);
327
                /* jshint ignore:start */
328
                div.click((function (login) {
329
                    return function () {
330
                        //enterLoginDetails(login);
331
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
332
                        fillLogin(login);
333
                        //@TODO Ask to update the url of the login
334
                        API.runtime.sendMessage(API.runtime.id, {
335
                            'method': 'updateCredentialUrlDoorhanger',
336
                            args: login
337
                        })
338
                    };
339
                })(login));
340
                /* jshint ignore:end*/
341
342
                picker.find('#searchResults').append(div);
343
            }
344
        });
345
    }
346
347
});