Completed
Pull Request — master (#4003)
by Morris
12:21
created
core/Controller/LostController.php 2 patches
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -54,266 +54,266 @@
 block discarded – undo
54 54
  */
55 55
 class LostController extends Controller {
56 56
 
57
-	/** @var IURLGenerator */
58
-	protected $urlGenerator;
59
-	/** @var IUserManager */
60
-	protected $userManager;
61
-	/** @var \OC_Defaults */
62
-	protected $defaults;
63
-	/** @var IL10N */
64
-	protected $l10n;
65
-	/** @var string */
66
-	protected $from;
67
-	/** @var IManager */
68
-	protected $encryptionManager;
69
-	/** @var IConfig */
70
-	protected $config;
71
-	/** @var ISecureRandom */
72
-	protected $secureRandom;
73
-	/** @var IMailer */
74
-	protected $mailer;
75
-	/** @var ITimeFactory */
76
-	protected $timeFactory;
77
-	/** @var ICrypto */
78
-	protected $crypto;
79
-
80
-	/**
81
-	 * @param string $appName
82
-	 * @param IRequest $request
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IUserManager $userManager
85
-	 * @param \OC_Defaults $defaults
86
-	 * @param IL10N $l10n
87
-	 * @param IConfig $config
88
-	 * @param ISecureRandom $secureRandom
89
-	 * @param string $defaultMailAddress
90
-	 * @param IManager $encryptionManager
91
-	 * @param IMailer $mailer
92
-	 * @param ITimeFactory $timeFactory
93
-	 * @param ICrypto $crypto
94
-	 */
95
-	public function __construct($appName,
96
-								IRequest $request,
97
-								IURLGenerator $urlGenerator,
98
-								IUserManager $userManager,
99
-								\OC_Defaults $defaults,
100
-								IL10N $l10n,
101
-								IConfig $config,
102
-								ISecureRandom $secureRandom,
103
-								$defaultMailAddress,
104
-								IManager $encryptionManager,
105
-								IMailer $mailer,
106
-								ITimeFactory $timeFactory,
107
-								ICrypto $crypto) {
108
-		parent::__construct($appName, $request);
109
-		$this->urlGenerator = $urlGenerator;
110
-		$this->userManager = $userManager;
111
-		$this->defaults = $defaults;
112
-		$this->l10n = $l10n;
113
-		$this->secureRandom = $secureRandom;
114
-		$this->from = $defaultMailAddress;
115
-		$this->encryptionManager = $encryptionManager;
116
-		$this->config = $config;
117
-		$this->mailer = $mailer;
118
-		$this->timeFactory = $timeFactory;
119
-		$this->crypto = $crypto;
120
-	}
121
-
122
-	/**
123
-	 * Someone wants to reset their password:
124
-	 *
125
-	 * @PublicPage
126
-	 * @NoCSRFRequired
127
-	 *
128
-	 * @param string $token
129
-	 * @param string $userId
130
-	 * @return TemplateResponse
131
-	 */
132
-	public function resetform($token, $userId) {
133
-		try {
134
-			$this->checkPasswordResetToken($token, $userId);
135
-		} catch (\Exception $e) {
136
-			return new TemplateResponse(
137
-				'core', 'error', [
138
-					"errors" => array(array("error" => $e->getMessage()))
139
-				],
140
-				'guest'
141
-			);
142
-		}
143
-
144
-		return new TemplateResponse(
145
-			'core',
146
-			'lostpassword/resetpassword',
147
-			array(
148
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
149
-			),
150
-			'guest'
151
-		);
152
-	}
153
-
154
-	/**
155
-	 * @param string $token
156
-	 * @param string $userId
157
-	 * @throws \Exception
158
-	 */
159
-	protected function checkPasswordResetToken($token, $userId) {
160
-		$user = $this->userManager->get($userId);
161
-		if($user === null) {
162
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
163
-		}
164
-
165
-		try {
166
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
167
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
168
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
169
-		} catch (\Exception $e) {
170
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
171
-		}
172
-
173
-		$splittedToken = explode(':', $decryptedToken);
174
-		if(count($splittedToken) !== 2) {
175
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
176
-		}
177
-
178
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
179
-			$user->getLastLogin() > $splittedToken[0]) {
180
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
181
-		}
182
-
183
-		if (!hash_equals($splittedToken[1], $token)) {
184
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185
-		}
186
-	}
187
-
188
-	/**
189
-	 * @param $message
190
-	 * @param array $additional
191
-	 * @return array
192
-	 */
193
-	private function error($message, array $additional=array()) {
194
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
195
-	}
196
-
197
-	/**
198
-	 * @return array
199
-	 */
200
-	private function success() {
201
-		return array('status'=>'success');
202
-	}
203
-
204
-	/**
205
-	 * @PublicPage
206
-	 * @BruteForceProtection passwordResetEmail
207
-	 *
208
-	 * @param string $user
209
-	 * @return array
210
-	 */
211
-	public function email($user){
212
-		// FIXME: use HTTP error codes
213
-		try {
214
-			$this->sendEmail($user);
215
-		} catch (\Exception $e){
216
-			return $this->error($e->getMessage());
217
-		}
218
-
219
-		return $this->success();
220
-	}
221
-
222
-	/**
223
-	 * @PublicPage
224
-	 * @param string $token
225
-	 * @param string $userId
226
-	 * @param string $password
227
-	 * @param boolean $proceed
228
-	 * @return array
229
-	 */
230
-	public function setPassword($token, $userId, $password, $proceed) {
231
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
232
-			return $this->error('', array('encryption' => true));
233
-		}
234
-
235
-		try {
236
-			$this->checkPasswordResetToken($token, $userId);
237
-			$user = $this->userManager->get($userId);
238
-
239
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
240
-
241
-			if (!$user->setPassword($password)) {
242
-				throw new \Exception();
243
-			}
244
-
245
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
246
-
247
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
248
-			@\OC_User::unsetMagicInCookie();
249
-		} catch (\Exception $e){
250
-			return $this->error($e->getMessage());
251
-		}
252
-
253
-		return $this->success();
254
-	}
255
-
256
-	/**
257
-	 * @param string $user
258
-	 * @throws \Exception
259
-	 */
260
-	protected function sendEmail($user) {
261
-		if (!$this->userManager->userExists($user)) {
262
-			throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
263
-		}
264
-
265
-		$userObject = $this->userManager->get($user);
266
-		$email = $userObject->getEMailAddress();
267
-
268
-		if (empty($email)) {
269
-			throw new \Exception(
270
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
271
-			);
272
-		}
273
-
274
-		$token = $this->config->getUserValue($user, 'core', 'lostpassword');
275
-		if ($token !== '') {
276
-			$token = $this->crypto->decrypt($token, $email.$this->config->getSystemValue('secret'));
277
-			$splittedToken = explode(':', $token);
278
-			if ((count($splittedToken)) === 2 && $splittedToken[0] > ($this->timeFactory->getTime() - 60 * 5)) {
279
-				throw new \Exception(
280
-					$this->l10n->t('The email is not sent because a password reset email was sent recently.')
281
-				);
282
-			}
283
-		}
284
-
285
-		// Generate the token. It is stored encrypted in the database with the
286
-		// secret being the users' email address appended with the system secret.
287
-		// This makes the token automatically invalidate once the user changes
288
-		// their email address.
289
-		$token = $this->secureRandom->generate(
290
-			21,
291
-			ISecureRandom::CHAR_DIGITS.
292
-			ISecureRandom::CHAR_LOWER.
293
-			ISecureRandom::CHAR_UPPER
294
-		);
295
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
296
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
297
-		$this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
298
-
299
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
300
-
301
-		$tmpl = new \OC_Template('core', 'lostpassword/email');
302
-		$tmpl->assign('link', $link);
303
-		$msg = $tmpl->fetchPage();
304
-
305
-		try {
306
-			$message = $this->mailer->createMessage();
307
-			$message->setTo([$email => $user]);
308
-			$message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
309
-			$message->setPlainBody($msg);
310
-			$message->setFrom([$this->from => $this->defaults->getName()]);
311
-			$this->mailer->send($message);
312
-		} catch (\Exception $e) {
313
-			throw new \Exception($this->l10n->t(
314
-				'Couldn\'t send reset email. Please contact your administrator.'
315
-			));
316
-		}
317
-	}
57
+    /** @var IURLGenerator */
58
+    protected $urlGenerator;
59
+    /** @var IUserManager */
60
+    protected $userManager;
61
+    /** @var \OC_Defaults */
62
+    protected $defaults;
63
+    /** @var IL10N */
64
+    protected $l10n;
65
+    /** @var string */
66
+    protected $from;
67
+    /** @var IManager */
68
+    protected $encryptionManager;
69
+    /** @var IConfig */
70
+    protected $config;
71
+    /** @var ISecureRandom */
72
+    protected $secureRandom;
73
+    /** @var IMailer */
74
+    protected $mailer;
75
+    /** @var ITimeFactory */
76
+    protected $timeFactory;
77
+    /** @var ICrypto */
78
+    protected $crypto;
79
+
80
+    /**
81
+     * @param string $appName
82
+     * @param IRequest $request
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IUserManager $userManager
85
+     * @param \OC_Defaults $defaults
86
+     * @param IL10N $l10n
87
+     * @param IConfig $config
88
+     * @param ISecureRandom $secureRandom
89
+     * @param string $defaultMailAddress
90
+     * @param IManager $encryptionManager
91
+     * @param IMailer $mailer
92
+     * @param ITimeFactory $timeFactory
93
+     * @param ICrypto $crypto
94
+     */
95
+    public function __construct($appName,
96
+                                IRequest $request,
97
+                                IURLGenerator $urlGenerator,
98
+                                IUserManager $userManager,
99
+                                \OC_Defaults $defaults,
100
+                                IL10N $l10n,
101
+                                IConfig $config,
102
+                                ISecureRandom $secureRandom,
103
+                                $defaultMailAddress,
104
+                                IManager $encryptionManager,
105
+                                IMailer $mailer,
106
+                                ITimeFactory $timeFactory,
107
+                                ICrypto $crypto) {
108
+        parent::__construct($appName, $request);
109
+        $this->urlGenerator = $urlGenerator;
110
+        $this->userManager = $userManager;
111
+        $this->defaults = $defaults;
112
+        $this->l10n = $l10n;
113
+        $this->secureRandom = $secureRandom;
114
+        $this->from = $defaultMailAddress;
115
+        $this->encryptionManager = $encryptionManager;
116
+        $this->config = $config;
117
+        $this->mailer = $mailer;
118
+        $this->timeFactory = $timeFactory;
119
+        $this->crypto = $crypto;
120
+    }
121
+
122
+    /**
123
+     * Someone wants to reset their password:
124
+     *
125
+     * @PublicPage
126
+     * @NoCSRFRequired
127
+     *
128
+     * @param string $token
129
+     * @param string $userId
130
+     * @return TemplateResponse
131
+     */
132
+    public function resetform($token, $userId) {
133
+        try {
134
+            $this->checkPasswordResetToken($token, $userId);
135
+        } catch (\Exception $e) {
136
+            return new TemplateResponse(
137
+                'core', 'error', [
138
+                    "errors" => array(array("error" => $e->getMessage()))
139
+                ],
140
+                'guest'
141
+            );
142
+        }
143
+
144
+        return new TemplateResponse(
145
+            'core',
146
+            'lostpassword/resetpassword',
147
+            array(
148
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
149
+            ),
150
+            'guest'
151
+        );
152
+    }
153
+
154
+    /**
155
+     * @param string $token
156
+     * @param string $userId
157
+     * @throws \Exception
158
+     */
159
+    protected function checkPasswordResetToken($token, $userId) {
160
+        $user = $this->userManager->get($userId);
161
+        if($user === null) {
162
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
163
+        }
164
+
165
+        try {
166
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
167
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
168
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
169
+        } catch (\Exception $e) {
170
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
171
+        }
172
+
173
+        $splittedToken = explode(':', $decryptedToken);
174
+        if(count($splittedToken) !== 2) {
175
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
176
+        }
177
+
178
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
179
+            $user->getLastLogin() > $splittedToken[0]) {
180
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
181
+        }
182
+
183
+        if (!hash_equals($splittedToken[1], $token)) {
184
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185
+        }
186
+    }
187
+
188
+    /**
189
+     * @param $message
190
+     * @param array $additional
191
+     * @return array
192
+     */
193
+    private function error($message, array $additional=array()) {
194
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
195
+    }
196
+
197
+    /**
198
+     * @return array
199
+     */
200
+    private function success() {
201
+        return array('status'=>'success');
202
+    }
203
+
204
+    /**
205
+     * @PublicPage
206
+     * @BruteForceProtection passwordResetEmail
207
+     *
208
+     * @param string $user
209
+     * @return array
210
+     */
211
+    public function email($user){
212
+        // FIXME: use HTTP error codes
213
+        try {
214
+            $this->sendEmail($user);
215
+        } catch (\Exception $e){
216
+            return $this->error($e->getMessage());
217
+        }
218
+
219
+        return $this->success();
220
+    }
221
+
222
+    /**
223
+     * @PublicPage
224
+     * @param string $token
225
+     * @param string $userId
226
+     * @param string $password
227
+     * @param boolean $proceed
228
+     * @return array
229
+     */
230
+    public function setPassword($token, $userId, $password, $proceed) {
231
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
232
+            return $this->error('', array('encryption' => true));
233
+        }
234
+
235
+        try {
236
+            $this->checkPasswordResetToken($token, $userId);
237
+            $user = $this->userManager->get($userId);
238
+
239
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
240
+
241
+            if (!$user->setPassword($password)) {
242
+                throw new \Exception();
243
+            }
244
+
245
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
246
+
247
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
248
+            @\OC_User::unsetMagicInCookie();
249
+        } catch (\Exception $e){
250
+            return $this->error($e->getMessage());
251
+        }
252
+
253
+        return $this->success();
254
+    }
255
+
256
+    /**
257
+     * @param string $user
258
+     * @throws \Exception
259
+     */
260
+    protected function sendEmail($user) {
261
+        if (!$this->userManager->userExists($user)) {
262
+            throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
263
+        }
264
+
265
+        $userObject = $this->userManager->get($user);
266
+        $email = $userObject->getEMailAddress();
267
+
268
+        if (empty($email)) {
269
+            throw new \Exception(
270
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
271
+            );
272
+        }
273
+
274
+        $token = $this->config->getUserValue($user, 'core', 'lostpassword');
275
+        if ($token !== '') {
276
+            $token = $this->crypto->decrypt($token, $email.$this->config->getSystemValue('secret'));
277
+            $splittedToken = explode(':', $token);
278
+            if ((count($splittedToken)) === 2 && $splittedToken[0] > ($this->timeFactory->getTime() - 60 * 5)) {
279
+                throw new \Exception(
280
+                    $this->l10n->t('The email is not sent because a password reset email was sent recently.')
281
+                );
282
+            }
283
+        }
284
+
285
+        // Generate the token. It is stored encrypted in the database with the
286
+        // secret being the users' email address appended with the system secret.
287
+        // This makes the token automatically invalidate once the user changes
288
+        // their email address.
289
+        $token = $this->secureRandom->generate(
290
+            21,
291
+            ISecureRandom::CHAR_DIGITS.
292
+            ISecureRandom::CHAR_LOWER.
293
+            ISecureRandom::CHAR_UPPER
294
+        );
295
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
296
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
297
+        $this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
298
+
299
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
300
+
301
+        $tmpl = new \OC_Template('core', 'lostpassword/email');
302
+        $tmpl->assign('link', $link);
303
+        $msg = $tmpl->fetchPage();
304
+
305
+        try {
306
+            $message = $this->mailer->createMessage();
307
+            $message->setTo([$email => $user]);
308
+            $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
309
+            $message->setPlainBody($msg);
310
+            $message->setFrom([$this->from => $this->defaults->getName()]);
311
+            $this->mailer->send($message);
312
+        } catch (\Exception $e) {
313
+            throw new \Exception($this->l10n->t(
314
+                'Couldn\'t send reset email. Please contact your administrator.'
315
+            ));
316
+        }
317
+    }
318 318
 
319 319
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 */
159 159
 	protected function checkPasswordResetToken($token, $userId) {
160 160
 		$user = $this->userManager->get($userId);
161
-		if($user === null) {
161
+		if ($user === null) {
162 162
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
163 163
 		}
164 164
 
@@ -171,11 +171,11 @@  discard block
 block discarded – undo
171 171
 		}
172 172
 
173 173
 		$splittedToken = explode(':', $decryptedToken);
174
-		if(count($splittedToken) !== 2) {
174
+		if (count($splittedToken) !== 2) {
175 175
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
176 176
 		}
177 177
 
178
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
178
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
179 179
 			$user->getLastLogin() > $splittedToken[0]) {
180 180
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
181 181
 		}
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 	 * @param array $additional
191 191
 	 * @return array
192 192
 	 */
193
-	private function error($message, array $additional=array()) {
193
+	private function error($message, array $additional = array()) {
194 194
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
195 195
 	}
196 196
 
@@ -208,11 +208,11 @@  discard block
 block discarded – undo
208 208
 	 * @param string $user
209 209
 	 * @return array
210 210
 	 */
211
-	public function email($user){
211
+	public function email($user) {
212 212
 		// FIXME: use HTTP error codes
213 213
 		try {
214 214
 			$this->sendEmail($user);
215
-		} catch (\Exception $e){
215
+		} catch (\Exception $e) {
216 216
 			return $this->error($e->getMessage());
217 217
 		}
218 218
 
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 
247 247
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
248 248
 			@\OC_User::unsetMagicInCookie();
249
-		} catch (\Exception $e){
249
+		} catch (\Exception $e) {
250 250
 			return $this->error($e->getMessage());
251 251
 		}
252 252
 
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 			ISecureRandom::CHAR_LOWER.
293 293
 			ISecureRandom::CHAR_UPPER
294 294
 		);
295
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
295
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
296 296
 		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
297 297
 		$this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
298 298
 
Please login to merge, or discard this patch.