Completed
Push — master ( d74b89...1fbafc )
by Thomas
21:17 queued 09:07
created

Controller::changePersonalPassword()   C

Complexity

Conditions 8
Paths 36

Size

Total Lines 33
Code Lines 23

Duplication

Lines 10
Ratio 30.3 %

Importance

Changes 0
Metric Value
cc 8
eloc 23
nc 36
nop 1
dl 10
loc 33
rs 5.3846
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Björn Schießle <[email protected]>
4
 * @author Christopher Schäpers <[email protected]>
5
 * @author Christoph Wurst <[email protected]>
6
 * @author Clark Tomlinson <[email protected]>
7
 * @author cmeh <[email protected]>
8
 * @author Florin Peter <[email protected]>
9
 * @author Jakob Sack <[email protected]>
10
 * @author Lukas Reschke <[email protected]>
11
 * @author Robin Appelman <[email protected]>
12
 * @author Sam Tuke <[email protected]>
13
 * @author Thomas Müller <[email protected]>
14
 * @author Ujjwal Bhardwaj <[email protected]>
15
 * @author Yarno Boelens <[email protected]>
16
 *
17
 * @copyright Copyright (c) 2017, ownCloud GmbH
18
 * @license AGPL-3.0
19
 *
20
 * This code is free software: you can redistribute it and/or modify
21
 * it under the terms of the GNU Affero General Public License, version 3,
22
 * as published by the Free Software Foundation.
23
 *
24
 * This program is distributed in the hope that it will be useful,
25
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27
 * GNU Affero General Public License for more details.
28
 *
29
 * You should have received a copy of the GNU Affero General Public License, version 3,
30
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
31
 *
32
 */
33
namespace OC\Settings\ChangePassword;
34
35
class Controller {
36
	public static function changePersonalPassword($args) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
37
		// Check if we are an user
38
		\OC_JSON::callCheck();
39
		\OC_JSON::checkLoggedIn();
40
41
		$username = \OC_User::getUser();
42
		$password = isset($_POST['personal-password']) ? $_POST['personal-password'] : null;
43
		$oldPassword = isset($_POST['oldpassword']) ? $_POST['oldpassword'] : '';
44
45 View Code Duplication
		if (!\OC_User::checkPassword($username, $oldPassword)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Bug Best Practice introduced by
The expression \OC_User::checkPassword($username, $oldPassword) of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
46
			$l = \OC::$server->getL10NFactory()->get('settings');
47
			\OC_JSON::error(["data" => ["message" => $l->t("Wrong password")]]);
48
			exit();
49
		}
50 View Code Duplication
		if ($oldPassword === $password) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
			$l = \OC::$server->getL10NFactory()->get('settings');
52
			\OC_JSON::error(["data" => ["message" => $l->t("The new password can not be the same as the previous one")]]);
53
			exit();
54
	        }
55
		try {
56
			if (!is_null($password) && \OC_User::setPassword($username, $password)) {
57
				\OC::$server->getUserSession()->updateSessionTokenPassword($password);
58
59
				self::sendNotificationMail($username);
60
61
				\OC_JSON::success();
62
			} else {
63
				\OC_JSON::error();
64
			}
65
		} catch (\Exception $e) {
66
			\OC_JSON::error(['data' => ['message' => $e->getMessage()]]);
67
		}
68
	}
69
70
	public static function changeUserPassword($args) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
71
		// Check if we are an user
72
		\OC_JSON::callCheck();
73
		\OC_JSON::checkLoggedIn();
74
75
		$l = \OC::$server->getL10NFactory()->get('settings');
76
		if (isset($_POST['username'])) {
77
			$username = $_POST['username'];
78
		} else {
79
			\OC_JSON::error(['data' => ['message' => $l->t('No user supplied')]]);
80
			exit();
81
		}
82
83
		$password = isset($_POST['password']) ? $_POST['password'] : null;
84
		$recoveryPassword = isset($_POST['recoveryPassword']) ? $_POST['recoveryPassword'] : null;
85
86
		$isUserAccessible = false;
87
		$currentUserObject = \OC::$server->getUserSession()->getUser();
88
		$targetUserObject = \OC::$server->getUserManager()->get($username);
89 View Code Duplication
		if($currentUserObject !== null && $targetUserObject !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
			$isUserAccessible = \OC::$server->getGroupManager()->getSubAdmin()->isUserAccessible($currentUserObject, $targetUserObject);
91
		}
92
93
		if (\OC_User::isAdminUser(\OC_User::getUser())) {
94
			$userstatus = 'admin';
95
		} elseif ($isUserAccessible) {
96
			$userstatus = 'subadmin';
97
		} else {
98
			\OC_JSON::error(['data' => ['message' => $l->t('Authentication error')]]);
99
			exit();
100
		}
101
102
		if (\OC_App::isEnabled('encryption')) {
103
			//handle the recovery case
104
			$crypt = new \OCA\Encryption\Crypto\Crypt(
105
				\OC::$server->getLogger(),
106
				\OC::$server->getUserSession(),
107
				\OC::$server->getConfig(),
108
				\OC::$server->getL10N('encryption'));
109
			$keyStorage = \OC::$server->getEncryptionKeyStorage();
110
			$util = new \OCA\Encryption\Util(
111
				new \OC\Files\View(),
112
				$crypt,
113
				\OC::$server->getLogger(),
114
				\OC::$server->getUserSession(),
115
				\OC::$server->getConfig(),
116
				\OC::$server->getUserManager());
117
			$keyManager = new \OCA\Encryption\KeyManager(
118
				$keyStorage,
119
				$crypt,
120
				\OC::$server->getConfig(),
121
				\OC::$server->getUserSession(),
122
				new \OCA\Encryption\Session(\OC::$server->getSession()),
123
				\OC::$server->getLogger(),
124
				$util);
125
			$recovery = new \OCA\Encryption\Recovery(
126
				\OC::$server->getUserSession(),
127
				$crypt,
128
				\OC::$server->getSecureRandom(),
129
				$keyManager,
130
				\OC::$server->getConfig(),
131
				$keyStorage,
132
				\OC::$server->getEncryptionFilesHelper(),
133
				new \OC\Files\View());
134
			$recoveryAdminEnabled = $recovery->isRecoveryKeyEnabled();
135
136
			$validRecoveryPassword = false;
137
			$recoveryEnabledForUser = false;
138
			if ($recoveryAdminEnabled) {
139
				$validRecoveryPassword = $keyManager->checkRecoveryPassword($recoveryPassword);
140
				$recoveryEnabledForUser = $recovery->isRecoveryEnabledForUser($username);
141
			}
142
143
			if ($recoveryEnabledForUser && $recoveryPassword === '') {
144
				\OC_JSON::error(['data' => [
145
					'message' => $l->t('Please provide an admin recovery password; otherwise, all user data will be lost.')
146
				]]);
147 View Code Duplication
			} elseif ($recoveryEnabledForUser && ! $validRecoveryPassword) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
				\OC_JSON::error(['data' => [
149
					'message' => $l->t('Wrong admin recovery password. Please check the password and try again.')
150
				]]);
151
			} else { // now we know that everything is fine regarding the recovery password, let's try to change the password
152
				$result = \OC_User::setPassword($username, $password, $recoveryPassword);
153
				if (!$result && $recoveryEnabledForUser) {
154
					\OC_JSON::error([
155
						"data" => [
156
							"message" => $l->t("Backend doesn't support password change, but the user's encryption key was successfully updated.")
157
						]
158
					]);
159 View Code Duplication
				} elseif (!$result && !$recoveryEnabledForUser) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
160
					\OC_JSON::error(["data" => ["message" => $l->t("Unable to change password" )]]);
161
				} else {
162
					self::sendNotificationMail($username);
163
					\OC_JSON::success(["data" => ["username" => $username]]);
164
				}
165
166
			}
167
		} else { // if encryption is disabled, proceed
168
			try {
169
				if (!is_null($password) && \OC_User::setPassword($username, $password)) {
170
					self::sendNotificationMail($username);
171
					\OC_JSON::success(['data' => ['username' => $username]]);
172
				} else {
173
					\OC_JSON::error(['data' => ['message' => $l->t('Unable to change password')]]);
174
				}
175
			} catch (\Exception $e) {
176
				\OC_JSON::error(['data' => ['message' => $e->getMessage()]]);
177
			}
178
		}
179
	}
180
181
	private static function sendNotificationMail($username) {
182
		$userObject = \OC::$server->getUserManager()->get($username);
183
		$email = $userObject->getEMailAddress();
184
		$defaults = new \OC_Defaults();
185
		$from = \OCP\Util::getDefaultEmailAddress('lostpassword-noreply');
186
		$mailer = \OC::$server->getMailer();
187
		$lion = \OC::$server->getL10N('lib');
188
189
		if ($email !== null && $email !== '') {
190
			$tmpl = new \OC_Template('core', 'lostpassword/notify');
191
			$msg = $tmpl->fetchPage();
192
193
			try {
194
				$message = $mailer->createMessage();
195
				$message->setTo([$email => $username]);
196
				$message->setSubject($lion->t('%s password changed successfully', [$defaults->getName()]));
197
				$message->setPlainBody($msg);
0 ignored issues
show
Bug introduced by
It seems like $msg defined by $tmpl->fetchPage() on line 191 can also be of type boolean; however, OC\Mail\Message::setPlainBody() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
198
				$message->setFrom([$from => $defaults->getName()]);
199
				$mailer->send($message);
200
			} catch (\Exception $e) {
201
				throw new \Exception($lion->t(
202
					'Couldn\'t send reset email. Please contact your administrator.'
203
				));
204
			}
205
		}
206
	}
207
}
208