Completed
Push — master ( 641a91...fc9f6a )
by
unknown
10:16
created

angular.controller(ꞌSettingsCtrlꞌ)   C

Complexity

Conditions 6
Paths 25

Size

Total Lines 288

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
dl 0
loc 288
rs 6.0666
c 1
b 1
f 0
nc 25
nop 12

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
/**
2
 * Nextcloud - passman
3
 *
4
 * @copyright Copyright (c) 2016, Sander Brand ([email protected])
5
 * @copyright Copyright (c) 2016, Marcos Zuriaga Miguel ([email protected])
6
 * @license GNU AGPL version 3 or any later version
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License as
10
 * published by the Free Software Foundation, either version 3 of the
11
 * License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
23
(function () {
24
	'use strict';
25
26
27
	/**
28
	 * @ngdoc function
29
	 * @name passmanApp.controller:SettingsCtrl
30
	 * @description
31
	 * # SettingsCtrl
32
	 * Controller of the passmanApp
33
	 */
34
	angular.module('passmanApp')
35
		.controller('SettingsCtrl', ['$scope', '$rootScope', 'SettingsService', 'VaultService', 'CredentialService', '$location', '$routeParams', '$http', 'EncryptService', 'NotificationService', '$sce', '$translate',
36
			function ($scope, $rootScope, SettingsService, VaultService, CredentialService, $location, $routeParams, $http, EncryptService, NotificationService, $sce, $translate) {
37
				$scope.vault_settings = {};
38
				$scope.new_vault_name = '';
39
				$scope.showGenericImport = false;
40
41
				$scope.active_vault = VaultService.getActiveVault();
42
				if (!SettingsService.getSetting('defaultVault') || !SettingsService.getSetting('defaultVaultPass')) {
43
					if (!$scope.active_vault) {
44
						$location.path('/');
45
						return;
46
					}
47
				} else {
48
					if (SettingsService.getSetting('defaultVault') && SettingsService.getSetting('defaultVaultPass')) {
49
						var _vault = angular.copy(SettingsService.getSetting('defaultVault'));
50
						_vault.vaultKey = SettingsService.getSetting('defaultVaultPass');
51
						VaultService.setActiveVault(_vault);
52
						$scope.active_vault = _vault;
53
					}
54
				}
55
56
				VaultService.getVault($scope.active_vault).then(function (vault) {
57
					vault.vaultKey = VaultService.getActiveVault().vaultKey;
58
					delete vault.credentials;
59
					VaultService.setActiveVault(vault);
60
					$scope.vault_settings = vault.vault_settings;
61
					if (!$scope.vault_settings.hasOwnProperty('pwSettings')) {
62
						$scope.vault_settings.pwSettings = {
63
							'length': 12,
64
							'useUppercase': true,
65
							'useLowercase': true,
66
							'useDigits': true,
67
							'useSpecialChars': true,
68
							'minimumDigitCount': 3,
69
							'avoidAmbiguousCharacters': false,
70
							'requireEveryCharType': true,
71
							'generateOnCreate': true
72
						};
73
					}
74
				});
75
76
				var key_strengths = [
77
					'password.poor',
78
					'password.poor',
79
					'password.weak',
80
					'password.good',
81
					'password.strong'
82
				];
83
84
				$scope.minimal_value_key_strength = SettingsService.getSetting('vault_key_strength');
85
				$translate(key_strengths[SettingsService.getSetting('vault_key_strength')]).then(function (translation) {
86
					$scope.required_score = {'strength': translation};
87
				});
88
89
				var btn_txt = $translate.instant('bookmarklet.text');
90
				var http = location.protocol, slashes = http.concat("//"), host = slashes.concat(window.location.hostname), complete = host + location.pathname;
91
				$scope.bookmarklet = $sce.trustAsHtml("<a class=\"button\" href=\"javascript:(function(){var a=window,b=document,c=encodeURIComponent,e=c(document.title),d=a.open('" + complete + "bookmarklet?url='+c(b.location)+'&title='+e,'bkmk_popup','left='+((a.screenX||a.screenLeft)+10)+',top='+((a.screenY||a.screenTop)+10)+',height=750px,width=475px,resizable=0,alwaysRaised=1');a.setTimeout(function(){d.focus()},300);})();\">" + btn_txt + "</a>");
92
93
94
				$scope.saveVaultSettings = function () {
95
					var _vault = $scope.active_vault;
96
					_vault.name = $scope.new_vault_name;
97
					_vault.vault_settings = angular.copy($scope.vault_settings);
98
					VaultService.updateVault(_vault).then(function () {
99
						//VaultService.setActiveVault(_vault);
100
						$scope.active_vault.name = angular.copy(_vault.name);
101
						NotificationService.showNotification($translate.instant('settings.saved'), 5000);
102
					});
103
				};
104
105
106
				$scope.tabs = [
107
					{
108
						title: $translate.instant('settings.general'),
109
						url: 'views/partials/forms/settings/general_settings.html'
110
					},
111
					{
112
						title: $translate.instant('settings.audit'),
113
						url: 'views/partials/forms/settings/tool.html'
114
115
					},
116
					{
117
						title: $translate.instant('settings.password'),
118
						url: 'views/partials/forms/settings/password_settings.html'
119
120
					},
121
					{
122
						title: $translate.instant('settings.import'),
123
						url: 'views/partials/forms/settings/import.html'
124
125
					},
126
					{
127
						title: $translate.instant('settings.export'),
128
						url: 'views/partials/forms/settings/export.html'
129
130
					},
131
					{
132
						title: $translate.instant('settings.sharing'),
133
						url: 'views/partials/forms/settings/sharing.html'
134
					}
135
				];
136
137
				$scope.currentTab = $scope.tabs[0];
138
139
				$scope.onClickTab = function (tab) {
140
					$scope.currentTab = tab;
141
				};
142
143
				$scope.isActiveTab = function (tab) {
144
					return tab.url === $scope.currentTab.url;
145
				};
146
147
				var getPassmanVersion = function () {
148
					var url = OC.generateUrl('apps/passman/api/internal/version');
149
					$http.get(url).then(function (result) {
150
						$scope.passman_version = result.data.version;
151
					});
152
				};
153
				getPassmanVersion();
154
155
				$scope.$watch(function () {
156
					return VaultService.getActiveVault();
157
				}, function (vault) {
158
					if (vault) {
159
						$scope.active_vault = vault;
160
					}
161
				});
162
163
				$rootScope.$on('logout', function () {
164
					$scope.selectedVault = false;
165
				});
166
167
				var getCurrentVaultCredentials = function (callback) {
168
					VaultService.getVault($scope.active_vault).then(callback);
169
				};
170
171
				$scope.startScan = function (minStrength) {
172
					getCurrentVaultCredentials(function (vault) {
173
						var results = [];
174
						for (var i = 0; i < vault.credentials.length; i++) {
175
							var c = angular.copy(vault.credentials[i]);
176
							if (c.password && c.hidden === 0) {
177
								try {
178
									c = CredentialService.decryptCredential(c);
179
									if (c.password) {
180
										var zxcvbn_result = zxcvbn(c.password);
181
										if (zxcvbn_result.score <= minStrength) {
182
											results.push({
183
												guid: c.guid,
184
												label: c.label,
185
												password: c.password,
186
												password_zxcvbn_result: zxcvbn_result
187
											});
188
										}
189
									}
190
								} catch (e) {
191
									console.warn(e);
192
								}
193
194
							}
195
							//@todo loop custom fields (if any and check secret fields
196
						}
197
						$scope.scan_result = results;
198
					});
199
				};
200
201
202
				$scope.cur_state = {};
203
204
205
				$scope.$on("$locationChangeStart", function (event) {
206
					if ($scope.change_pw) {
207
						if ($scope.change_pw.total > 0 && $scope.change_pw.done < $scope.change_pw.total) {
208
							if (!confirm($translate.instant('changepw.navigate.away.warning'))) {
209
								event.preventDefault();
210
							}
211
						}
212
					}
213
				});
214
215
216
				$scope.changeVaultPassword = function (oldVaultPass, newVaultPass, newVaultPass2) {
217
					$scope.error = '';
218
					if (oldVaultPass !== VaultService.getActiveVault().vaultKey) {
219
						$scope.error = $translate.instant('incorrect.password');
220
						return;
221
					}
222
					if (newVaultPass !== newVaultPass2) {
223
						$scope.error = $translate.instant('password.no.match');
224
						return;
225
					}
226
					SettingsService.setSetting('defaultVault', null);
227
					SettingsService.setSetting('defaultVaultPass', null);
228
					VaultService.getVault($scope.active_vault).then(function (vault) {
229
						jQuery('input').attr('disabled', true);
230
						jQuery('button').attr('disabled', true);
231
						var _selected_credentials = angular.copy(vault.credentials);
232
						$scope.change_pw = {
233
							percent: 0,
234
							done: 0,
235
							total: _selected_credentials.length
236
						};
237
						var changeCredential = function (index, oldVaultPass, newVaultPass) {
238
							var usedKey = oldVaultPass;
239
240
							if (_selected_credentials[index].hasOwnProperty('shared_key')) {
241
								if (_selected_credentials[index].shared_key) {
242
									usedKey = EncryptService.decryptString(angular.copy(_selected_credentials[index].shared_key), oldVaultPass);
243
								}
244
							}
245
246
							CredentialService.reencryptCredential(_selected_credentials[index].guid, usedKey, newVaultPass).progress(function (data) {
247
								$scope.cur_state = data;
248
							}).then(function () {
249
								var percent = index / _selected_credentials.length * 100;
250
								$scope.change_pw = {
251
									percent: percent,
252
									done: index + 1,
253
									total: _selected_credentials.length
254
								};
255
								if (index < _selected_credentials.length - 1) {
256
									changeCredential(index + 1, oldVaultPass, newVaultPass);
257
								} else {
258
									vault.private_sharing_key = EncryptService.decryptString(angular.copy(vault.private_sharing_key), oldVaultPass);
259
									vault.private_sharing_key = EncryptService.encryptString(vault.private_sharing_key, newVaultPass);
260
									VaultService.updateSharingKeys(vault).then(function () {
261
										$rootScope.$broadcast('logout');
262
										NotificationService.showNotification($translate.instant('login.new.pass'), 5000);
263
									});
264
								}
265
							});
266
						};
267
						changeCredential(0, VaultService.getActiveVault().vaultKey, newVaultPass);
268
269
					});
270
				};
271
272
				$scope.confirm_vault_delete = false;
273
				$scope.delete_vault_password = '';
274
        $scope.delete_vault = function() {
275
          if ($scope.confirm_vault_delete && $scope.delete_vault_password === VaultService.getActiveVault().vaultKey) {
276
            getCurrentVaultCredentials(function(vault) {
277
              var credentials = vault.credentials;
278
              $scope.remove_pw = {
279
                percent: 0,
280
                done: 0,
281
                total: vault.credentials.length,
282
              };
283
              var deleteCredential = function(index) {
284
                $scope.translationData = {
285
                  password: credentials[index].label,
286
                };
287
                CredentialService.destroyCredential(credentials[index].guid).then(function() {
288
                  var percent = index / vault.credentials.length * 100;
289
                  $scope.remove_pw = {
290
                    percent: percent,
291
                    done: index,
292
                    total: vault.credentials.length,
293
                  };
294
                  if (index === credentials.length - 1) {
295
                    VaultService.deleteVault(vault).then(function() {
296
                      SettingsService.setSetting('defaultVaultPass', false);
297
                      SettingsService.setSetting('defaultVault', null);
298
                      $rootScope.$broadcast('logout');
299
                      $location.path('/');
300
                    });
301
                    return;
302
                  }
303
                  deleteCredential(index + 1);
304
                });
305
              };
306
              deleteCredential(0);
307
            });
308
          }
309
310
        };
311
312
				$rootScope.$on('logout', function () {
313
					$scope.active_vault = null;
314
					VaultService.setActiveVault(null);
315
					$location.path('/');
316
317
				});
318
319
				$scope.cancel = function () {
320
					$location.path('/vault/' + $routeParams.vault_id);
321
				};
322
323
			}]);
324
325
}());