Completed
Pull Request — master (#5855)
by Morris
44:58 queued 29:58
created
lib/private/legacy/user.php 1 patch
Indentation   +495 added lines, -495 removed lines patch added patch discarded remove patch
@@ -57,499 +57,499 @@
 block discarded – undo
57 57
  */
58 58
 class OC_User {
59 59
 
60
-	/**
61
-	 * @return \OC\User\Session
62
-	 */
63
-	public static function getUserSession() {
64
-		return OC::$server->getUserSession();
65
-	}
66
-
67
-	private static $_usedBackends = array();
68
-
69
-	private static $_setupedBackends = array();
70
-
71
-	// bool, stores if a user want to access a resource anonymously, e.g if they open a public link
72
-	private static $incognitoMode = false;
73
-
74
-	/**
75
-	 * Adds the backend to the list of used backends
76
-	 *
77
-	 * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
78
-	 * @return bool
79
-	 *
80
-	 * Set the User Authentication Module
81
-	 */
82
-	public static function useBackend($backend = 'database') {
83
-		if ($backend instanceof \OCP\UserInterface) {
84
-			self::$_usedBackends[get_class($backend)] = $backend;
85
-			\OC::$server->getUserManager()->registerBackend($backend);
86
-		} else {
87
-			// You'll never know what happens
88
-			if (null === $backend OR !is_string($backend)) {
89
-				$backend = 'database';
90
-			}
91
-
92
-			// Load backend
93
-			switch ($backend) {
94
-				case 'database':
95
-				case 'mysql':
96
-				case 'sqlite':
97
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
98
-					self::$_usedBackends[$backend] = new \OC\User\Database();
99
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
100
-					break;
101
-				case 'dummy':
102
-					self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
103
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
104
-					break;
105
-				default:
106
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
107
-					$className = 'OC_USER_' . strtoupper($backend);
108
-					self::$_usedBackends[$backend] = new $className();
109
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
110
-					break;
111
-			}
112
-		}
113
-		return true;
114
-	}
115
-
116
-	/**
117
-	 * remove all used backends
118
-	 */
119
-	public static function clearBackends() {
120
-		self::$_usedBackends = array();
121
-		\OC::$server->getUserManager()->clearBackends();
122
-	}
123
-
124
-	/**
125
-	 * setup the configured backends in config.php
126
-	 */
127
-	public static function setupBackends() {
128
-		OC_App::loadApps(['prelogin']);
129
-		$backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
130
-		if (isset($backends['default']) && !$backends['default']) {
131
-			// clear default backends
132
-			self::clearBackends();
133
-		}
134
-		foreach ($backends as $i => $config) {
135
-			if (!is_array($config)) {
136
-				continue;
137
-			}
138
-			$class = $config['class'];
139
-			$arguments = $config['arguments'];
140
-			if (class_exists($class)) {
141
-				if (array_search($i, self::$_setupedBackends) === false) {
142
-					// make a reflection object
143
-					$reflectionObj = new ReflectionClass($class);
144
-
145
-					// use Reflection to create a new instance, using the $args
146
-					$backend = $reflectionObj->newInstanceArgs($arguments);
147
-					self::useBackend($backend);
148
-					self::$_setupedBackends[] = $i;
149
-				} else {
150
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
151
-				}
152
-			} else {
153
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
154
-			}
155
-		}
156
-	}
157
-
158
-	/**
159
-	 * Try to login a user, assuming authentication
160
-	 * has already happened (e.g. via Single Sign On).
161
-	 *
162
-	 * Log in a user and regenerate a new session.
163
-	 *
164
-	 * @param \OCP\Authentication\IApacheBackend $backend
165
-	 * @return bool
166
-	 */
167
-	public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
168
-
169
-		$uid = $backend->getCurrentUserId();
170
-		$run = true;
171
-		OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
172
-
173
-		if ($uid) {
174
-			if (self::getUser() !== $uid) {
175
-				self::setUserId($uid);
176
-				$setUidAsDisplayName = true;
177
-				if($backend instanceof \OCP\UserInterface
178
-					&& $backend->implementsActions(OC_User_Backend::GET_DISPLAYNAME)) {
179
-
180
-					$backendDisplayName = $backend->getDisplayName($uid);
181
-					if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
182
-						$setUidAsDisplayName = false;
183
-					}
184
-				}
185
-				if($setUidAsDisplayName) {
186
-					self::setDisplayName($uid);
187
-				}
188
-				$userSession = self::getUserSession();
189
-				$userSession->setLoginName($uid);
190
-				$request = OC::$server->getRequest();
191
-				$userSession->createSessionToken($request, $uid, $uid);
192
-				// setup the filesystem
193
-				OC_Util::setupFS($uid);
194
-				// first call the post_login hooks, the login-process needs to be
195
-				// completed before we can safely create the users folder.
196
-				// For example encryption needs to initialize the users keys first
197
-				// before we can create the user folder with the skeleton files
198
-				OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
199
-				//trigger creation of user home and /files folder
200
-				\OC::$server->getUserFolder($uid);
201
-			}
202
-			return true;
203
-		}
204
-		return false;
205
-	}
206
-
207
-	/**
208
-	 * Verify with Apache whether user is authenticated.
209
-	 *
210
-	 * @return boolean|null
211
-	 *          true: authenticated
212
-	 *          false: not authenticated
213
-	 *          null: not handled / no backend available
214
-	 */
215
-	public static function handleApacheAuth() {
216
-		$backend = self::findFirstActiveUsedBackend();
217
-		if ($backend) {
218
-			OC_App::loadApps();
219
-
220
-			//setup extra user backends
221
-			self::setupBackends();
222
-			self::getUserSession()->unsetMagicInCookie();
223
-
224
-			return self::loginWithApache($backend);
225
-		}
226
-
227
-		return null;
228
-	}
229
-
230
-
231
-	/**
232
-	 * Sets user id for session and triggers emit
233
-	 *
234
-	 * @param string $uid
235
-	 */
236
-	public static function setUserId($uid) {
237
-		$userSession = \OC::$server->getUserSession();
238
-		$userManager = \OC::$server->getUserManager();
239
-		if ($user = $userManager->get($uid)) {
240
-			$userSession->setUser($user);
241
-		} else {
242
-			\OC::$server->getSession()->set('user_id', $uid);
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Sets user display name for session
248
-	 *
249
-	 * @param string $uid
250
-	 * @param string $displayName
251
-	 * @return bool Whether the display name could get set
252
-	 */
253
-	public static function setDisplayName($uid, $displayName = null) {
254
-		if (is_null($displayName)) {
255
-			$displayName = $uid;
256
-		}
257
-		$user = \OC::$server->getUserManager()->get($uid);
258
-		if ($user) {
259
-			return $user->setDisplayName($displayName);
260
-		} else {
261
-			return false;
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * Check if the user is logged in, considers also the HTTP basic credentials
267
-	 *
268
-	 * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
269
-	 * @return bool
270
-	 */
271
-	public static function isLoggedIn() {
272
-		return \OC::$server->getUserSession()->isLoggedIn();
273
-	}
274
-
275
-	/**
276
-	 * set incognito mode, e.g. if a user wants to open a public link
277
-	 *
278
-	 * @param bool $status
279
-	 */
280
-	public static function setIncognitoMode($status) {
281
-		self::$incognitoMode = $status;
282
-	}
283
-
284
-	/**
285
-	 * get incognito mode status
286
-	 *
287
-	 * @return bool
288
-	 */
289
-	public static function isIncognitoMode() {
290
-		return self::$incognitoMode;
291
-	}
292
-
293
-	/**
294
-	 * Supplies an attribute to the logout hyperlink. The default behaviour
295
-	 * is to return an href with '?logout=true' appended. However, it can
296
-	 * supply any attribute(s) which are valid for <a>.
297
-	 *
298
-	 * @return string with one or more HTML attributes.
299
-	 */
300
-	public static function getLogoutAttribute() {
301
-		$backend = self::findFirstActiveUsedBackend();
302
-		if ($backend) {
303
-			return $backend->getLogoutAttribute();
304
-		}
305
-
306
-		$logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
307
-			'core.login.logout',
308
-			[
309
-				'requesttoken' => \OCP\Util::callRegister(),
310
-			]
311
-		);
312
-
313
-		return 'href="'.$logoutUrl.'"';
314
-	}
315
-
316
-	/**
317
-	 * Check if the user is an admin user
318
-	 *
319
-	 * @param string $uid uid of the admin
320
-	 * @return bool
321
-	 */
322
-	public static function isAdminUser($uid) {
323
-		$group = \OC::$server->getGroupManager()->get('admin');
324
-		$user = \OC::$server->getUserManager()->get($uid);
325
-		if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
326
-			return true;
327
-		}
328
-		return false;
329
-	}
330
-
331
-
332
-	/**
333
-	 * get the user id of the user currently logged in.
334
-	 *
335
-	 * @return string|bool uid or false
336
-	 */
337
-	public static function getUser() {
338
-		$uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
339
-		if (!is_null($uid) && self::$incognitoMode === false) {
340
-			return $uid;
341
-		} else {
342
-			return false;
343
-		}
344
-	}
345
-
346
-	/**
347
-	 * get the display name of the user currently logged in.
348
-	 *
349
-	 * @param string $uid
350
-	 * @return string uid or false
351
-	 */
352
-	public static function getDisplayName($uid = null) {
353
-		if ($uid) {
354
-			$user = \OC::$server->getUserManager()->get($uid);
355
-			if ($user) {
356
-				return $user->getDisplayName();
357
-			} else {
358
-				return $uid;
359
-			}
360
-		} else {
361
-			$user = self::getUserSession()->getUser();
362
-			if ($user) {
363
-				return $user->getDisplayName();
364
-			} else {
365
-				return false;
366
-			}
367
-		}
368
-	}
369
-
370
-	/**
371
-	 * Set password
372
-	 *
373
-	 * @param string $uid The username
374
-	 * @param string $password The new password
375
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
376
-	 * @return bool
377
-	 *
378
-	 * Change the password of a user
379
-	 */
380
-	public static function setPassword($uid, $password, $recoveryPassword = null) {
381
-		$user = \OC::$server->getUserManager()->get($uid);
382
-		if ($user) {
383
-			return $user->setPassword($password, $recoveryPassword);
384
-		} else {
385
-			return false;
386
-		}
387
-	}
388
-
389
-	/**
390
-	 * Check whether user can change his avatar
391
-	 *
392
-	 * @param string $uid The username
393
-	 * @return bool
394
-	 *
395
-	 * Check whether a specified user can change his avatar
396
-	 */
397
-	public static function canUserChangeAvatar($uid) {
398
-		$user = \OC::$server->getUserManager()->get($uid);
399
-		if ($user) {
400
-			return $user->canChangeAvatar();
401
-		} else {
402
-			return false;
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * Check whether user can change his password
408
-	 *
409
-	 * @param string $uid The username
410
-	 * @return bool
411
-	 *
412
-	 * Check whether a specified user can change his password
413
-	 */
414
-	public static function canUserChangePassword($uid) {
415
-		$user = \OC::$server->getUserManager()->get($uid);
416
-		if ($user) {
417
-			return $user->canChangePassword();
418
-		} else {
419
-			return false;
420
-		}
421
-	}
422
-
423
-	/**
424
-	 * Check whether user can change his display name
425
-	 *
426
-	 * @param string $uid The username
427
-	 * @return bool
428
-	 *
429
-	 * Check whether a specified user can change his display name
430
-	 */
431
-	public static function canUserChangeDisplayName($uid) {
432
-		$user = \OC::$server->getUserManager()->get($uid);
433
-		if ($user) {
434
-			return $user->canChangeDisplayName();
435
-		} else {
436
-			return false;
437
-		}
438
-	}
439
-
440
-	/**
441
-	 * Check if the password is correct
442
-	 *
443
-	 * @param string $uid The username
444
-	 * @param string $password The password
445
-	 * @return string|false user id a string on success, false otherwise
446
-	 *
447
-	 * Check if the password is correct without logging in the user
448
-	 * returns the user id or false
449
-	 */
450
-	public static function checkPassword($uid, $password) {
451
-		$manager = \OC::$server->getUserManager();
452
-		$username = $manager->checkPassword($uid, $password);
453
-		if ($username !== false) {
454
-			return $username->getUID();
455
-		}
456
-		return false;
457
-	}
458
-
459
-	/**
460
-	 * @param string $uid The username
461
-	 * @return string
462
-	 *
463
-	 * returns the path to the users home directory
464
-	 * @deprecated Use \OC::$server->getUserManager->getHome()
465
-	 */
466
-	public static function getHome($uid) {
467
-		$user = \OC::$server->getUserManager()->get($uid);
468
-		if ($user) {
469
-			return $user->getHome();
470
-		} else {
471
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
472
-		}
473
-	}
474
-
475
-	/**
476
-	 * Get a list of all users
477
-	 *
478
-	 * @return array an array of all uids
479
-	 *
480
-	 * Get a list of all users.
481
-	 * @param string $search
482
-	 * @param integer $limit
483
-	 * @param integer $offset
484
-	 */
485
-	public static function getUsers($search = '', $limit = null, $offset = null) {
486
-		$users = \OC::$server->getUserManager()->search($search, $limit, $offset);
487
-		$uids = array();
488
-		foreach ($users as $user) {
489
-			$uids[] = $user->getUID();
490
-		}
491
-		return $uids;
492
-	}
493
-
494
-	/**
495
-	 * Get a list of all users display name
496
-	 *
497
-	 * @param string $search
498
-	 * @param int $limit
499
-	 * @param int $offset
500
-	 * @return array associative array with all display names (value) and corresponding uids (key)
501
-	 *
502
-	 * Get a list of all display names and user ids.
503
-	 * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
504
-	 */
505
-	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
506
-		$displayNames = array();
507
-		$users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
508
-		foreach ($users as $user) {
509
-			$displayNames[$user->getUID()] = $user->getDisplayName();
510
-		}
511
-		return $displayNames;
512
-	}
513
-
514
-	/**
515
-	 * check if a user exists
516
-	 *
517
-	 * @param string $uid the username
518
-	 * @return boolean
519
-	 */
520
-	public static function userExists($uid) {
521
-		return \OC::$server->getUserManager()->userExists($uid);
522
-	}
523
-
524
-	/**
525
-	 * checks if a user is enabled
526
-	 *
527
-	 * @param string $uid
528
-	 * @return bool
529
-	 */
530
-	public static function isEnabled($uid) {
531
-		$user = \OC::$server->getUserManager()->get($uid);
532
-		if ($user) {
533
-			return $user->isEnabled();
534
-		} else {
535
-			return false;
536
-		}
537
-	}
538
-
539
-	/**
540
-	 * Returns the first active backend from self::$_usedBackends.
541
-	 *
542
-	 * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
543
-	 */
544
-	private static function findFirstActiveUsedBackend() {
545
-		foreach (self::$_usedBackends as $backend) {
546
-			if ($backend instanceof OCP\Authentication\IApacheBackend) {
547
-				if ($backend->isSessionActive()) {
548
-					return $backend;
549
-				}
550
-			}
551
-		}
552
-
553
-		return null;
554
-	}
60
+    /**
61
+     * @return \OC\User\Session
62
+     */
63
+    public static function getUserSession() {
64
+        return OC::$server->getUserSession();
65
+    }
66
+
67
+    private static $_usedBackends = array();
68
+
69
+    private static $_setupedBackends = array();
70
+
71
+    // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
72
+    private static $incognitoMode = false;
73
+
74
+    /**
75
+     * Adds the backend to the list of used backends
76
+     *
77
+     * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
78
+     * @return bool
79
+     *
80
+     * Set the User Authentication Module
81
+     */
82
+    public static function useBackend($backend = 'database') {
83
+        if ($backend instanceof \OCP\UserInterface) {
84
+            self::$_usedBackends[get_class($backend)] = $backend;
85
+            \OC::$server->getUserManager()->registerBackend($backend);
86
+        } else {
87
+            // You'll never know what happens
88
+            if (null === $backend OR !is_string($backend)) {
89
+                $backend = 'database';
90
+            }
91
+
92
+            // Load backend
93
+            switch ($backend) {
94
+                case 'database':
95
+                case 'mysql':
96
+                case 'sqlite':
97
+                    \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
98
+                    self::$_usedBackends[$backend] = new \OC\User\Database();
99
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
100
+                    break;
101
+                case 'dummy':
102
+                    self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
103
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
104
+                    break;
105
+                default:
106
+                    \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
107
+                    $className = 'OC_USER_' . strtoupper($backend);
108
+                    self::$_usedBackends[$backend] = new $className();
109
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
110
+                    break;
111
+            }
112
+        }
113
+        return true;
114
+    }
115
+
116
+    /**
117
+     * remove all used backends
118
+     */
119
+    public static function clearBackends() {
120
+        self::$_usedBackends = array();
121
+        \OC::$server->getUserManager()->clearBackends();
122
+    }
123
+
124
+    /**
125
+     * setup the configured backends in config.php
126
+     */
127
+    public static function setupBackends() {
128
+        OC_App::loadApps(['prelogin']);
129
+        $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
130
+        if (isset($backends['default']) && !$backends['default']) {
131
+            // clear default backends
132
+            self::clearBackends();
133
+        }
134
+        foreach ($backends as $i => $config) {
135
+            if (!is_array($config)) {
136
+                continue;
137
+            }
138
+            $class = $config['class'];
139
+            $arguments = $config['arguments'];
140
+            if (class_exists($class)) {
141
+                if (array_search($i, self::$_setupedBackends) === false) {
142
+                    // make a reflection object
143
+                    $reflectionObj = new ReflectionClass($class);
144
+
145
+                    // use Reflection to create a new instance, using the $args
146
+                    $backend = $reflectionObj->newInstanceArgs($arguments);
147
+                    self::useBackend($backend);
148
+                    self::$_setupedBackends[] = $i;
149
+                } else {
150
+                    \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
151
+                }
152
+            } else {
153
+                \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
154
+            }
155
+        }
156
+    }
157
+
158
+    /**
159
+     * Try to login a user, assuming authentication
160
+     * has already happened (e.g. via Single Sign On).
161
+     *
162
+     * Log in a user and regenerate a new session.
163
+     *
164
+     * @param \OCP\Authentication\IApacheBackend $backend
165
+     * @return bool
166
+     */
167
+    public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
168
+
169
+        $uid = $backend->getCurrentUserId();
170
+        $run = true;
171
+        OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
172
+
173
+        if ($uid) {
174
+            if (self::getUser() !== $uid) {
175
+                self::setUserId($uid);
176
+                $setUidAsDisplayName = true;
177
+                if($backend instanceof \OCP\UserInterface
178
+                    && $backend->implementsActions(OC_User_Backend::GET_DISPLAYNAME)) {
179
+
180
+                    $backendDisplayName = $backend->getDisplayName($uid);
181
+                    if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
182
+                        $setUidAsDisplayName = false;
183
+                    }
184
+                }
185
+                if($setUidAsDisplayName) {
186
+                    self::setDisplayName($uid);
187
+                }
188
+                $userSession = self::getUserSession();
189
+                $userSession->setLoginName($uid);
190
+                $request = OC::$server->getRequest();
191
+                $userSession->createSessionToken($request, $uid, $uid);
192
+                // setup the filesystem
193
+                OC_Util::setupFS($uid);
194
+                // first call the post_login hooks, the login-process needs to be
195
+                // completed before we can safely create the users folder.
196
+                // For example encryption needs to initialize the users keys first
197
+                // before we can create the user folder with the skeleton files
198
+                OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
199
+                //trigger creation of user home and /files folder
200
+                \OC::$server->getUserFolder($uid);
201
+            }
202
+            return true;
203
+        }
204
+        return false;
205
+    }
206
+
207
+    /**
208
+     * Verify with Apache whether user is authenticated.
209
+     *
210
+     * @return boolean|null
211
+     *          true: authenticated
212
+     *          false: not authenticated
213
+     *          null: not handled / no backend available
214
+     */
215
+    public static function handleApacheAuth() {
216
+        $backend = self::findFirstActiveUsedBackend();
217
+        if ($backend) {
218
+            OC_App::loadApps();
219
+
220
+            //setup extra user backends
221
+            self::setupBackends();
222
+            self::getUserSession()->unsetMagicInCookie();
223
+
224
+            return self::loginWithApache($backend);
225
+        }
226
+
227
+        return null;
228
+    }
229
+
230
+
231
+    /**
232
+     * Sets user id for session and triggers emit
233
+     *
234
+     * @param string $uid
235
+     */
236
+    public static function setUserId($uid) {
237
+        $userSession = \OC::$server->getUserSession();
238
+        $userManager = \OC::$server->getUserManager();
239
+        if ($user = $userManager->get($uid)) {
240
+            $userSession->setUser($user);
241
+        } else {
242
+            \OC::$server->getSession()->set('user_id', $uid);
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Sets user display name for session
248
+     *
249
+     * @param string $uid
250
+     * @param string $displayName
251
+     * @return bool Whether the display name could get set
252
+     */
253
+    public static function setDisplayName($uid, $displayName = null) {
254
+        if (is_null($displayName)) {
255
+            $displayName = $uid;
256
+        }
257
+        $user = \OC::$server->getUserManager()->get($uid);
258
+        if ($user) {
259
+            return $user->setDisplayName($displayName);
260
+        } else {
261
+            return false;
262
+        }
263
+    }
264
+
265
+    /**
266
+     * Check if the user is logged in, considers also the HTTP basic credentials
267
+     *
268
+     * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
269
+     * @return bool
270
+     */
271
+    public static function isLoggedIn() {
272
+        return \OC::$server->getUserSession()->isLoggedIn();
273
+    }
274
+
275
+    /**
276
+     * set incognito mode, e.g. if a user wants to open a public link
277
+     *
278
+     * @param bool $status
279
+     */
280
+    public static function setIncognitoMode($status) {
281
+        self::$incognitoMode = $status;
282
+    }
283
+
284
+    /**
285
+     * get incognito mode status
286
+     *
287
+     * @return bool
288
+     */
289
+    public static function isIncognitoMode() {
290
+        return self::$incognitoMode;
291
+    }
292
+
293
+    /**
294
+     * Supplies an attribute to the logout hyperlink. The default behaviour
295
+     * is to return an href with '?logout=true' appended. However, it can
296
+     * supply any attribute(s) which are valid for <a>.
297
+     *
298
+     * @return string with one or more HTML attributes.
299
+     */
300
+    public static function getLogoutAttribute() {
301
+        $backend = self::findFirstActiveUsedBackend();
302
+        if ($backend) {
303
+            return $backend->getLogoutAttribute();
304
+        }
305
+
306
+        $logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
307
+            'core.login.logout',
308
+            [
309
+                'requesttoken' => \OCP\Util::callRegister(),
310
+            ]
311
+        );
312
+
313
+        return 'href="'.$logoutUrl.'"';
314
+    }
315
+
316
+    /**
317
+     * Check if the user is an admin user
318
+     *
319
+     * @param string $uid uid of the admin
320
+     * @return bool
321
+     */
322
+    public static function isAdminUser($uid) {
323
+        $group = \OC::$server->getGroupManager()->get('admin');
324
+        $user = \OC::$server->getUserManager()->get($uid);
325
+        if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
326
+            return true;
327
+        }
328
+        return false;
329
+    }
330
+
331
+
332
+    /**
333
+     * get the user id of the user currently logged in.
334
+     *
335
+     * @return string|bool uid or false
336
+     */
337
+    public static function getUser() {
338
+        $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
339
+        if (!is_null($uid) && self::$incognitoMode === false) {
340
+            return $uid;
341
+        } else {
342
+            return false;
343
+        }
344
+    }
345
+
346
+    /**
347
+     * get the display name of the user currently logged in.
348
+     *
349
+     * @param string $uid
350
+     * @return string uid or false
351
+     */
352
+    public static function getDisplayName($uid = null) {
353
+        if ($uid) {
354
+            $user = \OC::$server->getUserManager()->get($uid);
355
+            if ($user) {
356
+                return $user->getDisplayName();
357
+            } else {
358
+                return $uid;
359
+            }
360
+        } else {
361
+            $user = self::getUserSession()->getUser();
362
+            if ($user) {
363
+                return $user->getDisplayName();
364
+            } else {
365
+                return false;
366
+            }
367
+        }
368
+    }
369
+
370
+    /**
371
+     * Set password
372
+     *
373
+     * @param string $uid The username
374
+     * @param string $password The new password
375
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
376
+     * @return bool
377
+     *
378
+     * Change the password of a user
379
+     */
380
+    public static function setPassword($uid, $password, $recoveryPassword = null) {
381
+        $user = \OC::$server->getUserManager()->get($uid);
382
+        if ($user) {
383
+            return $user->setPassword($password, $recoveryPassword);
384
+        } else {
385
+            return false;
386
+        }
387
+    }
388
+
389
+    /**
390
+     * Check whether user can change his avatar
391
+     *
392
+     * @param string $uid The username
393
+     * @return bool
394
+     *
395
+     * Check whether a specified user can change his avatar
396
+     */
397
+    public static function canUserChangeAvatar($uid) {
398
+        $user = \OC::$server->getUserManager()->get($uid);
399
+        if ($user) {
400
+            return $user->canChangeAvatar();
401
+        } else {
402
+            return false;
403
+        }
404
+    }
405
+
406
+    /**
407
+     * Check whether user can change his password
408
+     *
409
+     * @param string $uid The username
410
+     * @return bool
411
+     *
412
+     * Check whether a specified user can change his password
413
+     */
414
+    public static function canUserChangePassword($uid) {
415
+        $user = \OC::$server->getUserManager()->get($uid);
416
+        if ($user) {
417
+            return $user->canChangePassword();
418
+        } else {
419
+            return false;
420
+        }
421
+    }
422
+
423
+    /**
424
+     * Check whether user can change his display name
425
+     *
426
+     * @param string $uid The username
427
+     * @return bool
428
+     *
429
+     * Check whether a specified user can change his display name
430
+     */
431
+    public static function canUserChangeDisplayName($uid) {
432
+        $user = \OC::$server->getUserManager()->get($uid);
433
+        if ($user) {
434
+            return $user->canChangeDisplayName();
435
+        } else {
436
+            return false;
437
+        }
438
+    }
439
+
440
+    /**
441
+     * Check if the password is correct
442
+     *
443
+     * @param string $uid The username
444
+     * @param string $password The password
445
+     * @return string|false user id a string on success, false otherwise
446
+     *
447
+     * Check if the password is correct without logging in the user
448
+     * returns the user id or false
449
+     */
450
+    public static function checkPassword($uid, $password) {
451
+        $manager = \OC::$server->getUserManager();
452
+        $username = $manager->checkPassword($uid, $password);
453
+        if ($username !== false) {
454
+            return $username->getUID();
455
+        }
456
+        return false;
457
+    }
458
+
459
+    /**
460
+     * @param string $uid The username
461
+     * @return string
462
+     *
463
+     * returns the path to the users home directory
464
+     * @deprecated Use \OC::$server->getUserManager->getHome()
465
+     */
466
+    public static function getHome($uid) {
467
+        $user = \OC::$server->getUserManager()->get($uid);
468
+        if ($user) {
469
+            return $user->getHome();
470
+        } else {
471
+            return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
472
+        }
473
+    }
474
+
475
+    /**
476
+     * Get a list of all users
477
+     *
478
+     * @return array an array of all uids
479
+     *
480
+     * Get a list of all users.
481
+     * @param string $search
482
+     * @param integer $limit
483
+     * @param integer $offset
484
+     */
485
+    public static function getUsers($search = '', $limit = null, $offset = null) {
486
+        $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
487
+        $uids = array();
488
+        foreach ($users as $user) {
489
+            $uids[] = $user->getUID();
490
+        }
491
+        return $uids;
492
+    }
493
+
494
+    /**
495
+     * Get a list of all users display name
496
+     *
497
+     * @param string $search
498
+     * @param int $limit
499
+     * @param int $offset
500
+     * @return array associative array with all display names (value) and corresponding uids (key)
501
+     *
502
+     * Get a list of all display names and user ids.
503
+     * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
504
+     */
505
+    public static function getDisplayNames($search = '', $limit = null, $offset = null) {
506
+        $displayNames = array();
507
+        $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
508
+        foreach ($users as $user) {
509
+            $displayNames[$user->getUID()] = $user->getDisplayName();
510
+        }
511
+        return $displayNames;
512
+    }
513
+
514
+    /**
515
+     * check if a user exists
516
+     *
517
+     * @param string $uid the username
518
+     * @return boolean
519
+     */
520
+    public static function userExists($uid) {
521
+        return \OC::$server->getUserManager()->userExists($uid);
522
+    }
523
+
524
+    /**
525
+     * checks if a user is enabled
526
+     *
527
+     * @param string $uid
528
+     * @return bool
529
+     */
530
+    public static function isEnabled($uid) {
531
+        $user = \OC::$server->getUserManager()->get($uid);
532
+        if ($user) {
533
+            return $user->isEnabled();
534
+        } else {
535
+            return false;
536
+        }
537
+    }
538
+
539
+    /**
540
+     * Returns the first active backend from self::$_usedBackends.
541
+     *
542
+     * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
543
+     */
544
+    private static function findFirstActiveUsedBackend() {
545
+        foreach (self::$_usedBackends as $backend) {
546
+            if ($backend instanceof OCP\Authentication\IApacheBackend) {
547
+                if ($backend->isSessionActive()) {
548
+                    return $backend;
549
+                }
550
+            }
551
+        }
552
+
553
+        return null;
554
+    }
555 555
 }
Please login to merge, or discard this patch.
core/Controller/LostController.php 2 patches
Indentation   +299 added lines, -299 removed lines patch added patch discarded remove patch
@@ -55,303 +55,303 @@
 block discarded – undo
55 55
  */
56 56
 class LostController extends Controller {
57 57
 
58
-	/** @var IURLGenerator */
59
-	protected $urlGenerator;
60
-	/** @var IUserManager */
61
-	protected $userManager;
62
-	/** @var Defaults */
63
-	protected $defaults;
64
-	/** @var IL10N */
65
-	protected $l10n;
66
-	/** @var string */
67
-	protected $from;
68
-	/** @var IManager */
69
-	protected $encryptionManager;
70
-	/** @var IConfig */
71
-	protected $config;
72
-	/** @var ISecureRandom */
73
-	protected $secureRandom;
74
-	/** @var IMailer */
75
-	protected $mailer;
76
-	/** @var ITimeFactory */
77
-	protected $timeFactory;
78
-	/** @var ICrypto */
79
-	protected $crypto;
80
-
81
-	/**
82
-	 * @param string $appName
83
-	 * @param IRequest $request
84
-	 * @param IURLGenerator $urlGenerator
85
-	 * @param IUserManager $userManager
86
-	 * @param Defaults $defaults
87
-	 * @param IL10N $l10n
88
-	 * @param IConfig $config
89
-	 * @param ISecureRandom $secureRandom
90
-	 * @param string $defaultMailAddress
91
-	 * @param IManager $encryptionManager
92
-	 * @param IMailer $mailer
93
-	 * @param ITimeFactory $timeFactory
94
-	 * @param ICrypto $crypto
95
-	 */
96
-	public function __construct($appName,
97
-								IRequest $request,
98
-								IURLGenerator $urlGenerator,
99
-								IUserManager $userManager,
100
-								Defaults $defaults,
101
-								IL10N $l10n,
102
-								IConfig $config,
103
-								ISecureRandom $secureRandom,
104
-								$defaultMailAddress,
105
-								IManager $encryptionManager,
106
-								IMailer $mailer,
107
-								ITimeFactory $timeFactory,
108
-								ICrypto $crypto) {
109
-		parent::__construct($appName, $request);
110
-		$this->urlGenerator = $urlGenerator;
111
-		$this->userManager = $userManager;
112
-		$this->defaults = $defaults;
113
-		$this->l10n = $l10n;
114
-		$this->secureRandom = $secureRandom;
115
-		$this->from = $defaultMailAddress;
116
-		$this->encryptionManager = $encryptionManager;
117
-		$this->config = $config;
118
-		$this->mailer = $mailer;
119
-		$this->timeFactory = $timeFactory;
120
-		$this->crypto = $crypto;
121
-	}
122
-
123
-	/**
124
-	 * Someone wants to reset their password:
125
-	 *
126
-	 * @PublicPage
127
-	 * @NoCSRFRequired
128
-	 *
129
-	 * @param string $token
130
-	 * @param string $userId
131
-	 * @return TemplateResponse
132
-	 */
133
-	public function resetform($token, $userId) {
134
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
135
-			return new TemplateResponse('core', 'error', [
136
-					'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
137
-				],
138
-				'guest'
139
-			);
140
-		}
141
-
142
-		try {
143
-			$this->checkPasswordResetToken($token, $userId);
144
-		} catch (\Exception $e) {
145
-			return new TemplateResponse(
146
-				'core', 'error', [
147
-					"errors" => array(array("error" => $e->getMessage()))
148
-				],
149
-				'guest'
150
-			);
151
-		}
152
-
153
-		return new TemplateResponse(
154
-			'core',
155
-			'lostpassword/resetpassword',
156
-			array(
157
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
158
-			),
159
-			'guest'
160
-		);
161
-	}
162
-
163
-	/**
164
-	 * @param string $token
165
-	 * @param string $userId
166
-	 * @throws \Exception
167
-	 */
168
-	protected function checkPasswordResetToken($token, $userId) {
169
-		$user = $this->userManager->get($userId);
170
-		if($user === null) {
171
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172
-		}
173
-
174
-		try {
175
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
176
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
177
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
178
-		} catch (\Exception $e) {
179
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
180
-		}
181
-
182
-		$splittedToken = explode(':', $decryptedToken);
183
-		if(count($splittedToken) !== 2) {
184
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185
-		}
186
-
187
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
188
-			$user->getLastLogin() > $splittedToken[0]) {
189
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190
-		}
191
-
192
-		if (!hash_equals($splittedToken[1], $token)) {
193
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
194
-		}
195
-	}
196
-
197
-	/**
198
-	 * @param $message
199
-	 * @param array $additional
200
-	 * @return array
201
-	 */
202
-	private function error($message, array $additional=array()) {
203
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204
-	}
205
-
206
-	/**
207
-	 * @return array
208
-	 */
209
-	private function success() {
210
-		return array('status'=>'success');
211
-	}
212
-
213
-	/**
214
-	 * @PublicPage
215
-	 * @BruteForceProtection(action=passwordResetEmail)
216
-	 * @AnonRateThrottle(limit=10, period=300)
217
-	 *
218
-	 * @param string $user
219
-	 * @return JSONResponse
220
-	 */
221
-	public function email($user){
222
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223
-			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224
-		}
225
-
226
-		// FIXME: use HTTP error codes
227
-		try {
228
-			$this->sendEmail($user);
229
-		} catch (\Exception $e){
230
-			$response = new JSONResponse($this->error($e->getMessage()));
231
-			$response->throttle();
232
-			return $response;
233
-		}
234
-
235
-		$response = new JSONResponse($this->success());
236
-		$response->throttle();
237
-		return $response;
238
-	}
239
-
240
-	/**
241
-	 * @PublicPage
242
-	 * @param string $token
243
-	 * @param string $userId
244
-	 * @param string $password
245
-	 * @param boolean $proceed
246
-	 * @return array
247
-	 */
248
-	public function setPassword($token, $userId, $password, $proceed) {
249
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
250
-			return $this->error($this->l10n->t('Password reset is disabled'));
251
-		}
252
-
253
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
254
-			return $this->error('', array('encryption' => true));
255
-		}
256
-
257
-		try {
258
-			$this->checkPasswordResetToken($token, $userId);
259
-			$user = $this->userManager->get($userId);
260
-
261
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
262
-
263
-			if (!$user->setPassword($password)) {
264
-				throw new \Exception();
265
-			}
266
-
267
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
268
-
269
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
270
-			@\OC::$server->getUserSession()->unsetMagicInCookie();
271
-		} catch (\Exception $e){
272
-			return $this->error($e->getMessage());
273
-		}
274
-
275
-		return $this->success();
276
-	}
277
-
278
-	/**
279
-	 * @param string $input
280
-	 * @throws \Exception
281
-	 */
282
-	protected function sendEmail($input) {
283
-		$user = $this->findUserByIdOrMail($input);
284
-		$email = $user->getEMailAddress();
285
-
286
-		if (empty($email)) {
287
-			throw new \Exception(
288
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
289
-			);
290
-		}
291
-
292
-		// Generate the token. It is stored encrypted in the database with the
293
-		// secret being the users' email address appended with the system secret.
294
-		// This makes the token automatically invalidate once the user changes
295
-		// their email address.
296
-		$token = $this->secureRandom->generate(
297
-			21,
298
-			ISecureRandom::CHAR_DIGITS.
299
-			ISecureRandom::CHAR_LOWER.
300
-			ISecureRandom::CHAR_UPPER
301
-		);
302
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
303
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
304
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305
-
306
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
307
-
308
-		$emailTemplate = $this->mailer->createEMailTemplate();
309
-
310
-		$emailTemplate->addHeader();
311
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
312
-
313
-		$emailTemplate->addBodyText(
314
-			$this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
315
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
316
-		);
317
-
318
-		$emailTemplate->addBodyButton(
319
-			$this->l10n->t('Reset your password'),
320
-			$link,
321
-			false
322
-		);
323
-		$emailTemplate->addFooter();
324
-
325
-		try {
326
-			$message = $this->mailer->createMessage();
327
-			$message->setTo([$email => $user->getUID()]);
328
-			$message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
329
-			$message->setPlainBody($emailTemplate->renderText());
330
-			$message->setHtmlBody($emailTemplate->renderHtml());
331
-			$message->setFrom([$this->from => $this->defaults->getName()]);
332
-			$this->mailer->send($message);
333
-		} catch (\Exception $e) {
334
-			throw new \Exception($this->l10n->t(
335
-				'Couldn\'t send reset email. Please contact your administrator.'
336
-			));
337
-		}
338
-	}
339
-
340
-	/**
341
-	 * @param string $input
342
-	 * @return IUser
343
-	 * @throws \Exception
344
-	 */
345
-	protected function findUserByIdOrMail($input) {
346
-		$user = $this->userManager->get($input);
347
-		if ($user instanceof IUser) {
348
-			return $user;
349
-		}
350
-		$users = $this->userManager->getByEmail($input);
351
-		if (count($users) === 1) {
352
-			return $users[0];
353
-		}
354
-
355
-		throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
356
-	}
58
+    /** @var IURLGenerator */
59
+    protected $urlGenerator;
60
+    /** @var IUserManager */
61
+    protected $userManager;
62
+    /** @var Defaults */
63
+    protected $defaults;
64
+    /** @var IL10N */
65
+    protected $l10n;
66
+    /** @var string */
67
+    protected $from;
68
+    /** @var IManager */
69
+    protected $encryptionManager;
70
+    /** @var IConfig */
71
+    protected $config;
72
+    /** @var ISecureRandom */
73
+    protected $secureRandom;
74
+    /** @var IMailer */
75
+    protected $mailer;
76
+    /** @var ITimeFactory */
77
+    protected $timeFactory;
78
+    /** @var ICrypto */
79
+    protected $crypto;
80
+
81
+    /**
82
+     * @param string $appName
83
+     * @param IRequest $request
84
+     * @param IURLGenerator $urlGenerator
85
+     * @param IUserManager $userManager
86
+     * @param Defaults $defaults
87
+     * @param IL10N $l10n
88
+     * @param IConfig $config
89
+     * @param ISecureRandom $secureRandom
90
+     * @param string $defaultMailAddress
91
+     * @param IManager $encryptionManager
92
+     * @param IMailer $mailer
93
+     * @param ITimeFactory $timeFactory
94
+     * @param ICrypto $crypto
95
+     */
96
+    public function __construct($appName,
97
+                                IRequest $request,
98
+                                IURLGenerator $urlGenerator,
99
+                                IUserManager $userManager,
100
+                                Defaults $defaults,
101
+                                IL10N $l10n,
102
+                                IConfig $config,
103
+                                ISecureRandom $secureRandom,
104
+                                $defaultMailAddress,
105
+                                IManager $encryptionManager,
106
+                                IMailer $mailer,
107
+                                ITimeFactory $timeFactory,
108
+                                ICrypto $crypto) {
109
+        parent::__construct($appName, $request);
110
+        $this->urlGenerator = $urlGenerator;
111
+        $this->userManager = $userManager;
112
+        $this->defaults = $defaults;
113
+        $this->l10n = $l10n;
114
+        $this->secureRandom = $secureRandom;
115
+        $this->from = $defaultMailAddress;
116
+        $this->encryptionManager = $encryptionManager;
117
+        $this->config = $config;
118
+        $this->mailer = $mailer;
119
+        $this->timeFactory = $timeFactory;
120
+        $this->crypto = $crypto;
121
+    }
122
+
123
+    /**
124
+     * Someone wants to reset their password:
125
+     *
126
+     * @PublicPage
127
+     * @NoCSRFRequired
128
+     *
129
+     * @param string $token
130
+     * @param string $userId
131
+     * @return TemplateResponse
132
+     */
133
+    public function resetform($token, $userId) {
134
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
135
+            return new TemplateResponse('core', 'error', [
136
+                    'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
137
+                ],
138
+                'guest'
139
+            );
140
+        }
141
+
142
+        try {
143
+            $this->checkPasswordResetToken($token, $userId);
144
+        } catch (\Exception $e) {
145
+            return new TemplateResponse(
146
+                'core', 'error', [
147
+                    "errors" => array(array("error" => $e->getMessage()))
148
+                ],
149
+                'guest'
150
+            );
151
+        }
152
+
153
+        return new TemplateResponse(
154
+            'core',
155
+            'lostpassword/resetpassword',
156
+            array(
157
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
158
+            ),
159
+            'guest'
160
+        );
161
+    }
162
+
163
+    /**
164
+     * @param string $token
165
+     * @param string $userId
166
+     * @throws \Exception
167
+     */
168
+    protected function checkPasswordResetToken($token, $userId) {
169
+        $user = $this->userManager->get($userId);
170
+        if($user === null) {
171
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172
+        }
173
+
174
+        try {
175
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
176
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
177
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
178
+        } catch (\Exception $e) {
179
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
180
+        }
181
+
182
+        $splittedToken = explode(':', $decryptedToken);
183
+        if(count($splittedToken) !== 2) {
184
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185
+        }
186
+
187
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
188
+            $user->getLastLogin() > $splittedToken[0]) {
189
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190
+        }
191
+
192
+        if (!hash_equals($splittedToken[1], $token)) {
193
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
194
+        }
195
+    }
196
+
197
+    /**
198
+     * @param $message
199
+     * @param array $additional
200
+     * @return array
201
+     */
202
+    private function error($message, array $additional=array()) {
203
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204
+    }
205
+
206
+    /**
207
+     * @return array
208
+     */
209
+    private function success() {
210
+        return array('status'=>'success');
211
+    }
212
+
213
+    /**
214
+     * @PublicPage
215
+     * @BruteForceProtection(action=passwordResetEmail)
216
+     * @AnonRateThrottle(limit=10, period=300)
217
+     *
218
+     * @param string $user
219
+     * @return JSONResponse
220
+     */
221
+    public function email($user){
222
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223
+            return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224
+        }
225
+
226
+        // FIXME: use HTTP error codes
227
+        try {
228
+            $this->sendEmail($user);
229
+        } catch (\Exception $e){
230
+            $response = new JSONResponse($this->error($e->getMessage()));
231
+            $response->throttle();
232
+            return $response;
233
+        }
234
+
235
+        $response = new JSONResponse($this->success());
236
+        $response->throttle();
237
+        return $response;
238
+    }
239
+
240
+    /**
241
+     * @PublicPage
242
+     * @param string $token
243
+     * @param string $userId
244
+     * @param string $password
245
+     * @param boolean $proceed
246
+     * @return array
247
+     */
248
+    public function setPassword($token, $userId, $password, $proceed) {
249
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
250
+            return $this->error($this->l10n->t('Password reset is disabled'));
251
+        }
252
+
253
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
254
+            return $this->error('', array('encryption' => true));
255
+        }
256
+
257
+        try {
258
+            $this->checkPasswordResetToken($token, $userId);
259
+            $user = $this->userManager->get($userId);
260
+
261
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
262
+
263
+            if (!$user->setPassword($password)) {
264
+                throw new \Exception();
265
+            }
266
+
267
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
268
+
269
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
270
+            @\OC::$server->getUserSession()->unsetMagicInCookie();
271
+        } catch (\Exception $e){
272
+            return $this->error($e->getMessage());
273
+        }
274
+
275
+        return $this->success();
276
+    }
277
+
278
+    /**
279
+     * @param string $input
280
+     * @throws \Exception
281
+     */
282
+    protected function sendEmail($input) {
283
+        $user = $this->findUserByIdOrMail($input);
284
+        $email = $user->getEMailAddress();
285
+
286
+        if (empty($email)) {
287
+            throw new \Exception(
288
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
289
+            );
290
+        }
291
+
292
+        // Generate the token. It is stored encrypted in the database with the
293
+        // secret being the users' email address appended with the system secret.
294
+        // This makes the token automatically invalidate once the user changes
295
+        // their email address.
296
+        $token = $this->secureRandom->generate(
297
+            21,
298
+            ISecureRandom::CHAR_DIGITS.
299
+            ISecureRandom::CHAR_LOWER.
300
+            ISecureRandom::CHAR_UPPER
301
+        );
302
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
303
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
304
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305
+
306
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
307
+
308
+        $emailTemplate = $this->mailer->createEMailTemplate();
309
+
310
+        $emailTemplate->addHeader();
311
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
312
+
313
+        $emailTemplate->addBodyText(
314
+            $this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
315
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
316
+        );
317
+
318
+        $emailTemplate->addBodyButton(
319
+            $this->l10n->t('Reset your password'),
320
+            $link,
321
+            false
322
+        );
323
+        $emailTemplate->addFooter();
324
+
325
+        try {
326
+            $message = $this->mailer->createMessage();
327
+            $message->setTo([$email => $user->getUID()]);
328
+            $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
329
+            $message->setPlainBody($emailTemplate->renderText());
330
+            $message->setHtmlBody($emailTemplate->renderHtml());
331
+            $message->setFrom([$this->from => $this->defaults->getName()]);
332
+            $this->mailer->send($message);
333
+        } catch (\Exception $e) {
334
+            throw new \Exception($this->l10n->t(
335
+                'Couldn\'t send reset email. Please contact your administrator.'
336
+            ));
337
+        }
338
+    }
339
+
340
+    /**
341
+     * @param string $input
342
+     * @return IUser
343
+     * @throws \Exception
344
+     */
345
+    protected function findUserByIdOrMail($input) {
346
+        $user = $this->userManager->get($input);
347
+        if ($user instanceof IUser) {
348
+            return $user;
349
+        }
350
+        $users = $this->userManager->getByEmail($input);
351
+        if (count($users) === 1) {
352
+            return $users[0];
353
+        }
354
+
355
+        throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
356
+    }
357 357
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 */
168 168
 	protected function checkPasswordResetToken($token, $userId) {
169 169
 		$user = $this->userManager->get($userId);
170
-		if($user === null) {
170
+		if ($user === null) {
171 171
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172 172
 		}
173 173
 
@@ -180,11 +180,11 @@  discard block
 block discarded – undo
180 180
 		}
181 181
 
182 182
 		$splittedToken = explode(':', $decryptedToken);
183
-		if(count($splittedToken) !== 2) {
183
+		if (count($splittedToken) !== 2) {
184 184
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185 185
 		}
186 186
 
187
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
187
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
188 188
 			$user->getLastLogin() > $splittedToken[0]) {
189 189
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190 190
 		}
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 * @param array $additional
200 200
 	 * @return array
201 201
 	 */
202
-	private function error($message, array $additional=array()) {
202
+	private function error($message, array $additional = array()) {
203 203
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204 204
 	}
205 205
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 * @param string $user
219 219
 	 * @return JSONResponse
220 220
 	 */
221
-	public function email($user){
221
+	public function email($user) {
222 222
 		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223 223
 			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224 224
 		}
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		// FIXME: use HTTP error codes
227 227
 		try {
228 228
 			$this->sendEmail($user);
229
-		} catch (\Exception $e){
229
+		} catch (\Exception $e) {
230 230
 			$response = new JSONResponse($this->error($e->getMessage()));
231 231
 			$response->throttle();
232 232
 			return $response;
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 
269 269
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
270 270
 			@\OC::$server->getUserSession()->unsetMagicInCookie();
271
-		} catch (\Exception $e){
271
+		} catch (\Exception $e) {
272 272
 			return $this->error($e->getMessage());
273 273
 		}
274 274
 
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
 			ISecureRandom::CHAR_LOWER.
300 300
 			ISecureRandom::CHAR_UPPER
301 301
 		);
302
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
303
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
302
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
303
+		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
304 304
 		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305 305
 
306 306
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
Please login to merge, or discard this patch.