Completed
Pull Request — master (#47)
by Sander
01:10
created

$(document).ready   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 17
rs 9.2
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
    picker.find('.tab').click(function () {
203
        var target = $(this).attr('class').replace('active', '').replace('tab', '').trim();
204
        picker.find('.tab').removeClass('active');
205
        picker.find('.tab-content').children().hide();
206
        picker.find('.tab-' + target + '-content').show();
207
        picker.find('.tab.' + target).addClass('active');
208
    });
209
210
    $('.tab.close').click(function () {
211
        removePasswordPicker();
212
    });
213
214
215
    API.runtime.sendMessage(API.runtime.id, {method: "getActiveTab", args: {returnFn: "returnActiveTab"}});
216
217
    function returnActiveTab(tab) {
218
        API.runtime.sendMessage(API.runtime.id, {
219
            method: "getCredentialsByUrl",
220
            args: [tab.url]
221
        }).then(function (logins) {
222
            if (logins.length !== 0) {
223
                picker.find('.tab-list-content').html('');
224
            }
225
            for (var i = 0; i < logins.length; i++) {
226
                var login = logins[i];
227
                var div = $('<div>', {class: 'account', text: login.label});
228
                $('<br>').appendTo(div);
229
                var username = (login.username.trim() !== '' ) ? login.username : login.email;
230
                $('<small>').text(username).appendTo(div);
231
                /* jshint ignore:start */
232
                div.click((function (login) {
233
                    return function () {
234
                        //enterLoginDetails(login);
235
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
236
                        fillLogin(login)
237
                    };
238
                })(login));
239
                /* jshint ignore:end*/
240
241
                picker.find('.tab-list-content').append(div);
242
            }
243
        });
244
    }
245
246
    _this.returnActiveTab = returnActiveTab;
247
248
249
    $('.no-credentials .save').on('click', function () {
250
        $('.tab.add').click();
251
    });
252
    $('.no-credentials .search').on('click', function () {
253
        $('.tab.search').click();
254
    });
255
    $('.no-credentials .gen').on('click', function () {
256
        $('.tab.generate').click();
257
    });
258
    setupAddCredentialFields();
259
    setupPasswordGenerator();
260
261
262
    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...
263
        if (_this[msg.method]) {
264
            _this[msg.method](msg.args, sender);
265
        }
266
    });
267
268
269
    $('#password_search').keypress(function (e) {
270
        if (e.which === 13) {
271
            searchCredentials();
272
        }
273
    });
274
275
    function url_domain(data) {
276
        var matches = data.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
277
        return matches && matches[1];  // domain will be null if no match is found
278
    }
279
280
281
    function searchCredentials() {
282
        $('#searchResults').html('');
283
        var searchText = $('#password_search').val();
284
        if (searchText === '') {
285
            return;
286
        }
287
        API.runtime.sendMessage(API.runtime.id, {
288
            'method': 'searchCredential',
289
            args: searchText
290
        }).then(function (result) {
291
            if (result.length === 0) {
292
                $('#searchResults').html(API.i18n.getMessage('no_credentials_found'));
293
            }
294
            for (var i = 0; i < result.length; i++) {
295
                var login = result[i];
296
                var div = $('<div>', {class: 'account', text: login.label});
297
                $('<br>').appendTo(div);
298
                var username = (login.username.trim() !== '' ) ? login.username : login.email;
299
                $('<small>').text(username).appendTo(div);
300
                $('<br>').appendTo(div);
301
                $('<small>').text(url_domain(login.url)).appendTo(div);
302
                /* jshint ignore:start */
303
                div.click((function (login) {
304
                    return function () {
305
                        //enterLoginDetails(login);
306
                        //API.runtime.sendMessage(API.runtime.id, {method: 'getMasterPasswordSet'})
307
                        fillLogin(login);
308
                        //@TODO Ask to update the url of the login
309
                        API.runtime.sendMessage(API.runtime.id, {
310
                            'method': 'updateCredentialUrlDoorhanger',
311
                            args: login
312
                        })
313
                    };
314
                })(login));
315
                /* jshint ignore:end*/
316
317
                picker.find('#searchResults').append(div);
318
            }
319
        });
320
    }
321
322
});